繁体   English   中英

选择组合框项目

[英]Select combo box item

我有个问题。 我在组合框中显示来自数据库的数据。 我选择了3列:学生ID,姓氏,课程,这些列显示在下拉菜单中。 选择项目时,是否可能只显示组合框中的一列,例如仅显示StudentID?

谢谢,

马可

private void Form2_Load(object sender, EventArgs e)
    {
        connection.Open();

        OleDbCommand command = new OleDbCommand();

        command.Connection = connection;

        command.CommandText = "SELECT StudentID, Surname, Course FROM Students";

        OleDbDataReader reader = command.ExecuteReader();

        while(reader.Read())
        {
            comboBox1.Items.Add(reader[0].ToString() + " " + reader[1].ToString() + " " + reader[2].ToString());
        }

        connection.Close();
    }

当您说选择时,您是否仍想将所有三个都放在列表的一部分,而只显示ID? 您不仅可以添加阅读器中的第一项吗?

private void Form2_Load(object sender, EventArgs e)
{
    connection.Open();

    OleDbCommand command = new OleDbCommand();

    command.Connection = connection;

    command.CommandText = "SELECT StudentID, Surname, Course FROM Students";

    OleDbDataReader reader = command.ExecuteReader();

    while(reader.Read())
    {
        comboBox1.Items.Add(reader[0].ToString());
    }

    connection.Close();
}

编辑:

您需要为此创建一个对象,如下所示

private class Student
{
    public string Name;
    public int Id

    public Student(string name, int id) 
    {
        Name = name; 
        Id = id;
    }

    //override the tostring to change how it is displayed in the combobox
    public override string ToString()
    {
        return Name + " " + Id.ToString();
    }
}   

comboBox1.Items.Add(new Student(reader[1].ToString(), reader[0].ToString()));

如果我理解得很好,您只想显示StudentID字段,但仍想选择此ID的时间,可以使用查询中的其他字段,如果这是您的目标,则可以采用几种路径,例如如下:

comboBox1.Items.Add(drd["0"].ToString());
comboBox1.ValueMember = drd["0"].ToString();
comboBox1.DisplayMember = drd["1"].ToString();

因此您可以恢复一些信息,但是即使如此,您仍然需要进行所有的咨询,只需分配添加对象,然后使用以下行comboBox1.DisplayMember = "field you want to display"; ,选择要在组合中查看的内容comboBox1.DisplayMember = "field you want to display";

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM