Ex: mypage.aspx?num=xxx
How can I add a num checkbox column to Gridview in mypages by code-behind?
I had added num columns to Datatable with parameter typeof(bool) but when I loaded mypage, the checkboxes were disabled so I can't check them.
Ex: mypage.aspx?num=xxx
How can I add a num checkbox column to Gridview in mypages by code-behind?
I had added num columns to Datatable with parameter typeof(bool) but when I loaded mypage, the checkboxes were disabled so I can't check them.
This is my grid aspx code
<asp:GridView ID="gv" runat="server" AutoGenerateColumns="false">
<Columns>
</Columns>
</asp:GridView>
First of all add num number of template fields to your gridview
protected void Page_PreInit(object sender, EventArgs e)
{
int num = Request.QueryString["num"];
for (int i = 0; i < num; i++)
{
TemplateField tf = new TemplateField();
tf.HeaderText = "Status";
gv.Columns.Add(tf);
}
}
After adding template feilds, now we will add checkboxes to the gridview. We write a function to add checkboxes. Below is the code
private void AddCheckBox()
{
int num = Request.QueryString["num"];
for (int i = 0; i < num; i++)
{
foreach (GridViewRow row in gv.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox cb = new CheckBox();
cb.Checked = true;
row.Cells[i].Controls.Add(cb);
}
}
}
}
Now place this function in your grid databound event.
protected void gv_DataBound(object sender, EventArgs e)
{
AddCheckBox();
}
At the end also call the function in the page load event so first time when grid loads it shows checkboxes are checked
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
AddCheckBox();
}
}
To check my code: I add a bound feild to grid view and bind the grid view with a datatable:
<asp:GridView ID="gv" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Data" HeaderText="Data" />
</Columns>
</asp:GridView>
and in code behind in page_load event i add the following code
DataTable dt = new DataTable();
dt.Columns.Add("Data");
DataRow dr = dt.NewRow();
dr[0] = "Test";
dt.Rows.Add(dr);
gv.DataSource = dt;
gv.DataBind();
and also made 1 change in the function AddCheckBox as
for (int i = 1; i < num + 1; i++)
The above change is made because I have a databound feild at index 0 of the grid view columns so I changed it to start from 1.
and here is the result ( page output )
Data Status Status Status Status Status Status Status Status Status Status
Test Checked Checked Checked Checked Checked Checked Checked Checked Checked Checked
Checked is used for checkbox is checked