Click here to Skip to main content
15,901,283 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I using the same datatable that has a Boolean field to bind it to 2 different gridviews. One gridview is designed in aspx file and there is a template column for Boolean field
<asp:TemplateField>
<itemtemplate>
<asp:CheckBox ID="cb" runat="server" Width="100px"
Checked='<%# Convert.ToBoolean(Eval("boolField")) %>' />

<itemstyle horizontalalign="Center">

this works fine
but the second grid is built in the code behind

gr2.Columns.Clear();

for (int i = 0; i < dt.Rows.Count; i++)
{
BoundField dF = new BoundField();

dF.DataField = dt.Rows[i].ItemArray[0].ToString();
dF.HeaderText = dt.Rows[i].ItemArray[1].ToString();

gr2.Columns.Add(dF);
}

gr2.DataSource = dt;
gr2.DataBind();

this also works but shows bool column values as True/False.
I'd like it either to display Yes/No or check boxes. I know how to implement Checkbox via ItemTemplate in the code behind but can't figure out how to populate check boxes, in other words how to accomplish Checked='<%# Convert.ToBoolean(Eval("boolField")) %>' in the code behind.
Posted

1 solution

In order to implement it through codebehind please find below steps:

Step1: Add OnRowDataBound property in griview.
ASP.NET
<asp:gridview id="GridView1" runat="server" autogeneratecolumns="False" onrowdatabound="GridView1_RowDataBound" cellpadding="4" forecolor="#333333" gridlines="None" xmlns:asp="#unknown">
	<columns>
		<asp:boundfield datafield="UserId" headertext="User Id" />
		<asp:templatefield headertext="Select">
		<itemtemplate>
			<asp:checkbox id="chkSelect" runat="server" />
		</itemtemplate>
	</asp:templatefield></columns>
</asp:gridview>


Step2: Add OnRowDataBound method in code behind.
C#
 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
        //Check for the row type, which should be data row
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            //Find the check boxes and assign the values from the data source
            ((CheckBox)e.Row.FindControl("chkSelect")).Checked = Convert.ToBoolean(((DataRowView)e.Row.DataItem)[1]);
        }
}


http://www.c-sharpcorner.com/uploadfile/MohanKumar.R/selecting-checkboxes-inside-the-gridview-control/[^]
 
Share this answer
 
Comments
esb77 14-Sep-15 15:23pm    
did you read my question? I have an empty gridview in aspx file
<asp:GridView id="gr2" runat="server" AutoGenerateColumns="False">
<columns>

I build columns in the code-behind

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900