|

Introduction
This article will be very useful to all users who are working with ASP.NET 2.0 GridView control. Here, I will explain how to work with the GridView control in ASP.NET 2.0, which is very easier to use than the DataGrid control in ASP.NET 1.1. I will also explain the differences between the GridView and the DataGrid controls. We will also look into how to work with a template column having a DataGrid inside it.
Background
The basic idea behind this article is to see how much the ASP.NET 2.0's GridView control is easier to work than the DataGrid control in ASP.NET 1.1. I have previously worked with the DataGrid control, and I know how difficult it is to work with it in the same project in which I am using the GridView control. Working with the ASP.NET 2.0 GridView control is very easy as it is very user friendly. Though I had faced a lot of difficulties in using it, I can still say it is far better than the DataGrid control. The GridView control gives you Edit, Update, Delete, Sorting, Selection, and Paging functionality built-in.
Using the code
Here in this project, I have used an ObjectDataSource control for binding the GridView to the data source. This is one of the best features available in VS.NET 2005. It is very easy to work with it.
The main difference between a DataGrid and a GridView control is that the DataGrid control has centralized event handling which means any event raised by a control inside the DataGrid’s template column will be handled by the ItemCommand event of the DataGrid. But this functionality is some what different in the GridView control. It directly calls the handler of the control.
I mean to say that in the GridView control, if you add a template column having a GridView inside it and then if you select the Column Sorting command, it will not call any event of the master grid, but will directly call the sorting handler of the child grid. It is up to the user to take advantage of this feature.
So let me explain the code now. Here, I have a master table which is bind to the master grid using MasterDataSouce and a child table which is bound to a GridView inside a template column of the master grid. To bind the child grid to the ChildDataSource, we have to use the RowDataBound event which is called every time when a row from the database is bound to the GridView’s row.
Here, the basic idea behind caching is that when a cell value is required, you should get it and show it. So what happens behind the screen is:
RowDataBound event of the master gridProtected Sub grdMaster_RowDataBound(ByVal sender As Object, _
ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) _
Handles grdMaster.RowDataBound
Dim objListItem As DataControlRowState
objListItem = e.Row.RowState
Dim intMAsterID1 As Integer
If e.Row.RowType = DataControlRowType.DataRow Then
Dim grd As GridView
If objListItem = 5 Then
grd = CType(e.Row.FindControl("grdChildGridEdit"), GridView)
MasterTableID = Convert.ToInt32(CType(e.Row.DataItem, _
DataRowView).Row.ItemArray(0).ToString())
intMAsterID1 = MasterTableID
ElseIf objListItem = DataControlRowState.Normal Or _
objListItem = DataControlRowState.Alternate Then
grd = CType(e.Row.FindControl("grdChildGridNormal"), GridView)
intMAsterID1 = Convert.ToInt32(CType(e.Row.DataItem, _
DataRowView).Row.ItemArray(0).ToString())
Dim lnkButtton As LinkButton
lnkButtton = CType(e.Row.FindControl("Edit"), LinkButton)
If lnkButtton IsNot Nothing Then
lnkButtton.CommandName = "Edit Master"
lnkButtton.CommandArgument = intMAsterID1.ToString
End If
ElseIf objListItem = DataControlRowState.Edit Then
grd = CType(e.Row.FindControl("grdChildGridEdit"), GridView)
MasterTableID = Convert.ToInt32(CType(e.Row.DataItem, _
DataRowView).Row.ItemArray(0).ToString())
intMAsterID1 = MasterTableID
End If
If grd IsNot Nothing Then
grd.DataSourceID = ""
grd.DataSource = ChildDataSource
ChildDataSource.SelectParameters(_
"MasterTableID").DefaultValue = intMAsterID1
ChildDataSource.Select()
grd.DataBind()
End If
End If
End Sub
Here, what I am doing is when the master table's rows are bound with the GridView's row, I find the ChildGrid control and then bind that control with the ChildDataSource for that MasterID.
The above code will be used when the user hits on the Master Grid Edit button. So, in the template column, the child grid with the edit and the delete options will get visible. Now, the biggest problem with this child grid is that each and every event handler have to be written manually because the grid will lose its binding when any command gets fired. And another thing is that unlike the DataGrid, the child grid’s handler will get called when any command of the child grid gets fired like Edit, Delete, Sorting, or Paging. In the DataGrid, the inner control's event will be first handled by the grid's ItemCommand event irrespective of whether that control is a DataGrid, Button, or ListBox. But here it will not call the RowCommand event of the master grid, but will directly call the RowCommand event of the child grid. So, the event flow is like this:
- When the user presses the Edit option in the master grid, it will call the
RowCommand event of the master grid with the command name "Edit".
- Now, it will call the
RowDataBound of the master grid here. You will find whether the RowState of the particular row is "Edit", and then you will find the child grid with the Edit and Delete commands in the EditTemplate of the template column. And then you will bind the grid to ChildDataSource.
- Now, the master grid will look like below:

