Asp.Net GridView Manipulation Inside DataList Control


Introduction

To make things clear, we are going to display Customer Information in a GridView control under each Customer State using a DataList and a GridView control. The data listed in the GridView control canbe manipulated with Edit, Update and Delete operations. Along with this, we are going to place a check box control in the first column of the GridView control, by which we can do a ‘Select All’ action for each Customer list separated by in every Customer State. Finally, a prompt confirmation has been added with the Delete LinkButton in the GridView control.

So the entire Html code of the DataList and GridView control will look like below.

Listing – 1

       <asp:DataList ID="DataList1" runat="server" DataKeyField="Cus_State" OnItemDataBound="DataList1_ItemDataBound"
                Width="100%">
                <ItemTemplate>
                    Customer State :
                    <asp:Label ID="Label1" runat="server" Text='<%# Bind("Cus_State") %>'></asp:Label>
                    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="Cus_State,Cus_Code"
                        GridLines="Horizontal" Width="100%" OnRowDataBound="GridView1_RowDataBound" OnRowEditing="GridView1_RowEditing"
                        OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowDeleting="GridView1_RowDeleting"
                        OnRowUpdating="GridView1_RowUpdating">
                        <Columns>
                            <asp:TemplateField>
                                <HeaderTemplate>
                                    <asp:CheckBox ID="chkSelectAll" runat="server" Text="Select all" />
                                </HeaderTemplate>
                                <ItemTemplate>
                                    <asp:CheckBox ID="chkCusNo" runat="server" />
                                    <asp:HiddenField ID="hidCusState" runat="server" Value='<%# Bind("Cus_State") %>' />
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:BoundField DataField="Cus_Name" HeaderText="Name"></asp:BoundField>
                            <asp:BoundField DataField="Cus_Gender" HeaderText="Gender"></asp:BoundField>
                            <asp:BoundField DataField="Cus_Age" HeaderText="Age"></asp:BoundField>
                            <asp:BoundField DataField="Cus_City" HeaderText="City"></asp:BoundField>
                            <asp:CommandField HeaderText="Edit" ShowEditButton="True"></asp:CommandField>
                            <asp:CommandField HeaderText="Delete" ShowDeleteButton="True"></asp:CommandField>
                        </Columns>
                        <EmptyDataTemplate>
                            You have deleted all records.
                        </EmptyDataTemplate>
                    </asp:GridView>
                </ItemTemplate>
            </asp:DataList>

We have simplified the code-behind section up to certain extent. The brief steps involved to bind the GridView inside DataList are given below:

Step 1: Bind the DataList in Form Load Event

Listing - 2

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string sql = "Select Distinct Cus_State from Customers";
            SqlDataAdapter da = new SqlDataAdapter(sql, "YourConnectionString");

            DataTable dt = new DataTable();
            da.Fill(dt);

            DataList1.DataSource = dt;
            DataList1.DataBind();
        }
    }

Step 2: In ItemDataBound Event of DataList control, bind the GridView control.

Since we are going to use binding of GridView control frequently in every event, we write a private method as below.

Listing - 3

    private void BindGrid(GridView GridView, string CusState)
    {
        string sql = "Select Cus_No, Cus_Name, Cus_Gender, Cus_Age, Cus_City, Cus_State from";
        sql = sql + " Customers Where Cus_State='" + CusState+ "'";

        SqlDataAdapter da = new SqlDataAdapter(sql, "YourConnectionString");
        DataTable dt = new DataTable();
        da.Fill(dt);

        GridView.DataSource = dt;
        GridView.DataBind();
    }

BindGrid function takes two parameters such as GridView object and a string CusState, i.e. Customer State to fetch the records corresponding only to the Customer State. Then call this method in the ItemDataBound event of the DataList control as follows.

Listing - 4

    protected void DataList1_ItemDataBound (object sender, DataListItemEventArgs e)
    {
        GridView GridView1 = (GridView)e.Item.FindControl("GridView1");

        BindGrid(GridView1, DataList1.DataKeys[e.Item.ItemIndex].ToString());
    }

First line of code, finds the GridView control inside the DataList control. And the second line, calls the BindGrid function, by passing GridView object and Cus_State field’s value which we have already bound with the DataList in the DataKeyField properly.

