DataGridView meets Linq


DataGridView is a tool for displaying, modifying, entering values in Visual Studio.Net. Usually we are using loops or readers to traverse through rows or columns.

Linq query make it possible to do these take with few lines, instead of complicated loops.

We have a data entry GridView which accepts purchase details such as name,qty,price etc. Lets get the sum of quantity supplied in the grid using Linq query

We do the following

  1. Create List of values
  2. Call the Sum() for total function for the column we specified

The Linq Querry

var qt = from DataGridViewRow row in dataGridView1.Rows where row.Cells[COL_QTY.Index].FormattedValue.ToString().Trim().Length!=0 && row.Cells[COL_QTY.Index].FormattedValue != null select ( row.Cells[COL_QTY.Index].FormattedValue.ToString().Trim());

We have to make sure the cell is not null or it has any values at all, we place where section, otherwise the System will fire you for an unhandled exception, lol.

Summing up values

txt_tqty.Text = qt.Sum(c => Convert.ToDouble(c)).ToString();

That’s all

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.