Shovan Saha

Shovan Saha

  • NA
  • 321
  • 92.6k

Please edit this simple code

Sep 17 2017 1:51 PM
My code is nice if there is not null/empty value. For the yellow marked null value my code does not work. Please edit this code that allow null/empty value.
 
private void Form1_Load(object sender, EventArgs e)
{
AddRowsInDatagridView(0,"L", "A", "3", "2");
AddRowsInDatagridView(1,"M", "B", "4", "3");
AddRowsInDatagridView(2,"L", "A", "5", "7");
AddRowsInDatagridView(3,"M", "B", "", "8");
AddRowsInDatagridView(4,"L", "A", "3", "5");
AddRowsInDatagridView(5,"S", "S", "2", "9");
AddRowsInDatagridView(6,"S", "S", "1", "12");
dataGridView2.Visible = false;
}
public void AddRowsInDatagridView(int row,string Type, string Item, string Price, string Qty)
{
dataGridView1.Rows.Add();
dataGridView1.Rows[row].Cells[0].Value = Type;
dataGridView1.Rows[row].Cells[1].Value = Item;
dataGridView1.Rows[row].Cells[2].Value = Price;
dataGridView1.Rows[row].Cells[3].Value = Qty;
}
private void button1_Click(object sender, EventArgs e)
{
dataGridView2.Visible = true;
List<ProductList> _product = new List<ProductList>();
int Count = 1;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.Cells[0].Value != "" && row.Cells[0].Value != null)
{
if (_product.Where(x => x.Type.ToLower() == row.Cells[0].Value.ToString().ToLower()).Any())
{
string TotalQty = (Convert.ToInt32(_product.Where(x => x.Type.ToLower() == row.Cells[0].Value.ToString().ToLower()).Select(x => x.TotalQty).FirstOrDefault()) + Convert.ToInt32(row.Cells[3].Value.ToString())).ToString();
string TotalPrice = (Convert.ToInt32(_product.Where(x => x.Type.ToLower() == row.Cells[0].Value.ToString().ToLower()).Select(x => x.TotalPrice).FirstOrDefault()) + Convert.ToInt32(row.Cells[2].Value.ToString())).ToString();
_product.Where(x => x.Type.ToLower() == row.Cells[0].Value.ToString().ToLower()).ToList().ForEach(x => { x.TotalQty = TotalQty; x.TotalPrice = TotalPrice; });
}
else
{
_product.Add(new ProductList
{
Sno = Count,
Type = row.Cells[0].Value.ToString(),
Item = row.Cells[1].Value.ToString(),
TotalPrice = row.Cells[2].Value.ToString(),
TotalQty = row.Cells[3].Value.ToString()
});
Count++;
}
}
}
dataGridView2.DataSource = _product;
}
 

Answers (3)