//首先要建立EditingControl对象
private DataGridViewComboBoxEditingControl AAADGVComboBox = null;
private CalendarEditingControl AAADGVCalendar = null;
//添加Datagridview事件EditingControlShowing
private void BBBDGV_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (e.Control is DataGridViewComboBoxEditingControl)
{
if (BBBDGV.CurrentCell.OwningColumn.Name == "添加列的名字")
{
//取得被表示的控件
this.AAADGVComboBox = (DataGridViewComboBoxEditingControl)e.Control;
// SelectedIndexChanged事件处理器追加
this.AAADGVComboBox.SelectedIndexChanged += new EventHandler(AAADGVComboBox_SelectedIndexChanged);
}
}
if (e.Control is CalendarEditingControl)
{
if (BBBDGV.CurrentCell.OwningColumn.Name == "列的名字")
{
this.AAADGVCalendar = (CalendarEditingControl)e.Control;
this.AAADGVCalendar.ValueChanged += new EventHandler(AAADGVCalendar_ValueChanged);
}
}
}
//CellEndEdit事件处理器
private void BBBDGV_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
//SelectedIndexChanged事件处理器删除
if (this.AAADGVComboBox != null)
{
this.AAADGVComboBox.SelectedIndexChanged -= new EventHandler(AAADGVComboBox_SelectedIndexChanged);
this.AAADGVComboBox = null;
}
if (this.AAADGVCalendar != null)
{
this.AAADGVCalendar.ValueChanged -= new EventHandler(AAADGVCalendar_ValueChanged);
this.AAADGVCalendar = null;
}
}
//在DataGridView中表示的ComboBox的SelectedIndexChanged事件处理器
private void AAADGVComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
//表示被选择的Item
DataGridViewComboBoxEditingControl cb = (DataGridViewComboBoxEditingControl)sender;
if (cb.SelectedItem.ToString() )
{
}
else if (cb.SelectedItem.ToString() )
{
}
}
private void AAADGVCalendar_ValueChanged(object sendar, EventArgs e)
{
try
{
if (BBBDGV.CurrentCell.OwningColumn.Name == "列名字")
{
CalendarEditingControl ca = (CalendarEditingControl)sendar;
if (ca.Value.ToString() )
{
}
}
}
catch { }
}
其中AAA,BBB是datagridview的名字,其中要注册CellEndEdit和EditingControlShowing事件,侦听的具体操作在SelectedIndexChanged和ValueChanged里面实现。
要是将Button添加到datagridview里面的话:可以添加CellContentClick事件,代码如下:
private void DGV_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
int CIndex = e.ColumnIndex;
try
{
if (CIndex == 9)
{
if (this.DGV.CurrentRow.Cells[1].Value != null)
{
}
this.DGV.Rows.RemoveAt(this.DGV.CurrentRow.Index);
}
else if (CIndex == 10)
{
this.DGV.CurrentRow.Cells[4].FormattedValue.ToString();
}
}
catch { }
}