I'm trying to populate a checkedlistbox from a list
my approach:
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);
}
Does some one see what I'm missing here?
CodePudding user response:
Try this approach (instead of two loops, one loop is used in this approach, which increases the application's speed):
Output:
SQL
(a StoredProcedure
which is already created in the database):
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();
}
Tested in:
Visual Studio 2017
, .NET Framework 4.5.2
, Windows Forms
, SQL Server 12.0.6024.0