DataGridView 中的 DataGridViewCheckBoxColumn 的值得改变 需要实现的功能
Posted on 2011-07-17 22:05 itcfj 阅读(1200) 评论(0) 收藏 举报
在CheckBox改变值得时候,执行需要的业务。
summary
我的做法是,将焦点转移出去,触发CellValueChanged事件
summary
public partial class Form1 Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
CreateData();
}
summary
绑定数据
summary
private void CreateData()
{
DataTable dtSource = new DataTable();
dtSource.Columns.Add(isNeed,typeof(bool));
dtSource.Columns.Add(no, typeof(string));
dtSource.Columns.Add(number, typeof(string));
dtSource.Columns.Add(odds, typeof(string));
for (int i = 0; i 14; i++)
{
DataRow dr = dtSource.NewRow();
dr[0] = (i % 2 == 0);
dr[1] = i.ToString().PadLeft(2, '0');
dr[2] = i.ToString() + i.ToString() + i.ToString();
dr[3] = i.ToString() + i.ToString() + i.ToString() + i.ToString();
dtSource.Rows.Add(dr);
}
dgTest.DataSource = dtSource;
}
summary
在单元格的值更改时发生。
summary
param name=senderparam
param name=eparam
remarks注意:此事件在 .NET Framework 2.0 版中是新增的。remarks
private void dgTest_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (dgTest.DataSource == null)
{
return;
}
if (this.dgTest.Columns[this.dgTest.CurrentCell.ColumnIndex].Name == colIsNeed)
{
DataGridViewCheckBoxCell oCell = this.dgTest.CurrentCell as DataGridViewCheckBoxCell;
if ((bool)oCell.Value)
{
dgTest[colNumber,e.RowIndex].Value = e.RowIndex.ToString() + 9999;
}
else
{
dgTest[colNumber, e.RowIndex].Value = ;
}
}
}
summary
在单元格中的内容被单击时发生。
summary
param name=senderparam
param name=eparam
remarks注意:此事件在 .NET Framework 2.0 版中是新增的。 remarks
private void dgTest_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (this.dgTest.Columns[this.dgTest.CurrentCell.ColumnIndex].Name == colIsNeed)
{
SendKeys.SendWait({tab});
SendKeys.SendWait(+{tab});
}
}
}
更好的方法CellMouseUp
private void dgTest_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e)
{
if (dgTest.DataSource == null)
{
return;
}
if (this.dgTest.Columns[this.dgTest.CurrentCell.ColumnIndex].Name == colIsNeed)
{
DataGridViewCheckBoxCell oCell = this.dgTest.CurrentCell as DataGridViewCheckBoxCell;
if ((bool)oCell.FormattedValue)
{
dgTest[colNumber, e.RowIndex].Value = e.RowIndex.ToString() + 9999;
}
else
{
dgTest[colNumber, e.RowIndex].Value = ;
}
dgTest.CommitEdit(DataGridViewDataErrorContexts.Formatting);
}
}
KeyUp
private void dgTest_KeyUp(object sender, KeyEventArgs e)
{
if (this.dgTest.Columns[this.dgTest.CurrentCell.ColumnIndex].Name == colIsNeed)
{
if (e.KeyCode == Keys.Space)
{
dgTest.CommitEdit(DataGridViewDataErrorContexts.CurrentCellChange);
if (!(bool)this.dgTest.CurrentCell.FormattedValue)
{
其他处理①
dgTest[colNumber, this.dgTest.CurrentCell.RowIndex].Value = this.dgTest.CurrentCell.RowIndex.ToString() + 9999;
}
else
{
其他处理②
dgTest[colNumber, this.dgTest.CurrentCell.RowIndex].Value = ;
}
}
}
}