我所拥有的是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();
}
答案 0 :(得分:2)
为什么不简单地从“SQLServerPull”方法返回一组数据,而不是耦合UI和数据? UI可以以其认为合适的任何方式使用原始数据,例如,填充ComboBox。
答案 1 :(得分:-1)
为什么不这样做
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;
}
或返回DataTable
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;
}