问题
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);
}
回答1:
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);
}
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++)
Then make an button event handler:
protected void button_Clicked(object sender, EventAgrs e)
{
if (sender is Button)
{
try
{
String value = ((Button)sender).CommandArgument;
}
catch
{
//Check for exception
}
}
}
Also can view..
- http://forums.asp.net/t/1234622.aspx
回答2:
I know you did it because you asked before a few months, but I just answered for the others who research about this point.
just do this at the function to displayed:
DataGridViewButtonColumn col = new DataGridViewButtonColumn();
col.UseColumnTextForButtonValue = true;
col.Text = "ADD";
col.Name = "MyButton";
dataGridView1.Columns.Add(col);
来源:https://stackoverflow.com/questions/17588934/how-to-add-button-in-gridview-dynamically