Basic concept of what I have is that there are two data grids. One is populated with a material type and quantity I want as a base line. This table has unique material types. The second table may have multiple entries of the same type of material with differing quantities.
Table 1 Table 2
F01 20/40 150 F01 20/40 40
F01 30/50 150 F01 20/40 50
F01 50/90 150 F01 20/40 100
F01 70/110 150 F01 30/50 60
Since each material type in table 1 is unique, I’m taking each row (cell index [0]) and cycling through each row in the second column and adding up the quantity for each matching material type.
I’m stuck as I have been for a while why my loop keeps breaking after successfully tallying up the first material type. Here is my code:
private void combineButton_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
DataRow dtrow;
dt.Columns.Add("Material");
dt.Columns.Add("OnHand_Qty");
int x = 0;
foreach (DataGridViewRow row in baseStockGrid.Rows)
{
string material = row.Cells[0].Value.ToString();
foreach (DataGridViewRow crow in currentOnHandGrid.Rows)
{
string check = crow.Cells[0].Value.ToString();
if (check == material)
{
var y = crow.Cells[1].Value.ToString();
x = int.Parse(y) + x;
}
if (check != material)
{
continue;
}
}
dtrow = dt.NewRow();
dtrow[0] = material.ToString();
dtrow[1] = x;
dt.Rows.Add(dtrow);
x = 0;
currentOnHandGrid.DataSource = dt;
}
}
I basically refresh the data grid to show the combined material counts and it displays like this:
Table1 Table2
F01 20/40 150 F01 20/40 190
F01 30/50 150 F01 30/50 0 //<---- Should show 60 according to example above.
It appears that you are overwriting your own data source. At the beginning of the code, you declare a
DataTable dtas a new table and set it up to store your refreshed data. After you pull the appropriate data for your first material type fromcurrentOnHandGridand store it in tabledt, you overwritecurrentOnHandGridwithdt. Now, you have a table that has your first material filled in with no other materials included. When you go to the next material in the outer loop, the inner loop tries to look for that material in the table, but it is not there as you have overwritten the original table with a fresh one.Simply move the part where you overwrite the old table with the new one to the outside of the loop and it should write properly.
EDIT: Also, as the other answerer noted, you do not need the
Continuestatement. In addition, having an if-statement to check a condition and another if-statement to check the complement is bad form. The second if-statement should actually be an else-statement, as it is a boolean statement. “If it’s this, then do this, or else do that.” You don’t even need the else-statement with acontinueinside it either. If the first if-statement fails, the program should continue anyway.