Here is my ASP.NET code snippet.
I am trying to select a GridView Row and add the selected row items in Session Variable.
// ======================== MyGridView ========================
protected void GridView_MyGridView_SelectedIndexChanged(object sender, EventArgs e)
{
// Get Selected Row Items
Items myitems = new Items();
Session["Items"] = myitems;
((Invoices)Session["Items"]).ItemNo = int.Parse(((GridViewRow)(((WebControl)(sender)).Parent.Parent)).Cells[0].Text);
}
I do NOT want to use the clickable select button that comes with the GridView Columns.
I handled by the following code:
protected void GridView_MyGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onmouseover"] = "this.style.cursor='pointer';this.style.textDecoration='underline';";
e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';";
e.Row.ToolTip = "Click to Select a Visit.";
e.Row.Attributes["onclick"] = Page.ClientScript.GetPostBackClientHyperlink(sender as GridView, "SELECT$" + e.Row.RowIndex);
}
}
Now, when I run the program, I get the following error as soon as the gridview selected row changes:
Unable to cast object of type 'System.Web.UI.HtmlControls.HtmlForm' to type 'System.Web.UI.WebControls.GridViewRow'.
Please, provide your feedback.
Not sure what you are trying to do but your cast is what is causing it. Your call to Parent.Parent is going too far up the tree and you have ended up with the form container and are no longer within the GridView at all.
Instead of the cast you are attempting, why not just try:
GridViewRow row = GridView_MyGridView.SelectedRow;
((Invoices)Session["Items"]).ItemNo = int.Parse(row.Cells[0].Text);
Keep in mind, this will still error out if there is no text in the cell so you may want to look at handling that with additional logic or a TryParse() instead.