好久没写过WinForm程序了,昨天闲来无事就试着写个玩玩。界面中有两个combobox控件,第二个combobox控件中绑定值是根据第一个combobox值而定的。当时自己写的代码是:
1 private void btnGetDBs_Click(object sender, EventArgs e)
2 {
3 string strconnection = "数据库连接字符串" ;
4 conn = new SqlConnection(strconnection);
5 string sql = "Sql语句";
6
7 SqlDataAdapter da = new SqlDataAdapter(sql,conn);
8 DataSet ds = new DataSet();
9 da.Fill(ds, "table");
10
11 cmbDBs.DisplayMember = "Name";
12 cmbDBs.ValueMember = "Name";
13 cmbDBs.DataSource = ds.Tables[0].DefaultView;
14
15 }
16
17 private void cmbDBs_SelectedValueChanged(object sender, EventArgs e)
18 {
19 string strconnection = "数据库连接字符串";
20 conn = new SqlConnection(strconnection);
21 string sql = string.Format("Sql语句", cmbDBs.SelectedValue.ToString());
22
23 SqlDataAdapter da = new SqlDataAdapter(sql, conn);
24 DataSet ds = new DataSet();
25 da.Fill(ds, "table");
26 cmbTables.DataSource = ds.Tables[0].DefaultView;
27 cmbTables.DisplayMember = "Name";
28 cmbTables.ValueMember = "Name";
29 }
可是在获得cmbDBs.SelectedValue.ToString()值时说“未将对象引用到实例”或者就是取到“System.data.dataRowView”的值。后来在网上了下,只要将绑定第二个combobox的代码写在private void cmbDBs_SelectedIndexChanged(object sender, EventArgs e)事件中就能正确取出值了。即:
1 private void btnGetDBs_Click(object sender, EventArgs e)
2 {
3 string strconnection = "server=" + txtServiceIP.Text.Trim() + ";uid=" + txtUid.Text.Trim() + ";pwd=" + txtPwd.Text.Trim();
4 conn = new SqlConnection(strconnection);
5 string sql = "Select [Name] FROM Master..SysDatabases where DBId>4 ORDER BY Name";
6
7 SqlDataAdapter da = new SqlDataAdapter(sql,conn);
8 DataSet ds = new DataSet();
9 da.Fill(ds, "tb");
10
11 cmbDBs.DisplayMember = "Name";
12 cmbDBs.ValueMember = "Name";
13 cmbDBs.DataSource = ds.Tables[0].DefaultView;
14 }
15
16 private void cmbDBs_SelectedIndexChanged(object sender, EventArgs e)
17 {
18 string strconnection = "server=" + txtServiceIP.Text.Trim() + ";uid=" + txtUid.Text.Trim() + ";pwd=" + txtPwd.Text.Trim();
19 conn = new SqlConnection(strconnection);
20 string sql = string.Format("Select Name FROM {0}.dbo.SysObjects Where XType='U' ORDER BY Name ", cmbDBs.SelectedValue.ToString());
21
22 SqlDataAdapter da = new SqlDataAdapter(sql, conn);
23 DataSet ds = new DataSet();
24 da.Fill(ds, "tb");
25 cmbTables.DisplayMember = "Name";
26 cmbTables.ValueMember = "Name";
27 cmbTables.DataSource = ds.Tables[0].DefaultView;
28 }
另外在绑定时最好将这样写(个人觉得)
1 cmbTables.DisplayMember = "Name";
2 cmbTables.ValueMember = "Name";
3 cmbTables.DataSource = ds.Tables[0].DefaultView;
在默认的情况下combobox控件是可以自己手动输入的,如果想让它只读则只需改变DropDownList属性为DropDownList便可以了。