Bind Dropdown in Gridview

Hello All,

I want to share example of bind dropdown in gridview. In Edit mode when you want to show your value in dropdown it will help you.

To add dropdown use following code for gridview.


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

Now, add following code in cs file. We are using Edit event and BindDropDown function to achieve our goal. In Edit mode you can use other objects too like checkbox, radiobutton etc…

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

        HiddenField hdTitle = (HiddenField)gvData.Rows[e.NewEditIndex].FindControl("hdTitle");
        DropDownList ddlTitle = (DropDownList)gvData.Rows[e.NewEditIndex].FindControl("ddlTitle");

        BindDropDown(ddlTitle);

        if (ddlTitle != null)
            ddlTitle.SelectedValue = hdTitle.Value;
    }

private void BindDropDown(DropDownList ddl)
    {
        ddl.Items.Add(new ListItem("-- Select --", ""));
        ddl.Items.Add(new ListItem("Mr.", "Mr"));
        ddl.Items.Add(new ListItem("Mrs.", "Mrs"));
        ddl.Items.Add(new ListItem("Miss", "Miss"));
        ddl.Items.Add(new ListItem("Dr.", "Dr"));
        ddl.Items.Add(new ListItem("Sr.", "Sr"));
    }

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");
        DropDownList ddlTitle = (DropDownList)row.FindControl("ddlTitle");

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

                    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();
    }

Now, all done you can run it and see when you are in edit mode you will see your dropdown with selected value. I am attaching example with this article. Demo

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 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

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

Example of gridview binding

Hello Friends,

Today i want to show you how to bind gridview? I have created one simple example of gridview binding.
To create example i have used VS 2010 and Adventures database.

First create one web site/web application and create one page. Paste below code in your aspx page.



       
       
       
       
       
       


Now, in .cs file use following code to bind grid view.

            try
            {
                DBM.SqlCommandEx sqlCmd = new DBM.SqlCommandEx(
                        "SELECT TOP 10 Person.BusinessEntityID, FirstName, LastName, AddressLine1, City, PostalCode" +
                        " 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" +
                        " ORDER BY FirstName");

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

Now, you are ready. Hope it will help to beginner to bind data grid.
I am attaching example and other needed file with this article.
Download it from here GridViewExample.rar