繁体   English   中英

在 combobox 中设置从 c# 中的数据表填充的 SelectedValue?

[英]Set SelectedValue in combobox that populated from Data Table in c#?

我的表格中有一个 Combobox。 此 Combobox 填充了数据库中表(教师)中的值。

我需要根据另一个表(学生)中的记录来设置这个 Combobox 的SelectedValue 两个表都在同一个数据库中。

我尝试使用从student表中获取的值设置SelectedValue

cmbfaculty.SelectedValue = table.Rows[0][1].ToString();

但它没有用。

到目前为止,我只能填充 Combobox,

    // --- populate faculty cmb ---
MySqlCommand cmdCmb = new MySqlCommand("SELECT facultyname FROM faculty;", db.getConnection());
db.openConnection();    // open connection

using (var reader = cmdCmb.ExecuteReader())
{
    while (reader.Read())
    {
        cmbfaculty.Items.Add(reader.GetString("facultyname"));
    }
}

但无法设置SelectedValue

string sQuery = "SELECT indexno,faculty FROM student WHERE indexno ='"+selected+"'";
MySqlCommand cmd = new MySqlCommand(sQuery, db.getConnection());
MySqlDataAdapter adapter = new MySqlDataAdapter(cmd);
DataTable table = new DataTable();
adapter.Fill(table);

txtindex.Text = table.Rows[0][0].ToString();
cmbfaculty.SelectedValue = table.Rows[0][1].ToString();

希望能解决问题。


编辑:

能够通过找到与指定字符串ComboBox.FindStringExact Method完全匹配的项目来做到这一点,

 cmbfaculty.SelectedValue = table.Rows[0][1].ToString();

需要替换为

cmbfaculty.SelectedIndex = cmbfaculty.FindStringExact(table.Rows[0][1].ToString());

有没有其他方法来归档这个。

能够通过找到与指定字符串ComboBox.FindStringExact Method完全匹配的项目来做到这一点,

cmbfaculty.SelectedValue = table.Rows[0][1].ToString();

需要替换为

cmbfaculty.SelectedIndex = cmbfaculty.FindStringExact(table.Rows[0][1].ToString()) ;

暂无
暂无

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

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