如何向GridView添加复选框,并根据SQL表行值选择/取消选择

时间:2015-06-03 14:45:48

标签: c# html asp.net gridview datatable

<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>

代码隐藏:

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();

如何在每行的gridview中添加一个复选框,标题为“完成”并基于CT,如果是1则预选复选框,如果是0则不选中复选框它是composer.json

2 个答案:

答案 0 :(得分:1)

为带有复选框

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

答案 1 :(得分:0)

只需添加

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

如果CT是CHAR值,您可以修改您的语句,如CASE WHEN CT = '1' THEN 1 ELSE 0 END as CT