AspdotnetCodes.com
Search
Articles
Books
Resources
Asp.Net News
Downloads
Free Tech Magazines
Asp.Net Web Hosting
Archives
Softwares
Newsletter
Suggest Us
Link to Us
Feeds Subscription
Articles
Questions & Answers
Tips & Tricks
 Asp.Net GridView Manipulation Inside DataList Control
Posted by Moderator1 on 10/8/2008 9:51:42 AM Category: ADO.NET
Total Views : 95806
Add to my favorites
Email to friend
  
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 can be 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.

To-do at Design Section

Place a DataList control in your aspx page. Specify DataKeyNames of the DataList control as Cus_State. In the ItemTemplate section of the DataList control, place a Label control and a GridView control. Bind the Label control to display the Customer State.

Now in the GridView control, using the smart tag, add a Template Field to place a checkbox control in it, then add Bound Fields to display customer information such as Customer Name [Cus_Name], Gender [Cus_Gender], Age [Cus_Age] and City [Cus_City]. Then add 2 Command Fields to perform Edit/Update and Delete operations. Specify the DataKeyNames of the GridView control as Cus_State, Cus_Code. In the Template Field, place two checkbox controls, one at the HeaderTemplate section and another at the ItemTemplate section and specify its ID as chkSelectAll and chkCusNo respectively. In the Template Field’s ItemTemplate section, place a HiddenField control named “hidCusState”, near the checkbox and bind its Value property to Cus_State.

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

FYI: The below code includes all the events bounded with the DataList and GridView control. So make sure you have created the related events in the code-behind section before you run this page in the browser.

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

To-do on Code-Behind Section


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

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.

private void BindGrid(GridView GridView, string CusState)
{
  string sql = "Select Cus_No, Cus_Name, Cus_Gender, Cus_Age, Cus_City, Cus_State from  
    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.

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

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

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

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.

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.

Click here to view our Sample page
 
Viewer's Comments
Posted by Ruchi on 10/20/2008 12:11:23 AM
Excellent Article
 
Posted by saifullah on 10/21/2008 4:21:09 AM
great post, but can u do the same with dataset, not using querry, but using objectdatasource?
 
Posted by Ramani Sandeep on 11/7/2008 4:45:27 AM
Really a Great Article.. It Helps a Lot in Solving my Problem.. Thanks a lot ...
 
Posted by PriyanshShah on 11/18/2008 3:33:25 AM
Such a gr8 Article that help me to how to use datalist ctrl..Thanks
 
Posted by Sandeep Ramani on 11/24/2008 4:33:57 AM
I'm havin a huge problem that's driving me crazy. I have a DataList (dlOtherFinishes) embedded within another DataList (list) When I try to retrieve the DataKeyField of dlOtherFinishes in it's ItemDataBound event using: Dim productId As Int32 = Convert.ToInt32(dlOtherFinishes.DataKeys(e.Item.ItemIndex)) I receive the: Object reference not set to an instance of an object.
 
Posted by Kirti on 11/25/2008 4:16:38 AM
Its a great article.Its helps in solving all the grid view problem... Thanks
 
Posted by Kirti on 11/25/2008 4:35:12 AM
Can u provide the sample code for sorting?
 
Posted by Haresh Chaudahri on 12/4/2008 12:17:52 AM
good articles
 
Posted by amarnath on 12/8/2008 12:15:49 AM
Excellent article i got good idea on grid view
 
Posted by Dusty on 12/22/2008 8:13:42 AM
here is a nother good example: http://laymensterm.blogspot.com/2008/12/simple-aspnet-vbnet-database-connection.html
 
Posted by Farooq on 1/21/2009 2:28:49 AM
The article is very good! Can u please post the code for paging and sorting of gridview. Thanks, Farooq
 
Posted by srajmohan on 2/19/2009 6:51:06 AM
good
 
Posted by ANU on 3/9/2009 12:32:09 PM
YOU HAVE WRITEN VERY CLEARY IT DEFINIETLY HELP VIEWERS
 
Posted by naveen on 3/19/2009 1:36:01 AM
Good Article..............
 
Posted by naveen9948054301 on 3/19/2009 1:36:54 AM
very good article....
 
Posted by vijaya krishna Garikipati on 4/15/2009 7:01:53 AM
Excellent and Very Very Good and Use full Article and i got it u can also try it,,,, regards vijaya krishna garikipati Hyderabad
 
Posted by vijaya krishna Garikipati on 4/15/2009 7:02:15 AM
YOU HAVE WRITEN VERY CLEARY IT DEFINIETLY HELP VIEWERS
 
Posted by vijaya krishna Garikipati on 4/15/2009 7:02:36 AM
Really a Great Article.. It Helps a Lot in Solving my Problem.. Thanks a lot ...
 
Posted by vijaya krishna Garikipati on 4/15/2009 7:03:03 AM
Really a Great Article.. It Helps a Lot in Solving my Problem.. Thanks a lot ... regards vijay krishna Garikipati India
 
Posted by nagendra kumar on 5/9/2009 5:29:05 AM
jugfbnm,.
 
Posted by Madhu on 6/16/2009 4:03:23 AM
It's Very nice article.
 
Posted by Balaji Karpurapu on 7/21/2009 5:40:41 AM
This article is very usuful in realtime projects
 
Posted by appu on 2/2/2010 10:33:47 AM
very nice article
 
Posted by anand on 6/9/2010 11:29:54 PM
Hei this article helps me a lot..... please post similar articles to my id please.... sweetchilli.chilli@gmail.com
 
Posted by Deena on 7/1/2010 11:46:35 PM
Great Article to all the programmers!! Thanks a lot :)
 
