2012-01-04 44 views
1

我在我的gridviewrow中新创建的按钮没有触发它的EventHandler或RowCmmand事件,然后当按下新添加的行之后页面重新加载丢失可能是因为我无法调用我的BindData方法。我已删除从按钮的Click事件处理程序,只是使用的OnRowCommand事件,我还是我得到什么单击EventHandler not firing

protected void CustomGridView_DataBound(object sender, EventArgs e) 
{ 
    int count = ((GridView)sender).Rows.Count; 
    GridViewRow row = new GridViewRow(-1, -1, DataControlRowType.DataRow, DataControlRowState.Insert); 

    TableCell cell = new TableCell(); 
    Button button = new Button(); 
    button.Text = "Insert"; 
    button.ID = "Insert"; 
    button.CommandName = "Insert"; 
    button.Click += new EventHandler(insertButton_Click); 

    cell.Controls.Add(button); 
    row.Cells.Add(cell); 

    for (int i = 0; i < ((GridView)sender).Columns.Count; i++) 
    { 
     cell = new TableCell(); 
     cell.Controls.Add(new TextBox { ID = "Text" + i }); 
     row.Cells.Add(cell); 
    } 

    Table table = ((GridView)sender).Rows[0].Parent as Table; 
    table.Rows.AddAt(count + 1, row); 
} 

protected void insertButton_Click(object sender, EventArgs e) 
{ 
    lblInsert.Text = "Hello World"; 
} 

protected void CustomGridView1_RowCommand(object sender, GridViewCommandEventArgs e) 
{ 
    if (e.CommandName == "Insert") 
    { 
     lblInsert.Text = "Hello World"; 
    } 
} 
+0

总是有一个可靠的原因 - 为什么代码没有按预期运行。请具体说明并重新说明您的问题。 – adatapost 2012-01-04 03:39:34

回答

2

从你的代码中删除button.Click += new EventHandler(insertButton_Click);声明。当按下按钮时,GridView控件的RowCommand事件将被触发。欲了解更多信息 - How to: Respond to Button Events in a GridView Control

+0

我给了那个agao,它没有工作 – ONYX 2012-01-04 03:42:14

+0

我添加了RowCommand事件,那些没有响应 – ONYX 2012-01-04 03:45:13

+0

@KDM - 在代码片段中,您在行[0]添加行。在行[0]上添加TableRow的原因是什么? – adatapost 2012-01-04 03:58:43

0

您需要在数据绑定之前附加到网格的RowCommand事件。在页面或usercontrol的构造函数或Init事件上执行,而不是在数据绑定中执行。在数据绑定中,您将设置CommandName和CommandArgument属性。

希望它有帮助。