It is usually best to do operations on the underlying data structure, such as a DataTable.
1. Add the following member variable to your class.
private DataTable dtRecord;
2. I had to add init code somewhere
private void Form1_Load(object sender, EventArgs e)
{
dtRecord = new DataTable("Record");
dtRecord.Columns.Add("Id", typeof(System.Int32));
dtRecord.Columns.Add("Name", typeof(System.String));
dtRecord.Columns.Add("Balance", typeof(System.String));
dtRecord.Rows.Add(1, "Sai", "10000Cr");
dtRecord.Rows.Add(2, "Ram", "3000Dr");
dtRecord.Rows.Add(3, "Anu", "5000Cr");
dtRecord.Rows.Add(4, "Swathi", "4000Dr");
bindingSource1.DataSource = dtRecord.DefaultView;
dataGridView1.DataSource = bindingSource1;
CalculateSum();
}
3. You can use for example the event CellEndEdit
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
bindingSource1.EndEdit();
if (e.ColumnIndex == 2)
{
CalculateSum();
}
}
4. The method CalculateSum as the very simplest implementation
private void CalculateSum()
{
double sum = 0.0;
Regex balanceExpression = new Regex(@"(?<value>\d+)(?<type>cr|dr)", RegexOptions.IgnoreCase);
foreach (DataRow dr in dtRecord.Rows)
{
string balance = dr["Balance"].ToString();
Match m = balanceExpression.Match(balance);
if (m.Success)
{
if (m.Groups["type"].Value.ToUpper() == "CR")
sum += double.Parse(m.Groups["value"].Value);
else
sum -= double.Parse(m.Groups["value"].Value);
}
}
textBox1.Text = sum.ToString("N2");
}
</type></value>
Of course there are plenty of other ways to do the same thing, for example using LINQ for calculating the sum.