- When you press the Edit option of the child grid, it will invoke the
RowCommand of the child grid just like a DataGrid calls the ItemCommand of the master grid. And it will not call the RowDataBound of the master grid so your child edit grid for that particular row will not bind to the datasource. So your grid will disappear. Now, in the RowCommand of the child grid, you have to rebind the grid with the data source. grdchildgrid = CType(sender, GridView)
If e.CommandArgument IsNot Nothing Then
If IsNumeric(e.CommandArgument) Then
intRowId = Convert.ToInt32(e.CommandArgument)
End If
End If
If e.CommandName.Equals("Edit") Then
grdchildgrid.DataSourceID = ""
grdchildgrid.DataSource = ChildDataSource
ChildDataSource.SelectParameters(_
"MasterTableID").DefaultValue = MasterTableID
ChildDataSource.Select()
End If
If e.CommandName.Equals("Update") Then
UpdateChildRecord()
grdchildgrid.DataSourceID = ""
grdchildgrid.DataSource = ChildDataSource
ChildDataSource.SelectParameters(_
"MasterTableID").DefaultValue = MasterTableID
ChildDataSource.Select()
End If
If e.CommandName.Equals("Delete") Then
DeleteChildRecord()
grdchildgrid.DataSourceID = ""
grdchildgrid.DataSource = ChildDataSource
ChildDataSource.SelectParameters(_
"MasterTableID").DefaultValue = MasterTableID
ChildDataSource.Select()
End If
If e.CommandName.Equals("Cancel") Then
grdchildgrid.DataSourceID = ""
grdchildgrid.DataSource = ChildDataSource
ChildDataSource.SelectParameters(_
"MasterTableID").DefaultValue = MasterTableID
ChildDataSource.Select()
End If
If e.CommandName.Equals("Page") Then
grdchildgrid.EditIndex = -1
grdchildgrid.DataSourceID = ""
grdchildgrid.DataSource = ChildDataSource
ChildDataSource.SelectParameters(_
"MasterTableID").DefaultValue = MasterTableID
ChildDataSource.Select()
End If
If e.CommandName.Equals("Sort") Then
grdchildgrid.EditIndex = -1
Dim dt As DataView
grdchildgrid.DataSourceID = ""
ChildDataSource.SelectParameters(_
"MasterTableID").DefaultValue = MasterTableID
dt = CType(ChildDataSource.Select(), DataView)
If ViewState.Item("SortDirection") IsNot Nothing Then
If CType(ViewState.Item("SortDirection"), _
SortDirection) = SortDirection.Ascending Then
dt.Sort = e.CommandArgument & " ASC"
ViewState.Item("SortDirection") = _
SortDirection.Descending
Else
dt.Sort = e.CommandArgument & " DESC"
ViewState.Item("SortDirection") = _
SortDirection.Ascending
End If
End If
grdchildgrid.DataSource = dt
grdchildgrid.DataBind()
End If
Here, you will find that you have to handle every command manually, for the child grid, because you are continuously changing the binding of the child grid. And another thing I have found is that if you do not write the handlers for the Edit, Delete, Update, Sort, and Page commands, it will give an error because when you press the Edit command of the child grid, it will search for the RowEditing handler of the child grid even if you are doing all the activity in the RowCommand event.
The grid will look like this:

