Reputation: 9414
I generate CheckBoxField in GridView dynamically. but in output the CheckBox is disabled.
How to enable CheckBox dynamically.
I know if add a TemplateField in GridView markup my problem is solved but i won't add TemplateField in GridView
ASPX:
<asp:GridView ID="GridView2" runat="server">
</asp:GridView>
Code behind:
DataTable dTable = new DataTable();
dTable.Columns.Add("c1", typeof(bool));
DataRow r = dTable.NewRow();
r[0] = false;
dTable.Rows.Add(r);
r = dTable.NewRow();
r[0] = true;
dTable.Rows.Add(r);
CheckBoxField chkField = new CheckBoxField();
chkField.DataField = "c1";
chkField.HeaderText = "CheckBox";
chkField.ReadOnly = false;
GridView2.Columns.Add(chkField);
GridView2.DataSource = dTable;
GridView2.DataBind();
Upvotes: 1
Views: 9605
Reputation: 9414
Optimize Decker97 answer:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}
protected void BindGrid()
{
DataTable dTable = new DataTable();
dTable.Columns.Add("c1", typeof(bool));
DataRow r = dTable.NewRow();
r[0] = false;
dTable.Rows.Add(r);
r = dTable.NewRow();
r[0] = true;
dTable.Rows.Add(r);
GridView2.DataSource = dTable;
GridView2.DataBind();
}
protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
CheckBox cb = (CheckBox)e.Row.Cells[0].Controls[0];
cb.Enabled = true;
}
}
Upvotes: 0
Reputation: 1653
I put code in the RowDataBound event to enable the checkbox:
protected void Page_Load(object sender, EventArgs e)
{
this.GridView2.RowDataBound += GridView2_RowDataBound;
BindGrid();
}
void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.Cells[0].GetType() == typeof(System.Web.UI.WebControls.DataControlFieldCell))
{
TableCell tc = e.Row.Cells[0];
if (tc.Controls.Count > 0)
{
CheckBox cb = (CheckBox)tc.Controls[0];
if (!(cb == null))
{
cb.Enabled = true;
}
}
}
}
private void BindGrid()
{
DataTable dTable = new DataTable();
dTable.Columns.Add("c1", typeof(bool));
DataRow r = dTable.NewRow();
r[0] = false;
dTable.Rows.Add(r);
r = dTable.NewRow();
r[0] = true;
dTable.Rows.Add(r);
//CheckBoxField chkField = new CheckBoxField();
//chkField.DataField = "c1";
//chkField.HeaderText = "CheckBox";
//chkField.ReadOnly = false;
//GridView1.Columns.Add(chkField);
GridView2.DataSource = dTable;
GridView2.DataBind();
}
}
Upvotes: 2