如何使用 SQL 值动态填充列表框
我是 C# 初学者。我想做的是从 SQL 数据库中的列中提取数据并将其写入列表框。基本上,我希望表的part_num 列中的数据动态显示在列表框中。
我已经看到:
this.listParts.Items.AddRange(new object[] {"Part1", "Part2"});
但是我该如何用 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"});
}
}
任何帮助表示赞赏!
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.
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?
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为什么不使用
DataTable
作为DataSource
:您应该阅读
DataSets
甚至更好的EntityFramework
和 data-绑定。Why not use the
DataTable
asDataSource
:You should read up on
DataSets
or even better yetEntityFramework
and data-binding.