[英]How to delete items from a ComboBox at runtime using C# / WinForms
[英]C# winforms adding items from a combobox to from a seperate class
我在Form1.cs [Design]上拥有的是组合框,并且创建了一个名为SQLOperations的单独类来操作SQL东西,如何传递给组合框?
public static void SQLServerPull()
{
string server = "p";
string database = "IBpiopalog";
string security = "SSPI";
string sql = "select server from dbo.ServerList";
SqlConnection con = new SqlConnection("Data Source=" + server + ";Initial Catalog=" + database + ";Integrated Security=" + security);
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader dr = cmd.ExecuteReader();
while(dr.Read())
{
//this below doesnt work because it can't find the comboBox
comboBox1.Items.Add(dr[0].ToString());
//the rest of the code works fine
}
con.Close();
}
为什么不简单地从“ SQLServerPull”方法返回一组数据,而不是将UI和数据耦合在一起? UI可以以其认为合适的任何方式使用该原始数据,例如,填充ComboBox。
为什么不这样做
public static System.Collections.Generic.List<string> SQLServerPull()
{
System.Collections.Generic.List<string> Items = new System.Collections.Generic.List<string>();
string server = "p";
string database = "IBpiopalog";
string security = "SSPI";
string sql = "select server from dbo.ServerList";
using(SqlConnection con = new SqlConnection("Data Source=" + server + ";Initial Catalog=" + database + ";Integrated Security=" + security))
{
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader dr = cmd.ExecuteReader();
while(dr.Read())
{
//Add the items to the list.
Items.Add(dr[0].ToString());
//this below doesnt work because it can't find the comboBox
//comboBox1.Items.Add(dr[0].ToString());
//the rest of the code works fine
}
}
//Return the list of items.
return Items;
}
或返回一个数据表
public static System.Data.DataTable SQLServerPull()
{
System.Data.DataTable dt = new System.Data.DataTable();
string server = "p";
string database = "IBpiopalog";
string security = "SSPI";
string sql = "select server from dbo.ServerList";
using(SqlConnection con = new SqlConnection("Data Source=" + server + ";Initial Catalog=" + database + ";Integrated Security=" + security))
{
con.Open();
using(SqlCommand cmd = new SqlCommand(sql, con))
{
using(SqlDataReader dr = cmd.ExecuteReader())
{
dt.Load(dr);
}
}
}
return dt;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.