Dominik
Dominik

Reputation: 331

deleting a row in a table

I have a following markup on my web page:

<asp:GridView ID="GridView" runat="server" 
      AutoGenerateDeleteButton="True"
<Columns>
     <asp:TemplateField HeaderText="ID" Visible="false"> 
           <ItemTemplate>
              <asp:Label ID="lblID" runat="server" Text='<% #Eval("ID")%>'></asp:Label>
           </ItemTemplate>
     </asp:TemplateField>
...

I am trying to get the value of the text field to get the correct ID of the row that I want to be deleted, however I do not know how to exactly do it, I have tried following code:

Protected Sub GridView_RowDeleting(sender As Object, e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles GridView.RowDeleting
    Dim row As GridViewRow = GridView.Rows(e.RowIndex)
    Dim ID As Integer = TryCast(row.FindControl("lblID"), TextBox).Text
...

However after clicking on the delete button on the generated web page I just get error:

"Object reference not set to an instance of an object."

Visual Studio points the error to the "TryCast". I can not find any similar examples and do not understand what is happening, if somebody has a better idea of getting that ID value that would also work?

Upvotes: 0

Views: 46

Answers (1)

Tetsuya Yamamoto
Tetsuya Yamamoto

Reputation: 24957

Your lblID control certainly is a label defined by this control markup:

<asp:Label ID="lblID" runat="server" Text='<% #Eval("ID")%>'></asp:Label>

On this line you tried to cast the label control as TextBox instead of Label, so it returns Nothing and throwing NullReferenceException when accessing Text property:

Dim ID As Integer = TryCast(row.FindControl("lblID"), TextBox).Text

What do you need is cast to Label and get Text property there:

Dim ID As Integer = Convert.ToInt32(TryCast(row.FindControl("lblID"), Label).Text)

Note that Convert.ToInt32 added because Text property of a label control contains string value, hence casting to Integer is necessary. If you're not sure it will return Nothing, use Integer.TryParse instead.

Upvotes: 2

Related Questions