The GridView ‘gv1′ fired event RowDeleting which wasn’t handled

Hi Friends,

Today, i will discuss about gridview delete command event which returns error sometime like “The GridView ‘gv1′ fired event RowDeleting which wasn’t handled.” and why they return it??

see the below code where I have used delete image button in gridview template field. I have also defined event for OnRowCommand in gridview.



................................
................................
................................
................................









................................
................................
................................
................................



Here is what I am doing in the code-behind:

 protected void gv1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("DELETE"))
        {
           .........
           .........

           Operation related to deleting record from gridview and binding record to gridview

           .........
           .........

        }
    }

I am getting below error after clicking on delete button:
gv_deletee

Here is reason for error :-
I am assuming the delete button is in a datagrid. Since the name is ‘delete’, that’s a reserved name and it will trigger the deleting event.

Solution For This Error :-
Either change the name or add a dummy RowDeleting handler.

I have changed the command name of button from “DELETE” to “DELETEITEM” abd it solves the error.

Hope this will help !!!…

Gridview sorting ascending descending image example

Today i want to share Gridview ascending/descending image example with all of you.

To see sorting example visit my previous articles. How to enter ascending/descending image direction in gridview header? is common question for beginners. So, i have prepare one example to show you how you will do this.

In aspx page declare grid view as follow.


            
                
                    
                        
                    
                    
                        <%# Eval("BusinessEntityID")%>
                    
                
                
                    
                        First Name
                    
                    
                        <%# Eval("FirstName") %>
                    
                    
                        
                    
                
                
                    
                        Last Name
                    
                    
                        <%# Eval("LastName") %>
                    
                    
                        
                    
                
                
                    
                        Address
                    
                    
                        <%# Eval("AddressLine1") %>
                    
                    
                        
                    
                
                
                    
                        City
                    
                    
                        <%# Eval("City") %>
                    
                    
                        
                    
                
                
                    
                        Postal Code
                    
                    
                        <%# Eval("PostalCode") %>
                    
                    
                        
                    
                
                
            
        

Now, in cs file add following code at BindData function which is done all job for you. We are adding few lines which is search Linkbutton from gridview Hearder and add image at that place.

            // For Sorting Image
            LinkButton lnkID = (LinkButton)this.gvData.HeaderRow.FindControl("lnkID");
            LinkButton lnkFirstName = (LinkButton)this.gvData.HeaderRow.FindControl("lnkFirstName");

            if (this.gvData_SortBy == lnkID.CommandArgument.ToLower())
            {
                InsertSortImage(this.gvData.HeaderRow.Cells[0]);
            }
            else if (this.gvData_SortBy == lnkFirstName.CommandArgument.ToLower())
            {
                InsertSortImage(this.gvData.HeaderRow.Cells[1]);
            }

Add one more function to insert image in header.

    protected void InsertSortImage(TableCell orderedCell)
    {
        string imgUrl = null;

        if (this.gvData_IsAsc == true)
        {
            imgUrl = "images/desc.gif";
        }
        else
        {
            imgUrl = "images/asc.gif";
        }

        Image img = new Image();
        img.ImageUrl = imgUrl;
        img.BorderStyle = BorderStyle.None;
        orderedCell.Controls.Add(img);
    }

Now, you are ready just add “Images” folder in your project and add two images asc.gif and desc.gif. I am attaching both images here with this article.

descasc

How to retrieve youtube thumbnail image in asp.net

Hi Friends,

Today I will explain how to retrieve thumbnail image from YouTube video in asp.net.

Generally we are embedding a video from youtube to our website dynamically and we need to integrate thumbnail image of that video in our site.

To retrieve thumbnail image from YouTube video we can use YouTube API URL.
see below URL:
“http://img.youtube.com/vi/” + youtubeVideoID + “/default.jpg”

To test above URL replace youtubeVideoID with any YouTube video id like “UMAa148hojo” and run the URL it will show you thumbnail image of video.

Here, I have used default.jpg which shows “120×90″ size default youtube trailer thumbnail image.

If you want bigger image then you can use “0.jpg” instead of “default.jpg”.

If you want other thumbnail image instead of default image then you can specify “1, 2 or 3.jpg”.

See the below example, I have used “MERE BAAP PEHLE AAP” – Trailer and binds different size of thumbnails using asp.net.

Youtube Trailer Thumbnail Images

see below code for asp.net code behind class

