2017-10-18 70 views
0

我有我的网页上的下列标记:删除行的表

<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> 
... 

我试图获取文本字段的值来获得该行的正确的ID,我想删除了,但我不知道如何准确地做到这一点,我曾尝试下面的代码:

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 
... 

但是点击删除按钮生成的网页上后,我只是得到错误:

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

Visual Studio将错误指向“TryCast”。 我找不到任何类似的例子,不明白发生了什么,如果有人有更好的想法获得该ID值也可以工作?

+0

这段代码是绝对错误的:'TryCast(row.FindControl(“lblID”),TextBox).Text'。使用'TryCast'的重点在于它可能会失败,你可能会得到'Nothing',所以直接访问结果的成员是错误的。如果你知道演员阵容会成功,并且可以安全地访问这样的成员,那么你应该使用'DirectCast',否则你应该首先测试TryCast的结果,并且只有在它不是'Nothing'时才使用它。 – jmcilhinney

回答

2

lblID一定的控制是通过这个控制标记定义标签:

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

在这条线,你想投的标签控制为TextBox,而不是Label,所以它返回Nothing和访问Text时抛出NullReferenceException属性:

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

你需要什么被转换为Label并获得Text特性有:

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

注意Convert.ToInt32添加,因为一个标签控件的Text属性包含字符串值,因此铸造Integer是必要的。如果您不确定它会返回Nothing,请改为使用Integer.TryParse

+0

非常感谢你,我只是没有看到它。 – Dominik