我应该为此使用什么Datagrid事件
本文关键字:什么 Datagrid 事件 我应该 | 更新日期: 2023-09-27 18:30:08
所以我有一个从数据源调用的数据网格视图。
http://i58.tinypic.com/dwvxxv.png
这是它的代码:
string strsql = "select a.Denomination, a.Value, b.Quantity, b.Amount from [Masterfile].[Denomination] a "+
"left join [GEARS-POS].[POS].[CashCount] b "+
"on A.Sequence = B.Sequence order by a.sequence";
dataGridViewEx1.AutoGenerateColumns = false;
DataTable dtgt = Library.Lib.GetData(strsql, Common.Common.ConnectionString());
dataGridViewEx1.DataSource = dtgt.DefaultView;
dataGridViewEx1.Columns[0].DataPropertyName = "Denomination";
dataGridViewEx1.Columns[1].DataPropertyName = "Value";
dataGridViewEx1.Columns[2].DataPropertyName = "Quantity";
我想要的是,每当我更改数量行中的一个单元格时,数量单元格就会从该列对应的位置更改。
我是活动的初学者,所以当涉及到这类事情时,我真的需要帮助。提前感谢!
使用CellEndEdit事件:
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
if(e.ColumnIndex == 2) // quantity column
{
int col = e.ColumnIndex;
int row = e.RowIndex;
int quantity = Convert.ToInt32(dataGridView1.Rows[row].Cells[col].Value); // entered quantity
double value = Convert.ToDouble(dataGridView1.Rows[row].Cells[col -1].Value); // value of corresponding row
dataGridView1.Rows[row].Cells[col+1].Value = (quantity*value).ToString();
}
}
进一步关注
上面的代码很简单,假设软件没有被滥用,下一个代码更可靠:
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
if(dataGridView1[e.ColumnIndex, e.RowIndex] == null) return;
// rest of code as in the upper one
}
private void dataGridView1_CellValidating(object sender, DataGridViewCellEventArgs e)
{
int col = e.ColumnIndex;
int row = e.RowIndex;
string data = e.FormattedValue.ToString();
if(!checkData(data))
{
e.Cancel = false;
return;
}
// for example I want to limit the quantities to be between [0, 100]
if(col == 2)
{
int iData = Convert.ToInt32(data);
if(iData < 0 || iDat > 100)
{
e.Cancel = true;
return;
}
}
}
private bool chackData(string d)
{
if (d.Length <= 0 || d.Length >= 10) return false;
foreach (char c in d)
{
if('0' >= c || c >= '9')
{
return false;
}
}
return true;
}