如何将表列(通过SQL查询返回)列出为CheckedListBox中的项目? [英] How can I list table columns (returned through an SQL query) as items in a CheckedListBox?
问题描述
如果我有下表:
canAssign------------1个
是否可以将列标题文本(例如 canAssign
等)添加到 CheckedListBox
作为用户可以检查的标签?
我找到的所有答案都将 value 列为标签,如下所示:
☐1
代替此:
☐canAssign
仅作为示例,如果我使用以下内容列出canAssign列中的任何值,我该如何更改它以列出"canAssign"列标题文本?
string myString ="SELECT canAssign FROM Permissions";使用(SqlConnection myConn =新的SqlConnection(globalConnectionString)){尝试 {myConn.Open();使用(SqlCommand myComm = new SqlCommand(myString,myConn)){SqlDataReader myReader = myComm.ExecuteReader();while(myReader.Read()){CheckedListBox1.Items.Add(myReader ["canAssign"]);}}} catch(ex ex例外){MessageBox.Show(ex.Message);}}
假设您的代码段中的SQL查询是获取特定用户的权限,并使用数据库中相同的字段名称将其显示在CheckedListBox中./p>
如果这听起来不错,请阅读该条目,循环通过 SqlDataReader.GetBoolean 方法.
<代码>//例如...var myString =选择*从权限WHERE UserId = ....";尝试{使用(SqlConnection myConn =新的SqlConnection(globalConnectionString))使用(SqlCommand myComm = new SqlCommand(myString,myConn)){myConn.Open();使用(var myReader = myComm.ExecuteReader())如果(myReader.Read())对于(var i = 0; i< myReader.FieldCount; i ++)CheckedListBox1.Items.Add(myReader.GetName(i),myReader.GetBoolean(i));}}抓住(前例外){MessageBox.Show(ex.Message);}
If I have the following table:
canAssign
------------
1
Is there a way to add the column header text (e.g., canAssign
, etc.) to the CheckedListBox
as the labels that a user can check?
All answers I've found list the value as the labels, like this:
☐ 1
Instead of this:
☐ canAssign
For Example Only, If I'm using the following to list whatever value is in the canAssign column, how could I change this to list the 'canAssign' column header text?
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);
}
}
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);
}
这篇关于如何将表列(通过SQL查询返回)列出为CheckedListBox中的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!