How to access Datagrid Linkbutton with OnItemDataBound?

R

Rodusa

I keep getting this error when trying to modify the text property of a
linkbutton inside a datagrid template column.

Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not
set to an instance of an object.

Source Error:




Line 234: b.Text="Replace with this item"; // ERROR HAPPENS HERE

Line 235:

Line 236: for (int i=0; i < (e.Item.Cells.Count)-1; i++)







// CODE

public void CheckRow(object sender, DataGridItemEventArgs e)

{

string keyword = Request.QueryString["keyword"];

if (keyword!=null && keyword!=null) // Replace item event happens
(uses button Replace this item)

{

// changes button label

string test= e.Item.Cells.Count.ToString();

//gets first template column. It needs to be accessed differently
from databound items

LinkButton b = (LinkButton)e.Item.FindControl("btAddReplace");

b.Text="Replace with this item";



for (int i=0; i < (e.Item.Cells.Count)-1; i++)

{

Response.Write(i.ToString()+e.Item.Cells.Text+"<br>");

}

}

}






I also tried these two other alternatives and no success:


LinkButton b = (LinkButton)e.Item.Cells[0].Controls[0];

DataBoundLiteralControl b = b.Controls[0] as
DataBoundLiteralControl;




The error only happens when I try to access the control property
"b.Text". The instance of it is recognized by the framework.
thank you

Rod
 
R

Rodusa

I've just figured out. I forgot to skip the Datagrid headers

if (e.Item.ItemType == ListItemType.SelectedItem || e.Item.ItemType
== ListItemType.Item || e.Item.ItemType ==
ListItemType.AlternatingItem)
{
code here
}

Rod
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top