C# 如何使用 SQL 值动态填充列表框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9116807/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to populate listbox dynamically with SQL values
提问by Andrew De Forest
I am a C# beginner. What I am trying to do is pull data from a column in a SQL database and write it to a listbox. Basically, I want the data in the part_num column of my table to be displayed dynamically in the listbox.
我是 C# 初学者。我想要做的是从 SQL 数据库中的列中提取数据并将其写入列表框。基本上,我希望我的表的 part_num 列中的数据在列表框中动态显示。
I have seen:
我见过:
this.listParts.Items.AddRange(new object[] {"Part1", "Part2"});
But how would I go about replacing “Part1” and “Part2” with dynamically generated values from SQL?
但是我将如何用 SQL 动态生成的值替换“Part1”和“Part2”?
public mainForm()
{
InitializeComponent();
SqlConnection conn = new SqlConnection(
"Data Source=DBELL;Initial Catalog=part_table;Integrated Security=True");
conn.Open();
DataSet ds = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(
"SELECT part_num from customParts", conn);
adapter.Fill(ds);
foreach (DataRow row in ds.Tables[0].Rows)
{
for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
this.listParts.Items.AddRange(new object[] {"Part1", "Part2"});
}
}
Any help is appreciated!
任何帮助表示赞赏!
采纳答案by Mithrandir
Why not use the DataTableas DataSource:
为什么不使用DataTableas DataSource:
public mainForm()
{
InitializeComponent();
SqlConnection conn = new SqlConnection("Data Source=DBELL;Initial Catalog=part_table;Integrated Security=True");
conn.Open();
DataSet ds = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(
"SELECT part_num from customParts", conn);
adapter.Fill(ds);
this.listParts.DataSource = ds.Tables[0];
this.listParts.DisplayMember = "part_num";
}
You should read up on DataSetsor even better yet EntityFrameworkand data-binding.
您应该阅读DataSets甚至更好的EntityFramework数据绑定。

