lundi 3 avril 2017

How can I get checkboxes not in datagrid selected based on database value Y and N?

I have 3 checkboxes, I want them to be selected depending on a value from sql server database. The database has 2 columns Name and Relocate. If the Relocate value is Y, I want the checkbox to be selected.

Table:

Name | Relocate |
-----------------
John | Y        | 
Jane | N        | 
Mike | Y        | 

I know I need to have the 3 checkboxes associated to John, Jane and Mike but i'm not exactly sure how to go about this. Here's what I have tried but all the checkboxes are selected. 2 of the checkboxes should be selected (John and Mike) but 1 checkbox should not (Jane).

ASP.NET

 <asp:CheckBox ID="chkRelocate" runat="server" />
 <asp:CheckBox ID="chkRelocate0" runat="server" />
 <asp:CheckBox ID="chkRelocate1" runat="server" />

Cobebehind C#

    public partial class WebForm1 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string constring = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constring))
        {
            using (SqlCommand cmd = new SqlCommand("SELECT Name, Relocate FROM Employees", con))
            {
                cmd.CommandType = CommandType.Text;
                con.Open();
                SqlDataReader dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    chkRelocate.Checked = dr["Relocate"].ToString() == "Y";
                    chkRelocate0.Checked = dr["Relocate"].ToString() == "Y";
                    chkRelocate1.Checked = dr["Relocate"].ToString() == "Y";
                }
                con.Close();
            }
        }

    }
}
}




Aucun commentaire:

Enregistrer un commentaire