如何在GridView中动态添加按钮 [英] how to add button in gridview dynamically

查看:105
本文介绍了如何在GridView中动态添加按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在动态创建 gridview ...现在,我想在其中添加一些按钮,并添加其相对的rowCommand事件.请帮助我做到这一点.这就是我在代码中动态创建GridView的方式

i am creating gridview dynamically... Now i want to add some buttons in that and also add their relative rowCommand Events. please help me to do this. this is how I create GridView's dynamically in my code

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);
            }

推荐答案

尽管我没有对其进行测试,但从逻辑上讲,它类似于以下内容:

Though i don't test it but logically it would be like below:

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 循环中.

Where e would be GridViewRowEventArgs .And those code would be placed in your for/foreach loop.Probably like..

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
     }
   }
}

也可以查看..

这篇关于如何在GridView中动态添加按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