且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将SQL Server查询结果分配给C#中的CheckedListBox?

更新时间:2023-01-20 20:33:49

我发现了怎么做这里;这样可行:



  string  constring = Properties.Settings.Default .CPSDataConnection; 
使用(SqlConnection con = new SqlConnection(constring))
{
使用(SqlCommand cmd = new SqlCommand( SELECT单位FROM MasterUnits ORDER BY单位,con))
{
cmd.CommandType = CommandType.Text;
使用(SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
sda.Fill(dt);
((ListBox)MemberListBox).DataSource = dt;
((ListBox)MemberListBox).DisplayMember = Unit;
((ListBox)MemberListBox).ValueMember = Unit;
}
}
}


I can retrieve the data I want in LINQPad.

Trying to get it programmatically *and* assign it to a CheckedListBox in C#, though, has not yet worked. My code is:

var sqlDal = new SQLServer(Properties.Settings.Default.PltypusDataConnection) { CommandTimeout = 120 };
DataSet dsMembers = sqlDal.runSQLDataSet("SELECT PoisonToeLength FROM Platypi ORDER BY PoistonToeLength", "PoisonToes");
var dtMembers = dsMembers.Tables[0];
MemberListBox.DataSource = dtMembers;



All this does is fill the CheckedListBox (MemberListBox) with a slew of items displaying "System.Data.DataRowView"

How can I display the values from the query in the CheckedListBox?

I found out how to do it here ; so this works:

string constring = Properties.Settings.Default.CPSDataConnection;
using (SqlConnection con = new SqlConnection(constring))
{
    using (SqlCommand cmd = new SqlCommand("SELECT Unit FROM MasterUnits ORDER BY Unit", con))
    {
        cmd.CommandType = CommandType.Text;
        using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
        {
            DataTable dt = new DataTable();
            sda.Fill(dt);
            ((ListBox)MemberListBox).DataSource = dt;
            ((ListBox)MemberListBox).DisplayMember = "Unit";
            ((ListBox)MemberListBox).ValueMember = "Unit";
        }
    }
}