Add GridView Button Dynamically

2019-08-10 08:40发布

问题:

I have a asp.net form with a button1 and a gridview1. When i click button1, it performs a "select * from table" query and dumps the output to the gridview1.

 //update Gridview1
 GridView1.DataSource = _DataTable;
 GridView1.DataBind();

I have set the autogeneratecolums property ti true for this to work.

But now what i want is that for each row in this gridView, i now want to create a new column called "Click" which contains a button for each row.

 //Refetch data

 DataColumn dc = new DataColumn("Click", typeof(ButtonField));
 _DataTable.Columns.Add(dc);



 ButtonField _ButtonField = new ButtonField();
 _ButtonField.ButtonType = ButtonType.Button;
 _ButtonField.Text = "Testing";

 _DataTable.Rows[0].SetField("Click", _ButtonField);
 //update Gridview
 GridView1.DataSource = _DataTable;
 GridView1.DataBind();

Its not working. Help

回答1:

Change your code to this. This will add you a button on your Gridview. You can then handle its click event and write select code.

ButtonField buttonField = new ButtonField
{
    ButtonType = ButtonType.Button, 
    Text = "Testing"
};
GridView1.Columns.Add(buttonField);
GridView1.DataSource = _DataTable;
GridView1.DataBind();