Posted by Hasmukh on 7/22/2010 5:34:22 AM
FANTASTIC ARTICLE NEED SOME SLIDING TECHNOLOGY HERE !!!
 
Posted by veena on 2/22/2011 5:11:55 AM
NICE!!!!!!!!!!!
 
Posted by archi on 2/22/2011 5:16:45 AM
This article is helpful.Pls post some more like this
 
Posted by Akash on 4/13/2011 12:13:48 AM
Great work,it helped me alot.. :)
 
Posted by Saiyam on 4/23/2011 11:30:45 PM
Excellent article....
 
Posted by lakshmi on 1/11/2012 1:21:07 AM
I have a column with Class in database in that i have a cell like 1stclass,4thclass,8thclass.i want to display that in gridview with the linkbuttons.When I clicked on each class that particular class students will be displayed.I have student table also can any one help please
 
Posted by lakshmi on 1/11/2012 1:39:07 AM
Using asp.net with C# I have a column with Class in database in that i have a cell like 1stclass,4thclass,8thclass.i want to display that in gridview with the linkbuttons.When I clicked on each class that particular class students will be displayed.I have student table also can any one help please
 
Posted by Sunil B Samantray on 6/18/2012 2:47:06 AM
Excellent Code... But use if condition in Itembound event of datalist else will give Error: protected void DataList1_ItemDataBound (object sender, DataListItemEventArgs e) { GridView GridView1=(GridView)e.Item.FindControl("GridView1"); if (e.Item.ItemIndex > -1) { BindGrid(GridView1,DataList1.DataKeys [e.Item.ItemIndex].ToString()); }
 
Posted by Shriraj on 5/23/2013 10:31:58 AM
This tutorial is verymuch helpfull for me to learn and easy to understand as well.Thanks a lot
 
Posted by 55 on 10/17/2013 6:58:21 AM
5555555
 
Posted by nikita agarwal on 7/11/2015 1:54:39 PM
Amazing post with great explanation. Simply superb and a very helpful post.
 
 Rating & Comments
A word 'Excellent' means lot to the author of this article. You can give comments about this article but not the author.
Rate this Article:
Name:
Email Id:  
We never display your email id anywhere.
Comment/Question: Max. 500 letters
Thirteen minus One Equals To
 
 
Sponsored by
Simply SQL - Free 111 Page Preview!
The JavaScript Anthology: 101 Essential Tips, Tricks & Hacks - Free 158 Page Preview
SearchSAP