I wrote this formula here but for some reason it sums ALL the values in the amt column instead of the one that has the itemcolumn string. Any ideas?
foreach (DataGridViewRow row in itemGrid.Rows)
{
if (itemGrid.Rows[e.RowIndex].Cells["itemColumn"].Value.ToString() == itemcolumn)
total += Convert.ToDecimal(row.Cells["Amt"].Value.ToString());
}
Here’s the full code so you can see what’s going on here.
private void itemGrid_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
//
// [This string compares amt and amtvalue on Cell edit]
//
if (itemGrid.CurrentCell.ColumnIndex == 5 && isCalled)
{
// Prevents loop.
isCalled = false;
decimal total = 0;
string itemcolumn = String.Empty;
{
foreach (DataGridViewRow row in itemGrid.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
if (cell.Selected)
{
itemcolumn = Convert.ToString(row.Cells["itemColumn"].Value);
string strName = vendorBox.Text;
string Select = "select sum(case allocated when 'Received' then amt when 'Shipped' then -amt end) as amt from lineitem WHERE item='" + itemcolumn + "';";
MySql.Data.MySqlClient.MySqlConnection conDatabase = new
MySqlConnection(ConnectionString.connString);
MySql.Data.MySqlClient.MySqlCommand cmdDatabase = new
MySql.Data.MySqlClient.MySqlCommand(Select, conDatabase);
try
{
conDatabase.Open();
MySql.Data.MySqlClient.MySqlDataReader rdrRepairOrder;
rdrRepairOrder = cmdDatabase.ExecuteReader();
while (rdrRepairOrder.Read())
{
string rowz5 = string.Format("{0}", rdrRepairOrder.GetString(0));
string wut5 = rowz5.ToString();
itemamt = Convert.ToInt32(wut5);
}
rdrRepairOrder.Close();
conDatabase.Close();
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
MessageBox.Show("Error " + ex.Number + " has occurred: " + ex.Message,
"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
}
// Converts amt column.
// amt = The cell amount.
// itemamt = What's on the SQL table.
foreach (DataGridViewRow row in itemGrid.Rows)
{
if (itemGrid.Rows[e.RowIndex].Cells["itemColumn"].Value.ToString() == itemcolumn) total += Convert.ToDecimal(row.Cells["Amt"].Value.ToString());
}
MessageBox.Show("Total is: " + total.ToString());
int amt;
string amtz = itemGrid.Rows[e.RowIndex].Cells["Amt"].Value.ToString();
amt = Convert.ToInt32(amtz);
int value;
value = itemamt - amt;
if (value < 0)
{
MessageBox.Show("Cannot allocate more than what it is in inventory. You have " + itemamt.ToString() + " in stock.");
itemGrid[5, itemGrid.CurrentCell.RowIndex].Value = itemamt;
}
}
isCalled = true;
}
Instead of
itemGrid.Rows[e.RowIndex], try usingrowin your condition.