2016-09-15 61 views
0

我有一個gridview ASP.net從MS-SQL數據庫檢索某些列。它工作正常,正確顯示數據,我可以根據需要使用gridview附帶的按鈕進行編輯和刪除。gridview錯誤

我現在在數據庫中添加了一個新列,並且正在更新我的代碼。

我創建了一個新的datasource,現在我可以從數據庫中檢索該列。我有一個問題,在gridview中看不到editdelete,但我能夠設法使用AutoGenerateDeleteButton="true"AutoGenerateEditButton="true"來顯示它們。

但是,當我按下刪除或編輯按鈕,我得到下面的錯誤。

Unable to cast object of type 'System.Web.UI.WebControls.GridView' to type 'System.Web.UI.WebControls.LinkButton'. 

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.InvalidCastException: Unable to cast object of type 'System.Web.UI.WebControls.GridView' to type 'System.Web.UI.WebControls.LinkButton'. 

Source Error: 

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e) 
{ 
LinkButton lnkbtn = ((LinkButton)e.CommandSource); 
GridViewRow gvRow = (GridViewRow)(lnkbtn.NamingContainer); 
HiddenField hdn_supplier = (HiddenField)gvRow.FindControl("hdn_supplier"); 
} 

任何想法?

+0

GridView1_RowCommand你沒有測試e是一個linkbutton然後試圖引用它的CommandSource。你可能想要測試e的類型。 ((如鏈接按鈕== null) –

回答

0

這是一個來自正在進行的VB代碼工作的C#示例。它看起來像你缺少你刪除表彰處理器

protected void dgGlossaries_DeleteCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e) 
{ 
    dynamic rowToDelete = e.Item.ItemIndex; 
    DataTable dt = (DataTable)Session["glossaries"]; 
    DataRow dr = dt.Rows(rowToDelete); 
    dr.Delete(); 
    dgGlossaries.DataSource = dt; 
} 

這是VB相同的例子,工作應該希望你指出正確的方向,如果您遇到與在C#示例

Protected Sub dgGlossaries_DeleteCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) Handles dgGlossaries.DeleteCommand 
    Dim rowToDelete = e.Item.ItemIndex 

    Dim dt As DataTable = DirectCast(Session("glossaries"), DataTable) 
    Dim dr As DataRow = dt.Rows(rowToDelete) 
    dr.Delete() 

    dgGlossaries.DataSource = dt 
    dgGlossaries.DataBind() 
End Sub