所以我有一个datagridview,我从数据源调用。
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";
我想要的是每次从数量行更改一个单元格,然后Amount单元格将从列对应的位置更改。
我是这个事件的初学者,所以在谈到这类事情时我真的需要帮助。提前谢谢!
答案 0 :(得分:0)
使用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;
}