protected void Page_Load(object sender, EventArgs e)
    {
        string youtubeVideoID = "UMAa148hojo";
        image0.ImageUrl = "http://img.youtube.com/vi/" + youtubeVideoID + "/default.jpg";
        Image1.ImageUrl = "http://img.youtube.com/vi/" + youtubeVideoID + "/0.jpg";
        Image2.ImageUrl = "http://img.youtube.com/vi/" + youtubeVideoID + "/1.jpg";
        Image3.ImageUrl = "http://img.youtube.com/vi/" + youtubeVideoID + "/2.jpg";
        Image4.ImageUrl = "http://img.youtube.com/vi/" + youtubeVideoID + "/3.jpg";
    }

You will get below images for your code in output.
youtube_thubnails

How to use edit, delete in gridview

Hello Friends,

Today i am sharing one example for gridview edit and delete functionality. Example is for beginners who want to learn gridview edit and delete functionality.

To apply edit, delete functionality in your grid you should follow below steps.
In aspx page declare gridview control and add event OnRowEditing, OnRowUpdating, OnRowCancelingEdit and OnRowDeleting also add DataKeyNames for row value. Now, add CommandField in your grid. In my example i have declare grid as follow.

        
            
                
                    
                        
                    
                    
                        <%# Eval("BusinessEntityID")%>
                    
                
                
                    
                        First Name
                    
                    
                        <%# Eval("FirstName") %>
                    
                    
                        
                    
                
                
                    
                        Last Name
                    
                    
                        <%# Eval("LastName") %>
                    
                    
                        
                    
                
                
                    
                        Address
                    
                    
                        <%# Eval("AddressLine1") %>
                    
                    
                        
                    
                
                
                    
                        City
                    
                    
                        <%# Eval("City") %>
                    
                    
                        
                    
                
                
                    
                        Postal Code
                    
                    
                        <%# Eval("PostalCode") %>
                    
                    
                        
                    
                
                
            
        

In EditItemTemplate you can add textbox, radiobutton or checkbox etc…
In .cs file do following code

    protected void gvData_Editing(object sender, GridViewEditEventArgs e)
    {
        gvData.EditIndex = e.NewEditIndex;
        BindData();
    }

    protected void gvData_Updating(object sender, GridViewUpdateEventArgs e)
    {
        GridViewRow row = gvData.Rows[e.RowIndex];
        int id = 0;
        int.TryParse(e.Keys["BusinessEntityID"].ToString(), out id);

        TextBox txtFirstName = (TextBox)row.FindControl("txtFirstName");
        TextBox txtLastName = (TextBox)row.FindControl("txtLastName");
        TextBox txtAddressLine1 = (TextBox)row.FindControl("txtAddressLine1");
        TextBox txtCity = (TextBox)row.FindControl("txtCity");
        TextBox txtPostalCode = (TextBox)row.FindControl("txtPostalCode");

        DBM.SqlCommandEx sqlCmd = new DBM.SqlCommandEx(
                    String.Format("UPDATE Person.Person" +
                    " SET firstName='{0}', lastName='{1}'" +
                    " WHERE BusinessEntityID = {2}"
                    , txtFirstName.Text, txtLastName.Text, id) +

                    String.Format(" UPDATE Person.Address" +
                    " SET addressLine1='{0}', city='{1}', postalCode='{2}'" +
                    " WHERE addressID = (SELECT addressID FROM Person.BusinessEntityAddress WHERE BusinessEntityID = {3})"
                    , txtAddressLine1.Text, txtCity.Text, txtPostalCode.Text, id)

                    );

        DataTable i = sqlCmd.GetDataTable();

        gvData.EditIndex = -1;
        BindData(); 
    }

    protected void gvData_Deleting(object sender, GridViewDeleteEventArgs e)
    {
        GridViewRow row = gvData.Rows[e.RowIndex];
        int id = 0;
        int.TryParse(e.Keys["BusinessEntityID"].ToString(), out id);

        // Delete Code Goes here Try it yourself

        gvData.EditIndex = -1;
        BindData();
    }

    protected void gvData_CancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        gvData.EditIndex = -1;
        BindData();
    }

EditIndex is used to edit the gridview row. It will tell that grid is in edit mode. Default EditIndex is -1 means no row in editmode.

That’s it all done now, you are ready.
I am attaching demo here GridView Edit Delete Example

youtube flash player hide menu

Hello,

Today I have integrated youtube video in my site but it hides the menu and other asp.net controls.

I have just copied the youtube tag from youtube site and paste it into my iframe page.

You know that there is property “z-index” that helps the browsers understand which elements to display in which order. So I have assigned “z-index” but it doesn’t work.

After that I have used wmode parameter in youtube embedded tag and it solves my problem

see below example:
I have used below embedded code in my page


code with wmode parameter


If you can’t specify wmode property in youtube embedded tag then it will take default wmode as opaque. So you need to specify it as transparent and it will solve your problem.

Hope this will help.

accent search in sql server

