无法转换类型为#System; Web.UI.HtmlControls.HtmlForm'的对象键入' System.Web.UI.WebControls.GridViewRow'

时间:2014-11-02 16:45:56

标签: c# asp.net web-applications casting aspxgridview

这是我的ASP.NET代码段。

我正在尝试选择GridView行并在会话变量中添加所选行项。

// ======================== 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);    
}

我不想使用GridView列附带的可点击选择按钮。

我通过以下代码处理:

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);
    }
}

现在,当我运行程序时,一旦gridview选择了行更改,我就会收到以下错误:

无法转换类型为#System; Web.UI.HtmlControls.HtmlForm'的对象输入' System.Web.UI.WebControls.GridViewRow'。

请提供您的反馈。

1 个答案:

答案 0 :(得分:0)

不确定你想要做什么,但你的演员阵容是造成它的原因。你对Parent.Parent的调用在树上走得太远了,你最终得到了表单容器,根本不再在GridView中。

为什么不尝试:

,而不是你正在尝试的演员
GridViewRow row = GridView_MyGridView.SelectedRow;
((Invoices)Session["Items"]).ItemNo = int.Parse(row.Cells[0].Text);

请记住,如果单元格中没有文本,这仍然会出错,因此您可能希望查看使用其他逻辑或TryParse()来处理它。

相关问题