I'm trying to update GridView from code behind but stuck at a problem which I don't understand even after countless searches for a solution.
After editing a textbox in GridView EditItemTemplate, clicking an 'Update' button in the row would fire RowUpdating event. In the RowUpdating event handler, I use this code to get the string of the edited txtBox1:
Dim text1 As String = (CType(GridView1.Rows(e.RowIndex).FindControl("txtBox1"), TextBox)).Text
I am able to get a correct value for text1 but the problem is if I wrote GridView1.DataBind() in the same even handler, the code above will cause the error "Object reference not set to an instance of an object." I could not understand why the same code will work if delete/comment out GridView.DataBind() method.
I've been stuck with this problem for many days and I will really really appreciate any help.
Here's my VB.net code to handle GridView1.RowUpdating. This will only work if I delete or comment out GridView1.DataBind() method but GridView won't be updated with new data :
Protected Sub GridView1_RowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs) Handles GridView1.RowUpdating
Dim text1 As String = (CType(GridView1.Rows(e.RowIndex).FindControl("txtBox1"), TextBox)).Text
Dim text2 As String = (CType(GridView1.Rows(e.RowIndex).FindControl("txtBox2"), TextBox)).Text
Dim IDkey As String = GridView1.DataKeys(e.RowIndex).Values(0).ToString()
Dim sqlquery As String = "UPDATE tblPMU SET zone = '" & text1 & "', substation ='" & text2 & "' WHERE (ID ='" & IDKey & "')"
Dim sqlCmd As New SqlCommand(sqlquery, conn)
Dim sqlDa As New SqlDataAdapter(sqlCmd)
conn.open()
Dim dt As New DataTable()
sqlDa.Fill(dt)
conn.Close()
GridView1.EditIndex = -1
UpdateGridview()
GridView1.DataBind()
Label5.Text=text1
End Sub
My .aspx code for the GridView:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" AllowSorting="True"
onrowediting="GridView1_RowEditing"
onrowcancelingedit="GridView1_RowCancelingEdit"
onrowupdating="GridView1_RowUpdating">
<Columns>
<asp:CommandField ButtonType="Button" ShowEditButton="True" />
<asp:BoundField DataField="ID" HeaderText="ID" SortExpression="ID" ReadOnly="True" Visible="False" />
<asp:TemplateField HeaderText="subzone" SortExpression="zone">
<EditItemTemplate>
<asp:TextBox ID="txtBox1" runat="server" Text='<%# Bind("zone") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("zone") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="substation" SortExpression="station">
<EditItemTemplate>
<asp:TextBox ID="txtBox2" runat="server" Text='<%# Bind("station") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("station") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>