- Here, one thing that is important is that in the
RowCommand event of the child grid, you will get the old values in the grid, from the viewstate of the grid. But the child grid will not be bound to any data source if you don't bind it to in the RowCommand event.
- When you press
UpdateCommand, it will call the RowCommand with the CommandArgument as "Update". And after that, it will call the RowUpdating event of the child grid. But there will be no values in either e.NewValues or e.OldValues. So you will have to do the update in the RowCommand event.
Points of interest
ASP.NET 2.0 is a very good framework to work with. It is a much enhanced version and is very much handy to work with.
History
I will release a few more interesting articles on ASP.NET 2.0. If any body has any problems using DataGrid control, please let me know and I will try to work on it.
| You must Sign In to use this message board. |
|
| | Msgs 1 to 25 of 25 (Total in Forum: 25) (Refresh) | FirstPrevNext |
|
|
 |
|
|
Hi
I want to remove Header text which is repeatedly occurring in every child grid. How to make this .Plz help me.I was struck ed
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Hi,
I am new to gridview control. have nested a gridview inside another gridview. The address details in the child gridview is repeating for all users(candidate name) and I m not getting corresponding address for each users. Plz help me as soon as possible.. // Parent Gridview Binding public void BindData() {
SqlConnection con=new SqlConnection("Server:localhost;Uid=;Password=;Database="Employee"); SqlCommand cmd=new SqlCommand("Select * from Employee",con); SqlDataAdapter da=new SalDataAdapter(); Dataset ds=new DataSet(); da.Fill(ds); ParentGrid.DataSource = ds.Tables[0] ; ParentGrid.DataBind(); }
//Child Gridview Binding
protected void ParentGrid_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) {
SqlConnection con=new SqlConnection("Server:localhost;Uid=;Password=;Database="Employee"); SqlCommand cmd=new SqlCommand("Select Address,Mobile from Employee",con); SqlDataAdapter da=new SalDataAdapter(); Dataset ds=new DataSet(); da.Fill(ds); GridView gv2 = new GridView();
(GridView)gv2 = ( GridView)e.Row.FindControl("ChildGrid");
gv2.DataSource = ds.Tables[0]; gv2.DataBind();
} }
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
 |
|
|
For adding a dropdownlist in a Gridview,first add a template field in the columns collection of the Gridview.And in the code behind file inside the Template field script add item template and inside that create a dropdownlist.
<asp:TemplateField> <ItemTemplate> <asp:DropDownList runat="server" ID="dropdownlist1" AutoPostBack="true"> </asp:DropDownList> </ItemTemplate> </asp:TemplateField> You can bind the contents of other columns as usual.For binding contents to the dropdown list column,in the GridView1_RowDataBound event include the following code.
if (e.Row.RowType == DataControlRowType.DataRow) { DropDownList dropdown1 = (DropDownList)e.Row.FindControl("dropdownlist1"); for (int kk = 0; kk < h; kk++) { dropdown1.Items.Add(stringarray[kk]); } }
where stringarray is a string array which contains the contents to be added into the dropdownlist.
Like this the contents are added into the dropdownlist of the Gridview Control.
For Retriving the selected values of the dropdownlists inside the gridview,see the following code.
protected void Button1_Click(object sender, EventArgs e) {
for (int yy = 0; yy < GridView1.Rows.Count; yy++) { DropDownList dropdown2; dropdown2 = (DropDownList)GridView1.Rows[yy].FindControl("dropdownlist1"); Response.Write(dropdown2.SelectedItem.Text); } }
I think this will clear your doubts.
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
 |
|
|
 |
|
|
hi plz help me out if find some thing then mail me same_021@yahoo.co.in , or if u know about some of helpful links then plz mail me
|
| Sign In·View Thread·PermaLink | 2.00/5 (5 votes) |
|
|
|
 |
|
|
 |
|
|
 |
|
|
 |
