简体   繁体   English

我这个vb.net代码有什么问题

[英]what is wrong in my this vb.net code

替代文字

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim lab As Label = Me.GridView1.FindControl("Label1")
        If TextBox2.Text = "7" Then
            GridView1.SelectedRow.Cells(2).Text = "500"
        Else
            GridView1.SelectedRow.Cells(2).Text = "950"
        End If
    End Sub

The following error occurs : Object reference not set to an instance of an object. 发生以下错误: 对象引用未设置为对象的实例。

You've got this code in your Page Load event, so it will run when the page is first loaded, and on every single postback. 您已在Page Load事件中获得此代码,因此它将在首次加载页面时以及每次回发时运行。 This probably isn't what you want. 这可能不是你想要的。

I imagine that on the very first load, there isn't a selected row in your GridView, so GridView1.SelectedRow is going to be null . 我想象在第一次加载时,GridView中没有选定的行,因此GridView1.SelectedRow将为null If this isn't null, then Cells or Cells(2) definitely will be. 如果不为空,则CellsCells(2)肯定是。 Trying to access a property on null is going to throw a NullReferenceException - "Object reference not set to an instance of an object". 尝试访问null上的属性将引发NullReferenceException-“对象引用未设置为对象的实例”。

As this MSDN example shows, you're probably better off accessing the SelectedRow property in an event handler for the SelectedIndexChanged event of the GridView. 如该MSDN示例所示,最好在事件处理程序中访问GridView的SelectedIndexChanged事件的SelectedRow属性。

Dim lab As Label = Me.GridView1.FindControl("Label1")

It doesn't look like you're doing anything with this label. 您似乎对这个标签没有做任何事情。 Put a breakpoint on that line and see if it finds it. 在该行上放置一个断点,看看是否找到它。 If it doesn't and you don't even use it, take the line out. 如果没有,你甚至不使用它,请把线拿出来。

Also, check if textbox2 is valid whilst debugging. 另外,在调试时检查textbox2是否有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM