如何将 table 列(通过 SQL 查询返回)列为 CheckedListBox 中的项目?

How can I list table columns (returned through an SQL query) as items in a CheckedListBox?

如果我有以下table:

 canAssign 
------------
     1       

有没有办法将 header 列文本(例如 canAssign 等)添加到 CheckedListBox 作为用户可以检查的标签?

我找到的所有答案都将 列为标签,如下所示:

☐ 1

而不是这个:

☐ canAssign

仅供示例,如果我使用以下内容列出 canAssign 列中的任何值,我如何更改它以列出 'canAssign' 列 header 文本?

string myString = "SELECT canAssign FROM Permissions";
using (SqlConnection myConn = new SqlConnection(globalConnectionString)) 
{
    try {
        myConn.Open();
        using (SqlCommand myComm = new SqlCommand(myString, myConn)) 
        {
            SqlDataReader myReader = myComm.ExecuteReader();
            while (myReader.Read()) {
                checkedListBox1.Items.Add(myReader["canAssign"]);
            }
        }
    } catch (Exception ex) {
        MessageBox.Show(ex.Message);
    }
}

在这种情况下,我认为您希望在 CheckedListBox.Items collection and use CheckedListBox.DisplayMember property with CheckedListBox.ValueMember

中包含自定义对象

DisplayMember

Gets or sets a string that specifies a property of the objects contained in the list box whose contents you want to display.

ValueMember

Gets or sets a string that specifies the property of the data source from which to draw the value.

例子

public class ListBoxItem
{
    public string Text { get; set; }
    public string Value { get; set; }
}

checkedListBox.DisplayMember = "Text";
checkedListBox.ValueMember = "Value";

...create connection and create command logic...
command.CommandText = "SELECT * FROM Permissions";
var reader = command.ExecuteReader();

while (reader.Read()) {

  // of course it would be better to cache that and go straight by indexes
  for(int i = 0; i < reader.FieldCount; i++) {
     var columnName = reader.GetName(i);
     // some logic to humanize values like 'canDownload' to 'Can Download'
     var label = getLabelFor(columnName);
     var value = reader.GetBoolean(i);
     checkedListBox.Items.Insert(0, new ListBoxItem(label , value));
  }
}

假设代码段中的 SQL 查询是获取特定用户的权限,并使用数据库中相同的字段名称将其显示在 CheckedListBox 中。

如果听起来不错,请阅读条目,循环以分别通过 SqlDataReader.GetName and SqlDataReader.GetBoolean 方法获取字段名称和值。

//For example...
var myString = "SELECT * FROM Permissions WHERE UserId = ....";

try
{
    using (SqlConnection myConn = new SqlConnection(globalConnectionString))
    using (SqlCommand myComm = new SqlCommand(myString, myConn))
    {
        myConn.Open();

        using (var myReader = myComm.ExecuteReader())
            if (myReader.Read())
                for (var i = 0; i < myReader.FieldCount; i++)
                    checkedListBox1.Items.Add(myReader.GetName(i), myReader.GetBoolean(i));
    }
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}