请帮助我。
我有以下代码(C#):
decimal quantity = 0, avai = 0, newavai = 0;
decimal totalstock = 0, newtotalstock = 0;
if (decimal.TryParse(G1.Rows[e.RowIndex].Cells["Quantity"].Value.ToString(), out quantity) && decimal.TryParse(G1.Rows[e.RowIndex].Cells["AvailableStock"].Value.ToString(), out avai))
{
newavai = avai + quantity;
G1.Rows[e.RowIndex].Cells["AvailableStock"].Value = newavai.ToString();
}
if (decimal.TryParse(G1.Rows[e.RowIndex].Cells["TotalStock"].Value.ToString(), out totalstock) && decimal.TryParse(G1.Rows[e.RowIndex].Cells["Quantity"].Value.ToString(), out quantity))
{
newtotalstock = totalstock + quantity;
G1.Rows[e.RowIndex].Cells["TotalStock"].Value = newtotalstock.ToString();
}
这段代码只是关于在Datagridview中计算单元格,它工作得很好。事实是,我希望在加载表单时自动执行。现在我暂时把它放在Cell Click事件中因为我想测试代码并且不知道在哪里放代码,请帮帮我。
谢谢。
答案 0 :(得分:2)
你可以用两个选项来做到这一点:
首先创建DataGridViewCellEventArgs的新实例,然后指定列索引和行索引,您可以参考此链接获取更多信息: DataGridViewCellEventArgs
然后我用 ee 替换所有 e ,因为在Form Load中,变量e已被使用。就是这样。
private void Form1_Load(object sender, EventArgs e)
{
DataGridViewCellEventArgs ee = new DataGridViewCellEventArgs(1, 1);
decimal quantity = 0, avai = 0, newavai = 0;
decimal totalstock = 0, newtotalstock = 0;
if (decimal.TryParse(G1.Rows[ee.RowIndex].Cells["Quantity"].Value.ToString(), out quantity) && decimal.TryParse(G1.Rows[ee.RowIndex].Cells["AvailableStock"].Value.ToString(), out avai))
{
newavai = avai + quantity;
G1.Rows[ee.RowIndex].Cells["AvailableStock"].Value = newavai.ToString();
}
if (decimal.TryParse(G1.Rows[ee.RowIndex].Cells["TotalStock"].Value.ToString(), out totalstock) && decimal.TryParse(G1.Rows[ee.RowIndex].Cells["Quantity"].Value.ToString(), out quantity))
{
newtotalstock = totalstock + quantity;
G1.Rows[ee.RowIndex].Cells["TotalStock"].Value = newtotalstock.ToString();
}
}
另一个选项是你可以用这个来调用click事件处理程序:
private void Form1_Load(object sender, EventArgs e)
{
DataGridViewCellEventArgs ee = new DataGridViewCellEventArgs(1, 1);
G1_CellClick(sender, ee);
}
private void G1_CellClick(object sender, DataGridViewCellEventArgs e)
{
decimal quantity = 0, avai = 0, newavai = 0;
decimal totalstock = 0, newtotalstock = 0;
if (decimal.TryParse(G1.Rows[e.RowIndex].Cells["Quantity"].Value.ToString(), out quantity) && decimal.TryParse(G1.Rows[e.RowIndex].Cells["AvailableStock"].Value.ToString(), out avai))
{
newavai = avai + quantity;
G1.Rows[e.RowIndex].Cells["AvailableStock"].Value = newavai.ToString();
}
if (decimal.TryParse(G1.Rows[e.RowIndex].Cells["TotalStock"].Value.ToString(), out totalstock) && decimal.TryParse(G1.Rows[e.RowIndex].Cells["Quantity"].Value.ToString(), out quantity))
{
newtotalstock = totalstock + quantity;
G1.Rows[e.RowIndex].Cells["TotalStock"].Value = newtotalstock.ToString();
}
}