日期:2014-05-18 浏览次数:21143 次
// 构建表格实际数据源 DataTable dt = new DataTable(); dt.Columns.Add("c_ID"); dt.Columns.Add("d_ID"); for (int i = 0; i < 10; i += 2) dt.Rows.Add(new object[] { i, i % 4 }); dataGridView1.DataSource = dt; //先构建第一个联动数据列 DataTable dt1 = new DataTable(); dt1.Columns.Add("c_ID"); dt1.Columns.Add("c_name"); for (int i = 0; i < 10; i++) dt1.Rows.Add(new object[] { i, "公司" + i.ToString() }); //建立下拉列 DataGridViewComboBoxColumn cc = new DataGridViewComboBoxColumn(); cc.DataSource = dt1; cc.HeaderText = "公司名称"; cc.DisplayMember = "c_name"; cc.ValueMember = "c_ID"; cc.DataPropertyName = "c_ID"; dataGridView1.Columns.Add ( cc); //构建第二个级联动数据列 DataTable dt2 = new DataTable(); dt2.Columns.Add("d_ID"); dt2.Columns.Add("d_name"); for (int i = 0; i < 4; i++) dt2.Rows.Add(new object[] { i, "部门" + i.ToString() }); //建立下拉列 DataGridViewComboBoxColumn c2 = new DataGridViewComboBoxColumn(); c2.DataSource = dt2; c2.HeaderText = "部门"; c2.DisplayMember = "d_name"; c2.ValueMember = "d_ID"; c2.DataPropertyName = "d_ID"; dataGridView1.Columns.Add( c2); //最后隐藏ID列 dataGridView1.Columns[0].Visible = false; dataGridView1.Columns[1].Visible = false;
------解决方案--------------------
给公司这一列的ComboBox添加事件,我一般是这么做的~
dataGridView.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler(dataGridView_EditingControlShowing); private void dataGridView_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) { if (dataGridView.CurrentCell.OwningColumn.Name.Equals("公司") && e.Control is ComboBox) { (e.Control as ComboBox).SelectedValueChanged -= new EventHandler(ComboBox_SelectedValueChanged); (e.Control as ComboBox).SelectedValueChanged += new EventHandler(ComboBox_SelectedValueChanged); } } void ComboBox_SelectedValueChanged(object sender, EventArgs e) { if ((sender as ComboBox).SelectedItem != null) { dataGridView.CurrentRow.Cells["部门"].Value = ((sender as ComboBox).SelectedItem as DataRowView)["部门"]; } }