【问题标题】:how to add button in gridview dynamically如何在gridview中动态添加按钮
【发布时间】:2013-11-16 06:46:21
【问题描述】:

我正在动态创建gridview...现在我想在其中添加一些按钮并添加它们的相关 rowCommand 事件。请帮我这样做。这就是我在代码中动态创建 GridView 的方式

for (int i = 0; i < dtEmployees.Rows.Count; i++)
            {
                TableRow tr = new TableRow();
                TableCell tc = new TableCell();


                GridView gv = new GridView();
                gv.ID = "gv" + dtTasks.Rows[i]["TaskID"].ToString() + dtEmployees.Rows[i]["EmpID"].ToString();

                DataTable dt = dtTasks.Clone();

                foreach (DataRow dr in dtTasks.Rows)
                {
                    if (dr["EmpID"].ToString() == dtEmployees.Rows[i]["EmpID"].ToString())
                    {
                        dt.Rows.Add(dr.ItemArray);
                    }
                }
                gv.DataSource = dt;
                gv.DataBind();
                tc.Controls.Add(gv);
                tr.Cells.Add(tc);
                tblMain.Rows.Add(tr);
            }

【问题讨论】:

    标签: asp.net gridview dynamically-generated


    【解决方案1】:

    虽然我没有测试它,但逻辑上它会像下面这样:

    if(e.Row.RowIndex > -1) 
    { 
        Button button = new Button();
        button.CommandArgument = dt.Rows[e.Row.RowIndex][i].ToString(); 
        button.Attributes.Add("OnClick", "button_Clicked");
    
        e.Row.Cells[i].Controls.Add(button);
    }
    

    其中 e 将是 GridViewRowEventArgs 。这些代码将放在您的 for/foreach 循环中。可能就像......

    for (int i = 0; i < gv.Rows.Count; i++)
    

    然后制作一个按钮事件处理程序

    protected void button_Clicked(object sender, EventAgrs e)
    {
       if (sender is Button)
       {
         try
         {
            String value = ((Button)sender).CommandArgument;
         }
         catch
         {
           //Check for exception
         }
       }
    }
    

    也可以查看..

    【讨论】:

      【解决方案2】:

      我知道你这样做是因为你在几个月前问过,但我只是为其他研究这一点的人回答了。

      只需在要显示的函数处执行此操作:

              DataGridViewButtonColumn col = new DataGridViewButtonColumn();
              col.UseColumnTextForButtonValue = true;
              col.Text = "ADD";
              col.Name = "MyButton";
              dataGridView1.Columns.Add(col);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-15
        相关资源
        最近更新 更多