簡體   English   中英

從數據庫和列表中填充 CheckedListBox

[英]Populate CheckedListBox from Database and list

我正在嘗試從列表中填充選中列表框

我的方法:

SqlCommand getlocationnames = new SqlCommand("allLocationNames", conn);
getlocationnames.CommandType = CommandType.StoredProcedure; 
conn.Open();
SqlDataReader dr = getlocationnames.ExecuteReader();
List<locations> results = new List<locations>();
while (dr.Read())
{
  locations newItem = new locations();
  newItem.loc_name = dr.GetString(0);
  results.Add(newItem);
}
dr.Close();

foreach (var result in results)
{
  checkedListBox1.Items.Add(result);
}

有人看到我在這里缺少什么嗎?

試試這個方法(而不是兩個循環,這個方法使用一個循環,這提高了應用程序的速度):

Output:

輸出

SQL (已在數據庫中創建的StoredProcedure ):

Create Procedure AllValues As Select * From YourTableName
Go

C#:

    System.Data.SqlClient.SqlConnection Connection = new System.Data.SqlClient.SqlConnection("Data Source =.;" + "AttachDbFilename = " + Application.StartupPath + @"\YourDataBaseName.mdf;" + "Integrated Security = True;");
    private void AddButton_Click(object sender, EventArgs e)
    {
        Connection.Open();
        System.Data.SqlClient.SqlCommand Command = new System.Data.SqlClient.SqlCommand();
        Command.Connection = Connection;
        Command.CommandType = CommandType.StoredProcedure;
        Command.CommandText = "AllValues";
        System.Data.SqlClient.SqlDataReader DataReader = Command.ExecuteReader();
        List<object> results = new List<object>();
        //DataReader[0] means the first column of the table
        //DataReader[1] means the second column of the table
        while (DataReader.Read())
        {
            results.Add(string.Join(null, "Country = ", DataReader[0].ToString(), "\t\t", "Capital = ", DataReader[1].ToString()));
        }
        Connection.Close();
        checkedListBox.Items.Clear();
        checkedListBox.Items.AddRange(results.ToArray());
    }
    private void ClearButton_Click(object sender, EventArgs e)
    {
        checkedListBox.Items.Clear();
    }

測試:

Visual Studio 2017 , .NET Framework 4.5.2 , Windows Forms , SQL Server 12.0.6024.0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM