Best Example for your issue.
The CheckBox can be dynamically enabled and disabled in GridView in the following two ways
1. Using Eval function.
2. Using OnRowDataBound event.
The GridView is populated using some dummy records using DataTable.
using System.Data;
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id"), new DataColumn("Name"), new DataColumn("Status") });
dt.Rows.Add(1, "John Hammond", "Absent");
dt.Rows.Add(2, "Mudassar Khan", "Present");
dt.Rows.Add(3, "Suzanne Mathews", "Absent");
dt.Rows.Add(4, "Robert Schidner", "Present");
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
In this technique one has to write the condition within the <% %> tags. Below you will notice that I am matching the value of the Status field with the string Present and thus for all the records for which the Status is Present, the CheckBox will be enabled and for the remaining it will be disabled.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" Enabled='<%# Eval("Status").ToString().Equals("Present") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="150" />
<asp:BoundField DataField="Status" HeaderText="Status" ItemStyle-Width="100" />
</Columns>
</asp:GridView>
Another way is to make use of OnRowDataBound event of GridView. Thus first you need to assign OnRowDataBound event handler to the GridView as show below.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowDataBound="OnRowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="150" />
<asp:BoundField DataField="Status" HeaderText="Status" ItemStyle-Width="100" />
</Columns>
</asp:GridView>
Then you need to implement the OnRowDataBound event handler in the code behind and then enable and disable the CheckBox conditionally by matching the value with the Status field.
Here the value of the Status field is matched with the string Absent and if it matches then the CheckBox is disabled.
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
CheckBox CheckBox1 = (e.Row.FindControl("CheckBox1") as CheckBox);
if (e.Row.Cells[2].Text == "Absent")
{
CheckBox1.Enabled = false;
}
}
}