Believe it or not, hit F5 button once, your default browser will popped up, with a DataList displaying Customer State, and each row of the DataList will have a GridView control with corresponding Customers belongs to the State displayed in the DataList.

GridView Control Data Manipulations:

Step 1: GridView Row Editing Event

Listing - 5

    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView GridView1 = (GridView)sender;
        GridView1.EditIndex = e.NewEditIndex;
        BindGrid(GridView1, GridView1.DataKeys[e.NewEditIndex][0].ToString());
    }

Line 1: Creates GridView object from the sender, to identify which GridView control firing the ‘Edit’ event.
Line 2: Assign the EditIndex from the GridView events NewEditIndex.
Line 3: Call the BindGrid function by passing the created GridView object and the Customer State value taken from the DataKeyNames property.

Step 2: GridView Row Editing Cancel Event

Listing - 6

    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView GridView1 = (GridView)sender;
        GridView1.EditIndex = -1;
        BindGrid(GridView1, GridView1.DataKeys[e.RowIndex][0].ToString());
    }

Step 3: GridView Row Updating Event

Listing - 7

    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {

        GridView GridView1 = (GridView)sender;
        TextBox TxCusName = (TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0];
        TextBox TxCusGender = (TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[0];
        TextBox TxtCusAge = (TextBox)GridView1.Rows[e.RowIndex].Cells[3].Controls[0];
        TextBox TxCusCity = (TextBox)GridView1.Rows[e.RowIndex].Cells[4].Controls[0];

        string sql = "Update Customers Set Cus_Name=@CustomerName,"
        + "Cus_Gender=@CustomerGender, "
        + "Cus_Age=@CustomerAge, Cus_City=@CustomerCity "
        + "Where Cus_Code=@CustomerCode";

        SqlConnection conn = new SqlConnection(ConnectionString);
        conn.Open();

        SqlCommand cmd = new SqlCommand(sql, conn);
        cmd.Parameters.Add("@CustomerCode", SqlDbType.Int).Value =    GridView1.DataKeys[e.RowIndex].Values[1].ToString();
        cmd.Parameters.Add("@CustomerName", SqlDbType.VarChar, 50).Value = TxCusName.Text;
        cmd.Parameters.Add("@CustomerGender", SqlDbType.VarChar, 6).Value = TxCusGender.Text;
        cmd.Parameters.Add("@CustomerAge", SqlDbType.Int).Value = TxtCusAge.Text;
        cmd.Parameters.Add("@CustomerCity", SqlDbType.VarChar, 50).Value = TxCusCity.Text;
        cmd.Prepare();
        cmd.ExecuteNonQuery();
        conn.Close();

        GridView1.EditIndex = -1;
        BindGrid(GridView1, GridView1.DataKeys[e.RowIndex][0].ToString());

    }

The above code, finds the textboxes in the GridView Edit mode using the RowIndex property, followed by the usual coding to save the changes into the Database.

Step 4: GridView Row Deleting Event

Listing - 8

    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        GridView GridView1 = (GridView)sender;
        string sql = "Delete From Customers Where Cus_Code=@CustomerCode";

        SqlConnection conn = new SqlConnection(ConnectionString);
        conn.Open();
        SqlCommand cmd = new SqlCommand(sql, conn);
        cmd.Parameters.Add("@CustomerCode", SqlDbType.Int).Value
        = GridView1.DataKeys[e.RowIndex].Values[1].ToString();
        cmd.Prepare();
        cmd.ExecuteNonQuery();
        conn.Close();
        BindGrid(GridView1, GridView1.DataKeys[e.RowIndex][0].ToString());

    }

JavaScript function for ‘Select All’ Checkbox

To add ‘Select All’ checkbox functionality inside the GridView control, we have to work on both the Html and Code sections. In the Html section, we have already added two checkboxes in the GridView’s TemplateField’s HeaderTemplate and ItemTemplate sections. We have also added a HiddenField control along with the checkbox in the ItemTemplate section. To remind again, this HiddenField “hidCusState” will have the value of the Customer State. Now we are going to add a JavaScript function, which will be called when the CheckBox in the HeaderTemplate section is clicked.

