首页 > 代码库 > DataGridView中内置控件常用事件使用心得
DataGridView中内置控件常用事件使用心得
checkbox,button,imagebutton使用dataGridView1_CellContentClick
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) { tb.Text+=string.Format("\r\n{0},Row:{1},Column:{2}","单元格内容单击!",e.RowIndex,e.ColumnIndex); }
combobox使用EditingControlShowing+DropDownClosed,此二事件结合使用可以做到内置combobox一下拉选择了就触发事件
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) { tb.Text += string.Format("\r\n{0},控件名:{1}", "单元格控件编辑!", e.Control.GetType()); if (e.Control.GetType().Equals(typeof(DataGridViewComboBoxEditingControl))) { DataGridViewComboBoxEditingControl editingControl = e.Control as DataGridViewComboBoxEditingControl; try { editingControl.DropDownClosed -= new EventHandler(editingControl_DropDownClosed); } catch { } editingControl.DropDownClosed += new EventHandler(editingControl_DropDownClosed); } else if (e.Control.GetType().Equals(typeof(DataGridViewTextBoxEditingControl))) { DataGridViewTextBoxEditingControl editingControl = e.Control as DataGridViewTextBoxEditingControl; try { } catch { } } } private void editingControl_DropDownClosed(object sender, EventArgs e) { DataGridViewComboBoxEditingControl ctl = sender as DataGridViewComboBoxEditingControl; int r = dataGridView1.CurrentCell.RowIndex; int c = dataGridView1.CurrentCell.ColumnIndex; tb.Text += string.Format("\r\n{0},控件名:{1}", "单元格下拉框下拉!", ctl.GetType()); dataGridView1.CellValueChanged -= dataGridView1_CellValueChanged; }
textbox一般只需要验证事件可使用dgvJointList_CellValidating
private void dgvJointList_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) { int r = dgvJointList.CurrentCell.RowIndex; int c = dgvJointList.CurrentCell.ColumnIndex; if (dgvJointList.Columns["diameter"].Index == c || dgvJointList.Columns["thickness"].Index == c || dgvJointList.Columns["weldLength"].Index == c) { string txt = dgvJointList.CurrentCell.EditedFormattedValue.ToString(); string errorMsg; if (!ValidNumericFF(txt, out errorMsg)) { e.Cancel = true; this.errorProvider1.SetError(dgvJointList, errorMsg); } else { this.errorProvider1.SetError(dgvJointList, ""); } } }
单元格内容改变!,Row:-1,Column:0
单元格内容改变!,Row:-1,Column:1
单元格内容改变!,Row:-1,Column:2
单元格内容改变!,Row:-1,Column:3
单元格内容改变!,Row:-1,Column:4
单元格内容改变!,Row:-1,Column:5
单元格内容选择改变!,Row:0,Column:0
单元格控件编辑!,控件名:System.Windows.Forms.DataGridViewTextBoxEditingControl
点击checkboxcell
单元格验证!,Row:0,Column:0
单元格内容选择改变!,Row:0,Column:4
单元格单击!,Row:0,Column:4
单元格内容单击!,Row:0,Column:4
点击comboboxcell
单元格验证!,Row:0,Column:4
单元格内容改变!,Row:0,Column:4
单元格控件编辑!,控件名:System.Windows.Forms.DataGridViewComboBoxEditingControl
单元格内容选择改变!,Row:0,Column:3
单元格单击!,Row:0,Column:3
点击textboxcell
单元格验证!,Row:0,Column:3
单元格控件编辑!,控件名:System.Windows.Forms.DataGridViewTextBoxEditingControl
单元格内容选择改变!,Row:0,Column:0
单元格单击!,Row:0,Column:0
单元格离开!,Row:0,Column:0