C# 我应该为此使用什么Datagrid事件?

C# 我应该为此使用什么Datagrid事件?,c#,datagridview,C#,Datagridview,所以我有一个datagridview,我从数据源调用它 下面是代码: 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

所以我有一个datagridview,我从数据源调用它

下面是代码:

        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";
我想要的是,每当我从quantity行更改一个单元格时,Amount单元格就会从该列对应的位置更改


我是活动方面的新手,所以在这方面我真的需要帮助。提前谢谢

使用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;
}
当然,改变价值观更为恰当。谁在乎如果值没有改变,编辑会话是否刚刚结束,如果值在没有直接编辑单元格的情况下改变呢?你仍然在使用CellEndEdit,因此在这方面仍然是错误的。在这方面是错误的:我猜你指的是用户输入的数据与以其他方式输入的数据?根据我的理解,OP打算输入数据+他说它有效=不要认为这在这方面是错误的,而是这方面本身可能是错误的,你想检查一下吗?询问OP@jmcillhinney