Listing - 9

   <script type="text/javascript" language="javascript">
            function fnSelectAll(chkname, cusstate)
            {
                var inputs = document.getElementsByTagName('input');
                var checked=false;
                var hidCusState;

                for(var i=0;i<inputs.length;i++)
                {
                    if (inputs[i].id==chkname && inputs[i].type=="checkbox" && inputs[i].checked==true)
                    {
                        checked=true;
                        break;
                    }
                }

                for(var i=0;i<inputs.length;i++)
                {
                    if (inputs[i].id!=chkname && inputs[i].type=="checkbox")
                    {
                        hidCusState = inputs[i].id.replace("chkCusNo","hidCusState");
                        if (document.getElementById(hidCusState).value==cusstate)
                        inputs[i].checked=checked;
                    }
                }
            }
      </script>

This JavaScript function is exclusively written for web pages that work with MasterPages. Not only that, this function will only ‘checked’ the checkboxes belongs to a single Customer State.

How it works, is this function got two parameters such as the HeaderTemplate's CheckBox name and the value for the Customer State. The Customer State value passed is compared with the HiddenField control’s value, if it matches than that particular checkbox will get checked.

As first step it gets all the elements contains <input /> tags, finds only the ‘Select All’ checkbox, and identify whether it is checked or not. If the ‘Select All’ checkbox is checked then, it loops again to find out all the checkboxes and its corresponding hidden field in the GridView row, match both the cusstate and hidCusState value, and if match found, then change the status to ‘checked’. If the ‘Select All’ checkbox is unchecked, then it works vice-versa.

Now in the code-behind section, in the GridView RowDataBound event, add the following code.

Listing - 10

 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        //Part 1
        GridView GridView1 = (GridView)sender;
        DataListItem dlItem = (DataListItem)GridView1.Parent;
        DataListItemEventArgs dle = new DataListItemEventArgs(dlItem);
        if (e.Row.RowType == DataControlRowType.Header)
        {
            CheckBox chkSelectAll = (CheckBox)e.Row.FindControl("chkSelectAll");
            chkSelectAll.Attributes.Add("onclick",
            "fnSelectAll('" + chkSelectAll.ClientID + "', '"
            + DataList1.DataKeys[dle.Item.ItemIndex].ToString() + "');");
        }

        //Part 2
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (e.Row.Cells[6].HasControls())
            {
                LinkButton lnkbtnDelete = ((LinkButton)e.Row.Cells[6].Controls[0]);
                lnkbtnDelete.Attributes.Add("onclick", "return confirm('Do you want to Delete?');");
            }
        }
    }

The above code contains two parts. The first part belongs to ‘Select All’ function. In this part, we create an object to the GridView control from the sender object. Then we identify the parent of the GridView control, that is, the DataList item into which the GridView control belongs to. Using the DataListItemEventArgs object, we get the DataKey value of the parent’s DataList’s Item’s Customer State value. Then we find the chkSelectAll control and add the JavaScript function on the onclick event by passing it’s Client Id and the Customer State value of the DataList item.

Confirmation to Delete a Row in GridView control

Part 2 of the above RowDataBound event of the GridView control belongs to the confirmation of Delete functions before deleting a row in the GridView control.

Listing - 11

if (e.Row.RowType == DataControlRowType.DataRow)
    {
        if (e.Row.Cells[6].HasControls())
        {
            LinkButton lnkbtnDelete = ((LinkButton)e.Row.Cells[6].Controls[0]);
            lnkbtnDelete.Attributes.Add("onclick", "return confirm('Do you want to Delete?');");
        }
    }

Here we find the Delete LinkButton in the CommandField of the GridView control and then add a JavaScript confirm function on its onclick event.

Hope this article we give you a basic idea of how to manipulate GridView control inside a DataList and how to add JavaScript functions with various functionalities.

Advertisements

7 thoughts on “Asp.Net GridView Manipulation Inside DataList Control

  1. I am not positive the place you are getting your info, howeveer good topic.
    I mujst spend a while finding out more or working out more.
    Thank you for magnificent info I used to be searching for
    this information for my mission.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s