Click here to Skip to main content
15,898,373 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a windows form which loads all data from a table (tblMinistries) and displays it in a checklistbox. This work works correctly, now i have another table (tblNewministries) and i want all the items in the table (tblNewministries) to be checked automaticaly in the checkedlistbox when it is populated. table (tblNewministries) is a subset of table (tblMinistries)
Please help me out

code for populating the checkedlistbox

public void PopuMinistry()
        {
            SqlConnection conn = new SqlConnection("Data Source=USER-PC;Initial Catalog=PIWCDB;User ID=sa;Password=mike");
            if (conn.State != ConnectionState.Open)
            {
                conn.Open();
            }
            string SqlDataPull = ("select Homecellname from tblministries order by Homecellname");
            SqlCommand cmd = new SqlCommand(SqlDataPull);
            cmd.Connection = conn;
            cmd.CommandType = CommandType.Text;
            SqlDataReader dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                SqlDataPull = dr[0].ToString();
                cblMinistries.Items.Add(SqlDataPull);
            }
            dr.Close();
        }
Posted
Updated 6-May-14 22:24pm
v2

you can set the checked states as below
C#
cblMinistries.Items.Add(SqlDataPull,true);


or if you need to set it conditionally
C#
while (dr.Read())
{
    SqlDataPull = dr[0].ToString();
    bool checkedstatus = (put your condition here...); 
    cblMinistries.Items.Add(SqlDataPull,checkedstatus);
}
 
Share this answer
 
v2
C#
private void PopuMinistry()
{
    using (SqlConnection conn = new SqlConnection())
    {
        conn.ConnectionString = ConfigurationManager
                .ConnectionStrings["constr"].ConnectionString;
        using (SqlCommand cmd = new SqlCommand())
        {
            cmd.CommandText = "select Homecellname from tblministries order by Homecellname";
            cmd.Connection = conn;
            conn.Open();
            using (SqlDataReader sdr = cmd.ExecuteReader())
            {
                while (sdr.Read())
                {
                    ListItem item = new ListItem();
                    item.Text = sdr["Homecellname"].ToString();
                    item.Value = sdr["Homecellname"].ToString();
                    item.Selected = true;
                    chkHobbies.Items.Add(item);
                }
            }
           conn.Close();
        }
    }
}
 
Share this answer
 
Comments
mikeoabban 7-May-14 4:31am    
thank you very much for your help. i have modify the question a little bit . please help me out

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900