Search code examples
c#asp.netgridviewautogeneratecolumn

How to read a boolean that was bound to a Gridview with autogenerated columns


I am binding the Session Data to a Gridview with autogenerated columns in order to retrieve that data in case the session expired.

<asp:GridView ID="GridView_SessionTable" runat="server" AutoGenerateColumns="true"/> 

Boolean columns are displayed as checkboxes, but however I try to retrieve the value for those columns, nothing is returned.

    protected void ScanGrid(object sender, EventArgs e)
    {

        foreach (GridViewRow row in GridView_SessionTable.Rows)
        {
            Test.Text = Test.Text + "ID: " + row.Cells[0].Text + "Boolean Value:" + row.Cells[4].Text;
        }
    }

Every other columns that is not boolean is retrieved correctly! There must be a way to get that value. If I look at the source file I see that the cells html content is:

<span class="aspNetDisabled" title="Selectable"><input id="GridView_SessionTable_ctl00_0" type="checkbox" name="GridView_SessionTable$ctl02$ctl00" checked="checked" disabled="disabled" /></span>

Solution

  • The check box when rendered for Boolean columns in a GridView becomes an child control of the cells[] collection.

    So, you need this:

    ((CheckBox)row.Cells[2].Controls[0]).Checked
    

    The above returns a Boolean value. You could thus add to above:

    ((CheckBox)row.Cells[2].Controls[0]).Checked.ToString()