0

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>
Azizul H
  • 101
  • 2
  • 10
  • 2
    Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Panagiotis Kanavos Oct 31 '18 at 10:10
  • If you search for that error message you'll find there's a duplicate question that explains what's wrong and how to solve it. As for what's wrong, something in that long line of nested calls returns a NULL. Break the line apart in order to check what each call returns. What is that line supposed to do anyway? The call says `find a textbox inside the grid row` which doesn't make any sense. I suspect you should check a tutorial on ASP.NET data binding. – Panagiotis Kanavos Oct 31 '18 at 10:14
  • Have you set the DataSource of the GridView? – David Sdot Oct 31 '18 at 10:16
  • Web applications aren't desktop applications. They don't have controls. They *render* everything into HTML so when a postback occurs there are *no* controls and no data. WebForms tries to emulate controls and events using viewstate and request parameters. If you check the documentation on the RowUpdating event and specifically the [GridViewUpdateEventArgs](https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.webcontrols.gridviewupdateeventargs.keys?view=netframework-4.7.2) arguments you'll see the row keys and values are available as properties of the `args` parameter – Panagiotis Kanavos Oct 31 '18 at 10:18
  • The DataSource of the GridView is set in the PopulateGridview() function which send SELECT command to SQL database to get the data in it. – Azizul H Nov 01 '18 at 01:20
  • Thanks @Panagiotis Kanavos you're pointing me closer to the solution but there's something I still don't understand. First is why it doesn't make sense to find a textbox inside the grid row. From threads I read about RowUpdating, a lot of people used the same method to retrieve the text written in the textbox inside GridView but mine is causing the said error. Is there a better way? Second, I thought text1 value is not null because line Label5.Text=text1 is able to show the correct value. Only when I try to bind data to GridView, then I'll get the NullReferenceException error. – Azizul H Nov 01 '18 at 01:52
  • @AzizulH read the documentations and tutorials, not threads. A lot fo people don't understand the difference between Web Forms and Windows Forms or how to use data binding. You'll find a *lot* of awful code in discussion forums. As for a better way, I alreayd explaind the *proper* way. You have *all* the values, old, new and keys in `GridViewUpdateEventArgs`. You don't need the text boxes. Read the link I posted. It shows how to extract the values and even how to use a SqlDataSource component to update it without extra code – Panagiotis Kanavos Nov 01 '18 at 08:46

0 Answers0