I need to evaluate a condition from a database using linq so that a checkbox for each row enables or no, I think it can be done using the RowDataBound
or CreateRow
event.
i.e, I have a gridview with several columns that are fillied with a datasource from linq. Out of all those columns two of them have each a checkbox, so if a record from the base is equal to one, only column2 with the checkbox for that row is enabled, if it's not equal to one, then it stays as it is.
I have prepared you simplified sample how this can be done using databinding.
First aspx code, take notice I have used ValidateRecord to validate single record:
<asp:GridView ID="GridView1" runat="server" DataKeyNames="Id" DataSourceID="ObjectDataSource1" AutoGenerateColumns="true">
<Columns>
<asp:TemplateField HeaderText="Check">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" Enabled='<%# ValidateRecord(Eval("RowState")) %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" SelectMethod="GetItems" TypeName="WebTester.DataGridTester">
</asp:ObjectDataSource>
End now the code behind. GetItems is used only to generate some demo data, the point is inside ValidateRecord:
public bool ValidateRecord(object value)
{
return (value as int?) == 1;
}
public static DataTable GetItems()
{
//generate some demo data...
DataTable dt = new DataTable();
dt.Columns.Add("RowState", typeof(int?));
dt.Columns.Add("Id",typeof(int));
dt.Columns.Add("col1", typeof(string));
dt.Columns.Add("col2", typeof(string));
dt.Columns.Add("col3", typeof(string));
dt.Columns.Add("col4", typeof(string));
dt.Columns.Add("col5", typeof(string));
dt.Columns.Add("col6", typeof(string));
dt.Columns.Add("col7", typeof(string));
dt.Rows.Add(new object[] {1, 1,"some","data","in","first","row", ".", ".." });
dt.Rows.Add(new object[] {0, 2, "second", "record", "inside", "demo", "datatable", "-", "--" });
return dt;
}
So final result will look something like this:
First row checkbox is enabled, second is disabled.
Happy coding!