LinkButton Casting error

J

Jim McGivney

I am trying to determine the row of a Button on a DataView an. I need to
set the CommandArgument when the row is first created.
I copied the following from Visual Studio 2005 documentation

public void GridView1_RowCreated(Object sender, GridViewRowEventArgs e)
{// The GridViewCommandEventArgs class does not contain a
// property that indicates which row's command button was
// clicked. To identify which row's button was clicked, use
// the button's CommandArgument property by setting it to the
// row's index.
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Retrieve the LinkButton control from the first column.
LinkButton addButton = (LinkButton)e.Row.Cells[0].Controls[0];
//Button addButton = (Button)e.Row.Cells[0].Controls[0];
// Set the LinkButton's CommandArgument property with the
// row's index.
addButton.CommandArgument = e.Row.RowIndex.ToString();
}
}

When I run it I get the following message: Unable to cast object of type
'System.Web.UI.LiteralControl' to type
'System.Web.UI.WebControls.LinkButton'.

This is an error for the line "LinkButton addButton =
(LinkButton)e.Row.Cells[0].Controls[0];"

Any suggestions would be welcome.

Thanks,

Jim
 
N

Nathan Sokalski

When controls are added to cells, there are often LiteralControls added as
well. These LiteralControls are used for extra text that has no real meaning
(for example, a space or tab used in the *.aspx file to indent lines). The
best solution is to iterate through the controls and check the type of each
one before casting. Hopefully this will help.
 

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

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top