Hello All,

Generally in our business application, we need to implement search functionality on database column like title, firstname, lastname, city etc. It will create problem in search result when data contains accent characters and the database collation is accent-sensitive. so we will get wrong result.

Let’s take an example, you need to search the database for movies having a director that contains “Shohei”. So we will write query like below:

select movieTitle from movies where director like '%Shohei%'

Ideally, the result set should include below:
Shohei
Imamura, Shohei
Youssef Chahine,Shôhei Imamura
Amos Gitai,Shohei
Shôhei Imamura,Claude Lelouch

If your database collation is accent-sensitive, the result set includes only:
Shohei
Imamura, Shohei
Amos Gitai,Shohei

Note that directors containing accent characters are excluded from the result set. This is because accent characters are excluded from the query. Unfortunately, this is not the desired result.

Now I will show you how can we search accent characters in sql query. For this, first we need to understand collection in sql.

What is collation in SQL?
A collation in SQL Server is a defined set of rules for sorting and comparing data. This includes rules for case-sensitivity and accent-sensitivity. When you select a collation (for your server, database, column, or expression), you assign specific characteristics to your data that affect the results of database operations.

When we installed SQL Server 2008 R2/SQL Server 2012, the default collation was SQL_Latin1_General_CP1_CI_AS. The collation name is broken into these parts:

  • SQL = indicates a SQL Server collation name
  • Latin1_General = identifies the alphabet whose sorting rules are applied
  • CP1 = identifies Code Page 1252, which is a character encoding of the Latin alphabet
  • CI = defines case-insensitive comparison rules
  • AS = defines accent-sensitive comparison rules

I have already write one blog for the case sensitive search in sql server where we have use COLLATE Latin1_General_CS_AS = ‘Case sensitive Data’

How can we implement accent search in sql server. There are some solution for it.
1. Configure the database so that it is not accent-sensitive; change the collation to SQL_Latin1_General_CP1_CI_AI.

2. Remove and replace accented characters in the query.

select movieTitle from movies where replace(director, 'ô', 'o')like '%Shohei%'

3. Specify an accent-insensitive collation in the query

select movieTitle from movies where director like '%Shohei%' collate SQL_Latin1_General_CP1_CI_AI

Option 1 is simplest from a programmer’s perspective, because it is a permanent solution, server-wide and database-wide, and it requires no programming changes to applications. When you are installing a new SQL Server instance then this is easy to do.
Generally we are hosting application on hosting server so we cannot manage this option because they have already installed database with default option accent-sensitivity.

Options 2 and 3 are simplest from a database administrator’s perspective, because they require no changes to the database. This is useful for shared hosting environment.

Hope this will help.

Gridview paging and sorting example

Hello All,

We are move ahead in grid view example today we will talk about paging and sorting in grid view.

To enable sorting and paging in your grid use “AllowSorting” and “AllowPaging” property to enable it respectively. Make both properties to true for our example.

When you enable paging and sorting at that time write two events to work it. Those events are “OnPageIndexChanging” and “OnSorting”.

Paste below code in aspx page.

          
            
                
                    
                        
                    
                    
                        <%# Eval("BusinessEntityID")%>
                    
                
                
                    
                        First Name
                    
                    
                        <%# Eval("FirstName") %>
                    
                
                
                
                
                
            
        