|
|
Hiii..
Very Helpful post...
I hav code in .Net 2003 for the DataGrid is Item_Command...
What is in GridView(.Net2005) instead of Item_command...?
I cant found this Code...
Private Sub dgSupplierInfo_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) Handles dgSupplierInfo.ItemCommand If e.CommandName = "agentid" Then Dim txt As TextBox txt = e.Item.FindControl("txtPrID") LoadData(txt.Text) End If
End Sub
Can u pls Help me Regarding This Problem?
|
| Sign In·View Thread·PermaLink | 2.00/5 (2 votes) |
|
|
|
 |
|
|
Thank you for this article, just in time Im having trouble with displaying Gridview Inside a GridView... and wallaahh! problem solve...!
|
| Sign In·View Thread·PermaLink | 1.00/5 (1 vote) |
|
|
|
 |
|
|
i have a roblem GridView editing inside GridView in asp.net 2.0
so how to extract child gridview into childgridview _onrowediting event plz as soon as possible
avananda
|
| Sign In·View Thread·PermaLink | 1.67/5 (3 votes) |
|
|
|
 |
|
|
All the template columns in the gridview are created dynamically except the first column that contains the edit, delete and select link buttons.Any click event on these buttons is removing all the template columns.So i am not able to access the new values in the grid_updating,grid_rowcammand events.How can i fix this. Thank you in advance.
|
| Sign In·View Thread·PermaLink | 1.00/5 (1 vote) |
|
|
|
 |
|
|
Why do you do all of the updating, deleting inside the RowCommand sub instead of the updating sub?
I moved the code to the updating sub and it works there, and makes more sense.
DrWebMonkey
|
| Sign In·View Thread·PermaLink | 1.50/5 (2 votes) |
|
|
|
 |
|
|
i have a problem, have got a gridview where all products are populated, now i want user to select the products he wants to order and store all the products selected in another gridview on same page.
Currently i can transfer only one record on second grid view if i select another product from first gridview it will overwrite the record in second gridview.
Is it possible to insert multiple records in database through any gridview or datagrid or for matter anything else.
Thanks
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Hi
Would you be able to advise how we would be able to export the nested gridview to excel ?
Any help would be much appreciated.
TIA
|
| Sign In·View Thread·PermaLink | 2.67/5 (3 votes) |
|
|
|
 |
|
|
<%@ Page language="C#" Debug="true" %> <%@ Import Namespace="System.Drawing" %> <%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Data.SqlClient" %>
<script Language="C#" runat="server"> private void Button1_Click(object sender, System.EventArgs e) { //export to excel
Response.Clear(); Response.Buffer= true; Response.ContentType = "application/vnd.ms-excel"; Response.Charset = ""; this.EnableViewState = false;
System.IO.StringWriter oStringWriter = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
this.ClearControls(dg); dg.RenderControl(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
Response.End(); }
private void Page_Load(object sender, System.EventArgs e) { if (!IsPostBack) {
SqlConnection conn = new SqlConnection ("data source=(local);initial catalog=Northwind;Pwd=p@ssw0rd;User ID=sa"); SqlCommand cmd = new SqlCommand ("Select LastName, FirstName, Title, TitleOfCourtesy, BirthDate, HireDate, Address, City, Region, PostalCode, Country from Employees", conn); SqlDataAdapter da = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); da.Fill(ds); dg.DataSource = ds.Tables[0]; dg.DataBind(); }
}
private void ClearControls(Control control) { for (int i=control.Controls.Count -1; i>=0; i--) { ClearControls(control.Controls[i]); }
if (!(control is TableCell)) { if (control.GetType().GetProperty("SelectedItem") != null) { LiteralControl literal = new LiteralControl(); control.Parent.Controls.Add(literal); try { literal.Text = (string)control.GetType().GetProperty("SelectedItem").GetValue(control,null); } catch
{
}
control.Parent.Controls.Remove(control); }
else
if (control.GetType().GetProperty("Text") != null) { LiteralControl literal = new LiteralControl(); control.Parent.Controls.Add(literal); literal.Text = (string)control.GetType().GetProperty("Text").GetValue(control,null); control.Parent.Controls.Remove(control); } } return; } </script> <html> <body leftmargin="0" topmargin="0" marginwidth="0" marginheight="0"> <form id="frm" runat="server"> <asp:Button id="Button1" runat="server" Text="Export to Excel" önClick="Button1_Click">
<asp:Datagrid id="dg" runat="server" AutoGenerateColumns="True" AllowSorting="true" AllowPaging="true" CellPadding="3" PageSize=3>
<asp:LinkButton runat="server" CommandName="Edit" CausesValidation="false" ID="btnView" Text="Edit"/>
</form> </body> </html>
|
| Sign In·View Thread·PermaLink | 5.00/5 (1 vote) |
|
|
|
 |
