11

我有一个组合框错误

我的代码:

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 ");
}

数据显示在组合框中,但是当您更改选择值成员时,显示成员不会改变。

它现在正在工作,但是当我单击按钮以显示数据时

private void button1_Click(object sender, EventArgs e)
{
    label1.Text = cmbTripName.DisplayMember;
    label2.Text = cmbTripName.ValueMember;
}

显示如下:

车队名称 车队
ID

它不显示值

4

8 回答 8

22

您将不得不完全重写您的代码。DisplayMemberValueMember指向 columnNames!此外,您应该真正使用- 以便在查询执行后释放(并关闭using block)连接。

我没有使用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!");
    }               
}

使用dataTable可能比dataReader一点,但我不必创建自己的类。如果您真的必须/想要使用DataReader,您可以选择@Nattrass 方法。无论如何,您应该编写一个using 块

编辑

如果你想获得组合框的当前值试试这个

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());
    }
}
于 2012-09-19T12:51:35.820 回答
7

要以Combobox您想要的方式使用,您可以将一个对象传递给该cmbTripName.Items.Add方法。

该对象应具有FleetIDFleetName属性:

while (drd.Read())
{
    cmbTripName.Items.Add(new Fleet(drd["FleetID"].ToString(), drd["FleetName"].ToString()));
}
cmbTripName.ValueMember = "FleetId";
cmbTripName.DisplayMember = "FleetName";

Fleet班级:

class Fleet
{
     public Fleet(string fleetId, string fleetName)
     {
           FleetId = fleetId;
           FleetName = fleetName
     }
     public string FleetId {get;set;}
     public string FleetName {get;set;}
}

或者,您可能可以Fleet通过使用匿名类型完全消除对类的需求......

while (drd.Read())
{
    cmbTripName.Items.Add(new {FleetId = drd["FleetID"].ToString(), FleetName = drd["FleetName"].ToString()});
}
cmbTripName.ValueMember = "FleetId";
cmbTripName.DisplayMember = "FleetName";
于 2012-09-19T12:39:14.787 回答
3
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();

}
于 2018-05-05T18:33:24.253 回答
1

在循环之外,设置以下。

cmbTripName.ValueMember = "FleetID"
cmbTripName.DisplayMember = "FleetName"
于 2012-09-19T12:31:18.333 回答
0
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
         }
  }
于 2014-04-20T09:39:00.753 回答
0
            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();
于 2015-01-22T08:56:26.743 回答
0
string query = "SELECT column_name FROM table_name";      //query the database
SqlCommand queryStatus = new SqlCommand(query, myConnection);
sqlDataReader reader = queryStatus.ExecuteReader();                               
            
while (reader.Read())   //loop reader and fill the combobox
{
ComboBox1.Items.Add(reader["column_name"].ToString());
}
于 2017-11-22T16:07:30.943 回答
0

试试这个:

  1.  

    using MySql.Data.MySqlClient;
    
  2. 写:

    MySqlConnection con = new MySqlConnection("datasource=172.16.2.104;port=3306;server=localhost;database=DB_Name;uid=root;password=DB_Password;sslmode=none;charset=utf8;");
    MySqlCommand cmd = new MySqlCommand();
    
    var query2 = "SELECT `salary` FROM `employees_db` ";
    using (var command2 = new MySqlCommand(query2, con))
    {
        using (var reader2 = command2.ExecuteReader())
        {
            while (reader2.Read())
            {
                combox.Text  = reader2.GetString("salary");
            }
        }
    }
    
于 2021-10-09T21:36:43.983 回答