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

后端 未结 2 1804
执念已碎
执念已碎 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 04:44

    Assuming the SQL query in your code snippet is to get the permissions of a specific user and display them in a CheckedListBox using the same fields names from the database.

    If that sounds right, read the entry, loop to get the fields names and values through the SqlDataReader.GetName and SqlDataReader.GetBoolean methods respectively.

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

提交回复
热议问题