|
|
Can u have c# version and datas are populate through sqlconnection not in xml it is very useful to me
Tamil
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
I tried to find this in a lot of forums today but I had to figure it out on my own. I want to bind a DataTable to a dropdownlist in a edit template in code. There are many examples which use SQL data sources, but I couldn't find a solution to my problem. I finally got it to work.
Create a DataBinding event handler for the EditItemTemplate DropDownList Control you want to populate. And the event handler is as simple as:
protected void DropDownListDeptEdit_DataBinding(object sender, EventArgs e) { ((DropDownList)sender).DataSource = DepartmentList.DepartmentListDataSource(); }
In this case DepartmentList.DepartmentListDataSource() returns a DataTable. I hope this helps someone.
Thanks Rob
|
| Sign In·View Thread·PermaLink | 1.50/5 (2 votes) |
|
|
|
 |
|
|
Hi, When I tried to run the demo program, I got the Invalid object name 'MasterTable' error message. Do you have any idea why?
Here is the Stack Trace:
Source Error:
Line 684: this.Adapter.SelectCommand = this.CommandCollection[0]; Line 685: MasterTable.MasterTableDataTable dataTable = new MasterTable.MasterTableDataTable(); Line 686: this.Adapter.Fill(dataTable); Line 687: return dataTable; Line 688: }
Source File: c:\WINNT\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\gridview\2982f479\491ddf05\App_Code.swt1610x.1.cs Line: 686
Stack Trace:
[SqlException (0x80131904): Invalid object name 'MasterTable'.] System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) +857370 System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +734982 System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) +188 System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +1838 System.Data.SqlClient.SqlDataReader.ConsumeMetaData() +31 System.Data.SqlClient.SqlDataReader.get_MetaData() +62 System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +297 System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async) +886 System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) +132 System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +32 System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) +122 System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) +12 System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader(CommandBehavior behavior) +7 System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior) +141 System.Data.Common.DbDataAdapter.Fill(DataTable[] dataTables, Int32 startRecord, Int32 maxRecords, IDbCommand command, CommandBehavior behavior) +162 System.Data.Common.DbDataAdapter.Fill(DataTable dataTable) +107 MasterTableTableAdapters.MasterTableTableAdapter.GetData() in c:\WINNT\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\gridview\2982f479\491ddf05\App_Code.swt1610x.1.cs:686
Thanks, Michael
|
| Sign In·View Thread·PermaLink | 2.00/5 (1 vote) |
|
|
|
 |
|
|
Double click on the database file some how it make a connection and run the app again. It is worked. Thanks.
|
| Sign In·View Thread·PermaLink | 1.00/5 (2 votes) |
|
|
|
 |
|
|
 |
|
|
I work with Visual Studio 2005, and using GridView Control in my Project. How can i simply read data from cell of GridView and store in a variable with Visual Basic. Then I want to change the data and i would like to write back to cell. I have a Column, called: PRICE, in the database is not the correct price(without tax). That is the reason why i want to read, change, and write back the data. I'am a beginner, but i need this information.. thx.
|
| Sign In·View Thread·PermaLink | 2.00/5 (2 votes) |
|
|
|
 |
|
|
This article was very helpful. I am trying to make a Grid Where in I want to add columns dynamically. The column must have different controls based on the values that are entered in child grid vi | | | | | |