This article will show you how to deal with GridView control when you bind it from code behind and without using the DataSource Model.
going to bind a GridView via code there are a couple things to keep in
mind. When you do this you must handle the events yourself, unlike when
you configure the GridView in design-time.
Namely, you must handle: RowEditing, RowDeleting ,RowCancelingEdit & RowUpdating (Events of the GridView)
1. Presumably if you're binding the GridView in code, you'll will need to Bind the GridView in Page Load event Handler
<span class="kwd">If Not</span> IsPostBack<br /> GridView1.DataSource = EVALAdapter.GetData <span class="cmt">'my dataset</span><br /> GridView1.DataBind() <br /> <span class="kwd">End If</span>
2. In order to get your Gridview Row into 'Edit' mode you must do the following in the RowEditing event:
GridView2.EditIndex = e.NewEditIndex<br />GridView2.DataSource = EvalGroups.GetData 'my dataset<br />GridView2.DataBind()
3. The RowCancelingEdit is identical to RowEditing except for one small change:
GridView1.EditIndex = -1<br />GridView1.DataSource = EVALAdapter.GetData<br />GridView1.DataBind()
4. My RowUpdating looks like this:
Dim cmd As New dsEvalTableAdapters.tblEvalTableAdapter<br /><br />Dim FirstCellText as String = GridView1.Rows(e.RowIndex).Cells(0).Text<br />Dim chkCheck As CheckBox<br />chkCheck = GridView1.Rows(e.RowIndex).FindControl(<span class="st">"CheckBox1"</span>
things to keep in mind. FindControl is necessary because there isn't a
direct reference to the TextBox control that is dynamically created
when you go into edit mode. The name 'TextBox1' is generated
automatically (much like when you first add a TextBox control to a web
form and it is given a default ID value). You can see
this if you view the source of the aspx page after you go into edit
Important: The control field you're trying to find using FindControl, in this case, must be a template field and not merely a BoundField ( if they are a BoundField then you need to access them via GridViewRow.Cells collection like we do for the "FirstCellText " value ).
In this article , we show how to manually bind the GridView control using the Code behind and without using the Data Source Model .
Note that using the Data Source Model is much easier since you just need to configure the GridView dataSoruce using visual studio designer.Also using the Data source model allow you to automatically enable paging,editing,deleting,updating ,which requires a lot of work when you use the code behind approach ( as we show in this article).
Sometimes you have no choice but to use the code behind model , like if you want to bind the GridView to a list of Array elemnts or to a DataTable that is created in the page code behind.
Finally , Always try to use the DataSource model as much as you can because its easy and minimize the amount of code, hence it will minimze the bugs and effort.
Data Access Tutorials