it will allow to paging and sorting. To write there event in .cs file use below code

    protected void gvData_Sorting(object sender, GridViewSortEventArgs e)
    {
        if (e.SortExpression.Trim().ToLower() == this.gvData_SortBy)
        {
            this.gvData_IsAsc = !this.gvData_IsAsc;
        }
        else
        {
            this.gvData_SortBy = e.SortExpression.Trim().ToLower();
            this.gvData_IsAsc = true;
        }
        //this.ResetPagerControl();
        this.BindData();
    }

    protected void gvData_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        //this.gvData_PageIndex = e.NewPageIndex;
        this.BindData();
        this.gvData.PageIndex = e.NewPageIndex;
        this.gvData.DataBind();
    }

    // To Bind Data
    private void BindData()
    {
        try
        {
            //int rp = 100;
            int rowPage = rp;
            
            if (rp == 0)
                rp = 100;

            int start = ((this.gvData_PageIndex - 1) * rp);

            if (start != 0)
            {
                rp = start + rp;
                start = start + 1;
            }

            string limit;
            limit = String.Format(" WHERE row >= {0} and row <= {1}", start, rp);

            DBM.SqlCommandEx sqlCmd = new DBM.SqlCommandEx(
                    String.Format("SELECT * FROM(SELECT Person.BusinessEntityID, FirstName, LastName, AddressLine1, City, PostalCode, ROW_NUMBER() OVER (ORDER BY {0}) as row " +
                    " FROM Person.Person" +
                    " INNER JOIN Person.BusinessEntity on BusinessEntity.BusinessEntityID = Person.BusinessEntityID" +
                    " INNER JOIN Person.BusinessEntityAddress on BusinessEntityAddress.AddressID = BusinessEntity.BusinessEntityID" +
                    " INNER JOIN Person.Address on Address.AddressID = BusinessEntityAddress.AddressID) T {1} ORDER BY row"
                    , this.gvData_SortBy + " " + (this.gvData_IsAsc == true ? "ASC" : "DESC"), limit));

            gvData.DataSource = sqlCmd.GetDataTable();
            gvData.DataBind();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

Thats it you are ready with paging and sorting in gridview.

I am attaching sample with this article. Hope you will enjoy this!!
GridView Example With Paging Sorting

Cannot add duplicate collection entry of type ‘add’ with unique key attribute ‘value’

Hello,

Once I have transferred site from shared hosting to dedicated hosting and i got error “Cannot add duplicate collection entry of type add with unique key attribute value“.

see the below screenshot of error:
error

I have checked web.config file and IIS settings for this error.
I have seen below code in web.config file

 
    
      
        
        
        
        
        
        
      
    
 

This is for default document.

After that I have open IIS and check the site details, I have found below entries for the default documents:
iisdefault

So it occurs because of multiple entry of default page.

How can we solve it:To resolve this problem, first you must delete the duplicate entry that is defined at the highest level. The highest level may be the IIS server. After you delete the duplicate entry, the feature configuration page for the Web site or for the application should be displayed correctly.

Same event handler for multiple link buttons

Hello,

Today I am going to represent How to handle single event for multiple Link buttons in asp.net.

This is very useful concept and we will use it in our web application where we need to implement same event for multiple link buttons.

lets take an example, Suppose we want to implement alphabetical search in our web application then we will create link buttons for A,B,C…..Z.

see below code


..........................
..........................




...
...
...
...


..........................
..........................

Here, I have defined multiple link buttons for each alpha but all alpha contains same event handler.

Now How can we decide which link button has been clicked by user.
see below code

protected void Alpha_Click(object sender, EventArgs e)
{
     LinkButton btn = sender as LinkButton;
     if (btn == null) { return; }
     
     Response.Write(btn.Text);
}

Now we can use this in our query for finding records on the base of clicked link button.

how to detect mobile browser in javascript

Hello All,

Today I am going to describe how to detect mobile browser. Now a days mobile application is common and we arise this situation to detect the mobile browser.

we can easily implement this functionality in different language like java, asp.net, cold-fusion, c# etc.

Generally we can use javascript easily in different languages. so today i am going to descibe this functionality using javascript.

You know that navigator.userAgent provides the information related to browser. so i have used it for browser detection.

see the below javascript function for mobile browser detection.

 function DetectMobileOS()
        {
            var deviceWebos = "webos";
            var deviceIphone = "iphone";
            var deviceIpad = "ipad";
            var deviceIpod = "ipod";
            var devicePalm = "palm";
            var deviceS60 = "series60";
            var deviceSymbian = "symbian";
            var deviceAndroid = "android";
            var deviceWinMob = "windows ce";
            var deviceWinPhone = "windows phone";
            var deviceBB = "blackberry";
            var deviceZuneWP7 = "ZuneWP7";
            var deviceIEMobile = "IEMobile";
            var deviceOperaMini = "Opera Mini";
            var deviceBada = "bada";

            var uagent = navigator.userAgent.toLowerCase();
            
            if (
                    uagent.search(deviceWebos) > -1 ||
                    uagent.search(deviceIphone) > -1 ||
                    uagent.search(deviceIpad) > -1 ||
                    uagent.search(deviceIpod) > -1 ||
                    uagent.search(devicePalm) > -1 ||
                    uagent.search(deviceS60) > -1 ||
                    uagent.search(deviceSymbian) > -1 ||
                    uagent.search(deviceAndroid) > -1 ||
                    uagent.search(deviceWinMob) > -1 ||
                    uagent.search(deviceWinPhone) > -1 ||
                    uagent.search(deviceBB) > -1 ||
                    uagent.search(deviceZuneWP7) > -1 ||
                    uagent.search(deviceIEMobile) > -1 ||
                    uagent.search(deviceOperaMini) > -1 ||
                    uagent.search(deviceBada) > -1
                )
            {
                return true;
            }
            else
            {
                return false;
            }

        }

How can we use it in our code?

 if (DetectMobileOS())
 {
     //write code for the mobile browser
 }
 else
 {
    //write other code
 }

Hope this will help.