【求大神指点】怎么获得C#的combobox中的内容
【求大神指点】如何获得C#的combobox中的内容
绑定combobox的代码是这样的
private void frm2_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=ideapad\\SQLEXPRESS2008;Initial Catalog=点名系统;User ID=sa; Password=jasmine19940101;");
conn.Open();
String cmdstr = "select 所教班级名称 from 教师情况表 where 教师账号='" + paf.textBox1.Text + "'";
SqlDataAdapter da = new SqlDataAdapter(cmdstr, conn);
DataSet ds = new DataSet();
da.Fill(ds,"教师情况表");
//comboBox1.DataSource = ds.Tables[0].DefaultView;
for (int i = 0; i < ds.Tables[0].Rows.Count;i++)
{
comboBox1.Items.Add(ds.Tables[0].Rows[i][0].ToString().Trim());
}
comboBox1.DisplayMember = "所教班级名称";//下拉列表中显示的是你数据库中“所教班级名称”的值
comboBox1.ValueMember = "id";
conn.Close();
}
运行后绑定是成功的,然后我想获得combobox中的内容,我试了combobox.Text, comboBox1.GetItemText(comboBox1.Items[comboBox1.SelectedIndex]).ToString();
combobox.SelectedItem.ToString();都不行,求大神帮忙啊
------解决方案--------------------
要么
要么
至于
最后可以加一行
要取ComboBox选择的文本,下面两个都行:
(comboBox1.Items[comboBox1.SelectedIndex]).ToString();
combobox.SelectedItem.ToString();
------解决方案--------------------
试试selectValue
绑定combobox的代码是这样的
private void frm2_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=ideapad\\SQLEXPRESS2008;Initial Catalog=点名系统;User ID=sa; Password=jasmine19940101;");
conn.Open();
String cmdstr = "select 所教班级名称 from 教师情况表 where 教师账号='" + paf.textBox1.Text + "'";
SqlDataAdapter da = new SqlDataAdapter(cmdstr, conn);
DataSet ds = new DataSet();
da.Fill(ds,"教师情况表");
//comboBox1.DataSource = ds.Tables[0].DefaultView;
for (int i = 0; i < ds.Tables[0].Rows.Count;i++)
{
comboBox1.Items.Add(ds.Tables[0].Rows[i][0].ToString().Trim());
}
comboBox1.DisplayMember = "所教班级名称";//下拉列表中显示的是你数据库中“所教班级名称”的值
comboBox1.ValueMember = "id";
conn.Close();
}
运行后绑定是成功的,然后我想获得combobox中的内容,我试了combobox.Text, comboBox1.GetItemText(comboBox1.Items[comboBox1.SelectedIndex]).ToString();
combobox.SelectedItem.ToString();都不行,求大神帮忙啊
------解决方案--------------------
要么
comboBox1.DataSource = ds.Tables[0].DefaultView;
comboBox1.DisplayMember = "所教班级名称";//下拉列表中显示的是你数据库中“所教班级名称”的值
要么
for (int i = 0; i < ds.Tables[0].Rows.Count;i++)
{
comboBox1.Items.Add(ds.Tables[0].Rows[i][0].ToString().Trim());
}
至于
comboBox1.ValueMember = "id";select语句中有这个字段吗?
最后可以加一行
comboBox1.SelectedIndex=0;
要取ComboBox选择的文本,下面两个都行:
(comboBox1.Items[comboBox1.SelectedIndex]).ToString();
combobox.SelectedItem.ToString();
------解决方案--------------------
试试selectValue