开发者

Object reference not set to an instance of an object. (gridview, button)

I keep getting this error

Object reference not set to an instance of an object. 

What i want to do is when the button is clicked my panel is visible with a textbox of the id number, of the row that they clicked. by id number i mean the column id, and the number given to it by the database.

Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs)
    Dim button As Button = CType(e.Row.FindControl("button1"), Button)
    Dim id As Label = CType(e.Row.FindControl("id"), Label)

    but开发者_如何转开发ton.OnClientClick = _
    Panel1.Visible = True
    Label2.Visible = True
    Label2.Text = id.Text

    UpdatePanel1.Update()



End Sub


Try to add the following condition to ensure whether the DataRow (rather than the HeaderRow) is being processes at this moment:

If e.Row.RowType = DataControlRowType.DataRow Then
    ...
End If


Its more than likely one of the controls you are searching for is not being found.

Try the following, the error will tell you which one is not being found correctly.

Dim button As Button = CType(e.Row.FindControl("button1"), Button)
if(button == null) throw new ApplicationException("button1 was not found");

Dim id As Label = CType(e.Row.FindControl("id"), Label)
if(id== null) throw new ApplicationException("id was not found");

NB* All the information you need to find where the error is occurring is contained inside the exception details. Look at the stack trace for the line number. If there is one skill every programmer needs is the ability to read exceptions correctly and pay attention to them.


I would suspect your issue may be coming from

Dim id As Label = CType(e.Row.FindControl("id"), Label)

this line returning Nothing (as it may not have found the control) and then you are trying to access one of its properties here

Label2.Text = id.Text

I have no idea what this line is trying to

button.OnClientClick = _

but if it failed to find the control this would also cause the same error.

To solve the problem you are having I would recommend not doing this in the manner you are. But setting an OnClick in button definition of the Row for a method like MyButtonClicked, handle this server side where you will be be able to determine the row sending the command and then have you're logic to hide/show the panel/text boxes etc


One of your two controls isn't being found in the row. Is the ID for the Label control really "id"?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