user1599309 user1599309 - 4 months ago 12 Question

ASP.NET GridView_RowEditing get value of cell

This is pretty basic stuff, but I am unable to extract the text from a cell in my gridview.

<asp:TemplateField HeaderText="Rolle" SortExpression="role">
<asp:Label ID="roleLabel" runat="server" Text='<%# Eval("role") %>'></asp:Label>

<asp:DropDownList style="width: 200px;" ID="roleDropdown" runat="server" DataSourceID="SqlDataSourceDropDownlist" DataTextField="role" DataValueField="roleID"></asp:DropDownList>


Protected Sub GridView1_rowediting(sender As Object, e As GridViewEditEventArgs) Handles GridView1.RowEditing

Dim tb As Label
tb = CType(GridView1.SelectedRow.Cells(1).FindControl("roleLabel"), Label)
Dim userRoleString As String = tb.Text

End Sub

I received this error:

Object reference not set to an instance of an object.

How do i extract the text from the cell in a GridView?


Most likely you need to find the control you want first then grab the text, something like this:

Dim tb as TextBox 
tb = CType(GridView1.SelectedRow.Cells(1).FindControl("ID_Of_Some_textbox"), TextBox)
Dim userRoleString As String = tb.Text

EDIT: Added Sample code

The basic Idea:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="user_id" 
        <asp:CommandField ShowSelectButton="True" />
        <asp:TemplateField HeaderText="user_name" SortExpression="user_name">
                <asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDataSource2" DataTextField="user_name" 
                    DataValueField="user_name" SelectedValue='<%# Bind("user_name") %>' >
                <asp:Label ID="Label1" runat="server" Text='<%# Bind("user_name") %>'></asp:Label>