如何从数据库填充checkedlistbox并同时将其标记为已选中 [英] how to populate checkedlistbox from database and mark it as checked at the same time

查看:99
本文介绍了如何从数据库填充checkedlistbox并同时将其标记为已选中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个窗口表单,它从表(tblMinistries)加载所有数据并将其显示在一个清单框中。这项工作正常,现在我有另一个表(tblNewministries),我希望表格中的所有项目(tblNewministries)在填充它时在checkedlistbox中自动检查。 table(tblNewministries)是表的一个子集(tblMinistries)

请帮帮我



用于填充checkedlistbox的代码



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

推荐答案

您可以将检查状态设置如下

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





或者如果你需要有条件地设置



or if you need to set it conditionally

while (dr.Read())
{
    SqlDataPull = dr[0].ToString();
    bool checkedstatus = (put your condition here...); 
    cblMinistries.Items.Add(SqlDataPull,checkedstatus);
}


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


这篇关于如何从数据库填充checkedlistbox并同时将其标记为已选中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