我有一个包含三列的gridview(Order):
我想将Price
与Quantity
相乘,并在dataGridview的Total
列中显示结果。
请记住:我的dataGridview不与任何表绑定。
我正在尝试使用此代码来实现我的目标,但这不是工作意味着价值不会被退回:
private void totalcal()
{
// is the foreach condition true? Remember my gridview isn't bound to any tbl
foreach (DataGridViewRow row in gvSale.Rows)
{
int a = Convert.ToInt32(row.Cells[3].Value) * Convert.ToInt32(row.Cells[4].Value); // value is null why??
row.Cells[5].Value = a;
}
}
这是我按下按钮时调用的方法。 (这不是我上面代码中定义的工作原因)
而且我想知道哪个是适合此计算的Datagridview事件?我不想按钮点击计算总数
答案 0 :(得分:1)
试
int.Parse(row.Cells[3].Value.toString()) * int.Parse(row.Cells[4].Value.toString())
insted of
Convert.ToInt32(row.Cells[3].Value) * Convert.ToInt32(row.Cells[4].Value)
而且你知道你可以随时调用这个方法,如果你不希望它点击按钮。在gvSale的行填充操作完成后调用它。
修改强>
我想您希望在用户输入价格或 Quanitity 时进行计算。为此,您需要为datagridview编写EditingControlShowing
方法。这是一段代码。我实际测试了它并使其正常工作。
在InitializeComponent();
行
gvSale.EditingControlShowing += new System.Windows.Forms.DataGridViewEditingControlShowingEventHandler(this.gvSale_EditingControlShowing);
然后添加此方法:
TextBox tb = new TextBox(); // this is just a textbox to use in editing control
int Price_Index = 3; // set this to your Price Column Index
int Quantity_Index = 4; // set this to your Quantity Column Index
int Total_Index = 5; // set this to your Total Column Index
private void gvSale_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (gvSale.CurrentCell.ColumnIndex == Price_Index || gvSale.CurrentCell.ColumnIndex == Quantity_Index)
{
tb = e.Control as TextBox;
tb.KeyUp += new KeyEventHandler(Calculate_Total);
}
}
private void Calculate_Total(object sender, KeyEventArgs e)
{
int Price_Value = 0;
int Quantity_Value = 0;
int.TryParse(gvSale.CurrentCell.ColumnIndex != Price_Index ? gvSale.CurrentRow.Cells[Price_Index].Value.ToString() : tb.Text, out Price_Value);
int.TryParse(gvSale.CurrentCell.ColumnIndex != Quantity_Index ? gvSale.CurrentRow.Cells[Quantity_Index].Value.ToString() : tb.Text, out Quantity_Value);
gvSale.CurrentRow.Cells[Total_Index].Value = Price_Value * Quantity_Value;
}