C#用数据库的列名而不是列值填充组合框 [英] C# Filling Combo box with Column name of Database not Column values
问题描述
我知道已经多次询问过这个问题,并且有很多关于此的资源,但相信我,我尝试过这些,不幸的是,总是会发生同样的事情.我真的不知道为什么我的组合框列值重复.有人可以帮助我以适当的方式做这些.我在这里忘记了什么吗?谢谢
I know it's been asked many times and there's so many resources about this but believe me i tried those, Unfortunately same thing is always happen. I really don't know why my combo box column value is repeating. Can someone help me in doing these in a proper way. Did i forgot something here ? Thank you
public void FillComboBox()
{
using (var con = SQLConnection.GetConnection())
{
using (var cmd = new SqlCommand("SELECT * FROM employee_product", con))
{
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
cbox_order.Items.Add("Code").ToString();
cbox_order.Items.Add("Model").ToString();
cbox_order.Items.Add("Itemdescription").ToString();
}
}
}
}
}
这是提供的图片
推荐答案
如果您检查代码,您基本上只是将字符串Code"、Model"和Itemdescription"添加到组合框.我猜你想要的是类似的东西:
If you check the code, you are basically just adding the strings "Code", "Model" and "Itemdescription" to the combobox. I guess you want rather something like:
while (reader.Read())
{
cbox_order.Items.Add($"{reader["Code"]} {reader["Model"]} {reader["Itemdescription"]}");
}
在此代码段中,我使用 reader
从数据库中获取返回行中列的值,然后在单个 string
中显示连接这些值,即然后添加到 ComboBox
作为一个项目.
In this snippet I am using the reader
to get values of the columns in the returned row from the DB and then displaying joining those values in a single string
that is then added to the ComboBox
as an item.
如果您知道列名,为什么不直接这样做?
If you know the column names, why not just do this?
public void FillComboBox()
{
cbox_order.Items.Add("Code").ToString();
cbox_order.Items.Add("Model").ToString();
cbox_order.Items.Add("Itemdescription").ToString();
}
这篇关于C#用数据库的列名而不是列值填充组合框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!