C# 从数据库填充组合框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12494634/
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
Fill Combobox from database
提问by Ahmed Sharkawy
I have an error with a combobox
我有一个组合框错误
My code:
我的代码:
SqlConnection conn = new SqlConnection();
try
{
conn = new SqlConnection(@"Data Source=SHARKAWY;Initial Catalog=Booking;Persist Security Info=True;User ID=sa;Password=123456");
string query = "select FleetName, FleetID from fleets";
SqlCommand cmd = new SqlCommand(query, conn);
cmd.CommandText = query;
conn.Open();
SqlDataReader drd = cmd.ExecuteReader();
while (drd.Read())
{
cmbTripName.Items.Add(drd["FleetName"].ToString());
cmbTripName.ValueMember = drd["FleetID"].ToString();
cmbTripName.DisplayMember = drd["FleetName"].ToString();
}
}
catch
{
MessageBox.Show("Error ");
}
The data is presented in the combobox, but when you change the selection valuemember the displaymember does not change.
数据显示在组合框中,但是当您更改选择值成员时,显示成员不会更改。
It's working now but when I click the button to show the data
它现在正在工作,但是当我单击按钮显示数据时
private void button1_Click(object sender, EventArgs e)
{
label1.Text = cmbTripName.DisplayMember;
label2.Text = cmbTripName.ValueMember;
}
This is displayed:
这是显示:
FleetName
FleetID
FleetName
FleetID
It does not display the value
它不显示值
采纳答案by Pilgerstorfer Franz
You will have to completely re-write your code. DisplayMemberand ValueMemberpoint to columnNames! Furthermore you should really use a using block- so the connection gets disposed(and closed) after query execution.
您将不得不完全重新编写代码。DisplayMember和ValueMember指向 columnNames!此外,您应该真正使用using block- 以便在查询执行后处理(并关闭)连接。
Instead of using a dataReaderto access the values I choosed a dataTableand bound it as dataSource onto the comboBox.
我没有使用dataReader来访问值,而是选择了一个dataTable并将其作为 dataSource 绑定到组合框上。
using (SqlConnection conn = new SqlConnection(@"Data Source=SHARKAWY;Initial Catalog=Booking;Persist Security Info=True;User ID=sa;Password=123456"))
{
try
{
string query = "select FleetName, FleetID from fleets";
SqlDataAdapter da = new SqlDataAdapter(query, conn);
conn.Open();
DataSet ds = new DataSet();
da.Fill(ds, "Fleet");
cmbTripName.DisplayMember = "FleetName";
cmbTripName.ValueMember = "FleetID";
cmbTripName.DataSource = ds.Tables["Fleet"];
}
catch (Exception ex)
{
// write exception info to log or anything else
MessageBox.Show("Error occured!");
}
}
Using a dataTablemay be a little bit slowerthan a dataReaderbut I do not have to create my own class. If you really have to/want tomake use of a DataReaderyou may choose @Nattrass approach. In any case you should write a using block!
使用dataTable可能比dataReader慢一点,但我不必创建自己的类。如果您真的必须/想要使用DataReader,您可以选择@Nattrass 方法。在任何情况下,您都应该编写一个using 块!
EDIT
编辑
If you want to get the current Value of the combobox try this
如果你想获得组合框的当前值,试试这个
private void cmbTripName_SelectedIndexChanged(object sender, EventArgs e)
{
if (cmbTripName.SelectedItem != null)
{
DataRowView drv = cmbTripName.SelectedItem as DataRowView;
Debug.WriteLine("Item: " + drv.Row["FleetName"].ToString());
Debug.WriteLine("Value: " + drv.Row["FleetID"].ToString());
Debug.WriteLine("Value: " + cmbTripName.SelectedValue.ToString());
}
}
回答by Prasanna
Out side the loop, set following.
在循环之外,设置以下。
cmbTripName.ValueMember = "FleetID"
cmbTripName.DisplayMember = "FleetName"
回答by Nattrass
To use the Comboboxin the way you intend, you could pass in an object to the cmbTripName.Items.Addmethod.
要Combobox以您想要的方式使用,您可以将一个对象传递给该cmbTripName.Items.Add方法。
That object should have FleetIDand FleetNameproperties:
该对象应该具有FleetID和FleetName属性:
while (drd.Read())
{
cmbTripName.Items.Add(new Fleet(drd["FleetID"].ToString(), drd["FleetName"].ToString()));
}
cmbTripName.ValueMember = "FleetId";
cmbTripName.DisplayMember = "FleetName";
The FleetClass:
该Fleet类别:
class Fleet
{
public Fleet(string fleetId, string fleetName)
{
FleetId = fleetId;
FleetName = fleetName
}
public string FleetId {get;set;}
public string FleetName {get;set;}
}
Or, You could probably do away with the need for a Fleetclass completely by using an anonymous type...
或者,您可能可以Fleet通过使用匿名类型来完全消除对类的需求......
while (drd.Read())
{
cmbTripName.Items.Add(new {FleetId = drd["FleetID"].ToString(), FleetName = drd["FleetName"].ToString()});
}
cmbTripName.ValueMember = "FleetId";
cmbTripName.DisplayMember = "FleetName";
回答by Md.Rajibuzzaman
private void StudentForm_Load(object sender, EventArgs e)
{
string q = @"SELECT [BatchID] FROM [Batch]"; //BatchID column name of Batch table
SqlDataReader reader = DB.Query(q);
while (reader.Read())
{
cbsb.Items.Add(reader["BatchID"].ToString()); //cbsb is the combobox name
}
}
回答by user4481744
SqlConnection conn = new SqlConnection(@"Data Source=TOM-PC\sqlexpress;Initial Catalog=Northwind;User ID=sa;Password=xyz") ;
conn.Open();
SqlCommand sc = new SqlCommand("select customerid,contactname from customers", conn);
SqlDataReader reader;
reader = sc.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("customerid", typeof(string));
dt.Columns.Add("contactname", typeof(string));
dt.Load(reader);
comboBox1.ValueMember = "customerid";
comboBox1.DisplayMember = "contactname";
comboBox1.DataSource = dt;
conn.Close();
回答by Inaldi Gomez
string query = "SELECT column_name FROM table_name"; //query the database
SqlCommand queryStatus = new SqlCommand(query, myConnection);
sqlDataReader reader = query.ExecuteReader();
while (reader.Read()) //loop reader and fill the combobox
{
ComboBox1.Items.Add(reader["column_name"].ToString());
}
回答by shakur oussama
void Fillcombobox()
{
con.Open();
cmd = new SqlCommand("select ID From Employees",con);
Sdr = cmd.ExecuteReader();
while (Sdr.Read())
{
for (int i = 0; i < Sdr.FieldCount; i++)
{
comboID.Items.Add( Sdr.GetString(i));
}
}
Sdr.Close();
con.Close();
}

