简体   繁体   中英

Select combo box item

I have a question. I'm showing data from a database in my combobox. I have chosen 3 columns: StudentID, Surname, Course, that are shown in the drop down menu. Is it possible, when selecting an item, to show only one column in the combobox, for example only StudentID?

Thank you,

Marco

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

When you say select, do you still want to have all three at part of the list but only show the Id? Can you not just add the first item from the reader?

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

edit:

You need to create an object for this like below

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()));

if I understand well, you wanna just show StudentID field, but still would like to select when this id, able to use the other fields in the query made, if that is your goal, you can take several paths, an example for you would be the following:

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

so u could recover some of the informations, but even so, u still need all obejtos consultation, just assign the add object and choose what you want to view in combo with the following line comboBox1.DisplayMember = "field you want to display";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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