user1663870 user1663870 - 8 months ago 106
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;
sCommand.Connection.Open();
SqlDataReader reader = sCommand.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
gridView.DataSource = reader;
gridView.DataBind();
}
for (int i = 0; i < gridView.Rows.Count; i++)
{
ListBox1.Items.Add(gridView.Rows[i].Cells[3].Text);
}
}
}


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")))
{
ListBox1.Items.Add(reader.GetOrdinal("MyColumn1").ToString());
}

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: http://www.codeproject.com/Articles/25056/The-RIGHT-Way-to-Use-Checkboxes-in-a-NET-Repeater

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:

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

    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