2010-06-08 84 views
2

我正在ASP .net 2.0中工作。我是一名學習者。我有一個網格視圖,其中有一個按鈕。請在下面找到asp標記使用按鈕添加新行到asp .net網格視圖使用按鈕

<form id="form1" runat="server"> 
<div> 
    <asp:GridView ID="myGridView" runat="server"> 
     <Columns> 
      <asp:TemplateField> 
       <ItemTemplate> 
        <asp:Button CommandName="AddARowBelow" Text="Add A Row Below" runat="server" /> 
       </ItemTemplate> 
      </asp:TemplateField> 
     </Columns> 
    </asp:GridView> 
</div> 
</form> 

請在下面找到代碼。

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Data; 
using System.Web.UI.WebControls; 

namespace GridViewDemo 
{ 
    public partial class _Default : System.Web.UI.Page 
    { 
     protected void Page_Load(object sender, EventArgs e) 
     { 
      DataTable dt = new DataTable("myTable"); 
      dt.Columns.Add("col1"); 
      dt.Columns.Add("col2"); 
      dt.Columns.Add("col3"); 
      dt.Rows.Add(1, 2, 3); 
      dt.Rows.Add(1, 2, 3); 
      dt.Rows.Add(1, 2, 3); 
      dt.Rows.Add(1, 2, 3); 
      dt.Rows.Add(1, 2, 3); 
      myGridView.DataSource = dt; 
      myGridView.DataBind(); 
     } 

     protected void myGridView_RowCommand(object sender, GridViewCommandEventArgs e) 
     { 

     } 
    } 
} 

我在想,當我點擊命令按鈕,它會觸發mygridview_rowcommand(),而是它如下拋出一個錯誤:

無效的回發或回調參數。事件驗證在配置中啓用,或在頁面中啓用<%@ Page EnableEventValidation =「true」%>。爲了安全起見,此功能驗證回發或回調事件的參數來自最初呈現它們的服務器控件。如果數據有效且預期,請使用ClientScriptManager.RegisterForEventValidation方法爲註冊回發或回調數據進行驗證。

任何人都可以讓我知道我要去哪裏嗎?

回答

1

首先,嘗試禁用事件驗證並查看結果是什麼,因爲這是代碼中的明顯問題。

<%@ Page EnableEventValidation="false" ... 

然而,如果你不想restort這樣的黑客,請執行下列操作:

之後,刪除按鈕的屬性OnCommand事件,以及OnRowCommand事件添加到GridView本身。

實施例:

<asp:GridView OnRowCommand="myGridView_RowCommand"> 
    ... 
</asp:GridView> 

這應該是處理這些命令的正確方法。
該按鈕必須具有特定CommandName才能按預期工作。

See this page有關可能的值和對此問題的更多解釋。在該頁面上還有一個工作示例,值得你花時間檢查一下。

+0

我照你說的去做了。然後我沒有得到錯誤。但是當我點擊按鈕時,myGridView_RowCommand沒有觸發。 我其實加了

 asp:Button OnCommand="myGridView_RowCommand" .... 
它工作。 – SARAVAN 2010-06-08 18:59:51

+0

@SARAVAN - 順便說一句,在你的代碼中'GridView'和'myGridView_RowCommand'沒有任何連接。 – Venemo 2010-06-08 19:08:02

+0

asp:Button OnCommand =「myGridView_RowCommand」 看看上面的代碼,我實際上在你回答我的問題時加了它。無論如何,我更新了代碼。 – SARAVAN 2010-06-08 19:51:26