SearchForKnowledge
SearchForKnowledge

Reputation: 3751

How to add a checkbox to a GridView and select/deselect based on a SQL table row value

<asp:GridView ShowHeaderWhenEmpty="false" ID="gvSubTasks" runat="server" AutoGenerateColumns="false" ClientIDMode="Static">
    <Columns>
        <asp:BoundField DataField="SN" HeaderText="SN" />
        <asp:BoundField DataField="ST" HeaderText="ST" />
        <%-- ADD ANOTHER COLUMN HERE WITH THE CHECKBOX --%>
    </Columns>
</asp:GridView>

code-behind:

string strST = @"SELECT 
            ,A345 'SN'
            ,M3w 'ST'
            ,A667 'CT' -- 0 for not complete and 1 for complete
        FROM [mydb].[dbo].[table1]";

public DataTable RT()
{
    using (SqlConnection con = new SqlConnection(gloString))
    {
        using (SqlCommand cmd = new SqlCommand())
        {
            cmd.CommandText = strST;

            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.Connection = con;
                sda.SelectCommand = cmd;

                using (DataSet ds = new DataSet())
                {
                    DataTable dt = new DataTable();
                    sda.Fill(dt);

                    return dt;
                }
            }
        }
    }
}

gvSubTasks.DataSource = RT();
gvSubTasks.DataBind();

How can I add a checkbox in my gridview per row, with a header "Complete" and based on the CT, pre-select the checkbox if it is 1 and not select the checkbox if it is 0.

Upvotes: 0

Views: 162

Answers (2)

fubo
fubo

Reputation: 45947

just add

  <asp:CheckBoxField DataField="CT" HeaderText="CT" </asp:CheckBoxField> 

if CT is a CHAR value you can modify your statement like CASE WHEN CT = '1' THEN 1 ELSE 0 END as CT

Upvotes: 0

Mairaj Ahmad
Mairaj Ahmad

Reputation: 14604

Add this for a column with checkbox

<asp:TemplateField HeaderText="Complete">
  <ItemTemplate>
  <asp:CheckBox ID="CheckBox1" runat="server" Checked='<%# Eval("CT").ToString() == "1" ? true : false %>' />
  </ItemTemplate>
 <ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>

Upvotes: 1

Related Questions