user1663870 user1663870 - 3 months ago 56
ASP.NET (C#) Question

C#/ASP.Net - Extract bit value of column in a gridview

I have a gridview that is SQL bound. In some of the columns there are bit values. When I use C# to get the values into the gridview, checkboxes are displayed. I need to extract the value of that column into text.

SqlConnection sConnection = new SqlConnection(MyConnectionString);
SqlCommand sCommand = new SqlCommand();
using (sConnection)
sCommand.Connection = sConnection;
sCommand.CommandText = "MyStoredProcedure";
sCommand.CommandType = CommandType.StoredProcedure;
SqlDataReader reader = sCommand.ExecuteReader();
if (reader.HasRows)
while (reader.Read())
gridView.DataSource = reader;
for (int i = 0; i < gridView.Rows.Count; i++)

The gridview column data type is 'bit'. I do not have access to the database or stored procedure to change anything there. I need to somehow extract the '0' or '1' value, but when I do it like above, the text is blank.

I also tried to use 'GetOrdinal'. It returned a True/False value from the database, but I could not figure out how to get the value for each item in the gridview.

if (!reader.IsDBNull(reader.GetOrdinal("MyColumn1")))

Answer Source

General overview:

  • You need to be able to find the CheckBox that's generated and get the value of it's "Checked" property.

  • To do this, you need to be able to use the FindControl() method on the GridViewRow.

  • To use FindControl, the CheckBox needs a predictable name.
  • To get a predictable name, you need to have that column be a TemplateColumn so that you can specify the name of the CheckBox in the markup on the ASPX page.

There's a full working set of code here:

This shows the code for a Repeater, but it's the same principle and general code for any DataBound control.

The code below should work with modifications to match your DB names:

   <ItemTemplate > 
       <asp:checkbox id="MyColumnNameCheckbox" runat="server" /> 

    string defaultvalue = "0"; // To be used to display the value of the original bit field.
    foreach (GridViewRow row in GridView1.Rows) 
     CheckBox chkBx = (CheckBox)row.FindControl("MyColumnNameCheckbox"); 

        if (chkBx != null && chkBx.Checked) 
            defaultvalue = "1";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download