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

后端 未结 2 1807
执念已碎
执念已碎 2021-01-21 04:23

If I have the following table:

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

Is there a way to add the column header text (e.g., canAssign

2条回答
  •  一整个雨季
    2021-01-21 05:04

    In this case I think you'd like to have custom objects in 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.

    Example

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

提交回复
热议问题