基于数据库数据检查CheckedBoxList中的项目 [英] Checking Items in a CheckedBoxList based on Database Data

查看:92
本文介绍了基于数据库数据检查CheckedBoxList中的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在很难根据数据库数据检查CheckedBoxList中的项目几周了。

i尝试了这段代码但是收到错误无法将带有[]的索引应用于'System'类型的表达式.Windows.Forms.CheckedListBox'来自这行代码DataRowView row =(DataRowView)this.cblMinistries [i];请帮帮我

代码

am having difficulty Checking Items in a CheckedBoxList based on Database Data for some weeks now.
i tried this code but am getting the error " Cannot apply indexing with [] to an expression of type 'System.Windows.Forms.CheckedListBox' " from this line of code "DataRowView row = (DataRowView)this.cblMinistries[i];" please help me out
codes

public void minsearch()
{
    SqlConnection conn = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"]);
    conn.ConnectionString = "Data Source=USER-PC;Initial Catalog=PIWCDB;User ID=sa;Password=mike";
    conn.Open();
    
    string sqlQuery = "SELECT Ministryname FROM tblMembershipministry WHERE FormattedMembershipid = '" + this.txtMembershipid.Text + "'";
    SqlCommand cmd = new SqlCommand();
    cmd.Connection = conn;
    cmd.CommandText = sqlQuery;
    cmd.CommandType = System.Data.CommandType.Text;
    
    try
    {
        System.Data.SqlClient.SqlDataReader dr = null;
        dr = cmd.ExecuteReader();
    
        while (dr.Read())
        {                   
          for (int i = 0; i < cblMinistries.Items.Count; i++)
            {
                DataRowView row = (DataRowView)this.cblMinistries[i];
                if (row[cblMinistries.ValueMember].ToString() == dr["FormattedMembershipid"].ToString())
                {
                    cblMinistries.SetItemChecked(i, true);
                }
            }
        }
        dr.Close();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

推荐答案

更改

change
DataRowView row = (DataRowView)this.cblMinistries[i];

to

to

DataRowView row = (DataRowView)this.cblMinistries.Items[i];





并且在下一行中,您使用 dr [FormattedMembershipid] 检查项目的值成员,但是您没有在select语句中选择此列。因为你已经在下面的条件中使用了这个列值,你可以直接检查如下





And also in next line you are check the value member of the item with dr["FormattedMembershipid"] but you are not selecting such column in your select statement. since you have used this column value in where condition you can directly check as below

if (row["ValueMembercolumnName"].ToString() == this.txtMembershipid.Text)
{

}


你可以将数据库值与checkboxlist项目进行比较如下:



You can compare the database value with checkboxlist items as following:

while (dr.Read())
 {
    foreach (ListItem li in cblMinistries.Items)
    {
       if (li.Value == dr["FormattedMembershipid"].ToString())
          li.Selected = true;
    }
 }


这篇关于基于数据库数据检查CheckedBoxList中的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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