2014-11-02 100 views
0

這是我的ASP.NET代碼片段。無法投射「System.Web.UI.HtmlControls.HtmlForm」類型的對象來鍵入「System.Web.UI.WebControls.GridViewRow」

我想選擇一個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'。

請提供您的反饋。

回答

0

不知道你正在試圖做什麼,但你的演員是什麼導致它。您對Parent.Parent的調用在樹上過高,並且您已經以表單容器結束,並且不再位於GridView中。

相反,你正在嘗試中投,爲什麼不嘗試:

GridViewRow row = GridView_MyGridView.SelectedRow; 
((Invoices)Session["Items"]).ItemNo = int.Parse(row.Cells[0].Text); 

請記住,這仍然會報錯了,如果有牢房內沒有文字,所以你可能想看看在處理該使用額外的邏輯或TryParse()代替。

+0

gridview包含數據。 只有當我使用GridView模板中的選擇列時,您的建議代碼纔有效。 我想要完成的是刪除每個GridView Row前面的這個選擇按鈕,並使用e.row.Attributes來選擇一個GridView Row。 – CyborgHead 2014-11-03 11:29:10

+0

我修改了我的代碼,現在可以使用您的建議代碼。 – CyborgHead 2014-11-03 12:30:01

相關問題