Cuando usamos el control DataGridView muchas veces necesitamos realizar operaciones sobre las filas o columnas del control, ahora veremos la manera de como realizar la suma de una columna del datagriedview usando linq.
El ejemplo esta desarrollado en visual estudio 2010 con los lenguajes c# y vb.net.
El ejemplo es sencillo y usare un datatable que lleno manualmente para el origen de datos, en un ejemplo real este datatable se llenaría con datos de una base de datos.
El diseño de la aplicacion es el siguiente.
Ahora veamos la manera como llenamos el datatable con los datos que usaremos
private DataTable Datos()
{
DataTable dt = new DataTable();
dt.Columns.Add("Id");
dt.Columns.Add("Producto");
dt.Columns.Add("Total");
DataRow row = dt.NewRow();
row["Id"] = 1;
row["Producto"] = "Arroz";
row["Total"] = 50.00;
dt.Rows.Add(row);
row = dt.NewRow();
row["Id"] = 2;
row["Producto"] = "Pollo";
row["Total"] = 75.25;
dt.Rows.Add(row);
row = dt.NewRow();
row["Id"] = 3;
row["Producto"] = "Frijoles";
row["Total"] = 60.25;
dt.Rows.Add(row);
row = dt.NewRow();
row["Id"] = 4;
row["Producto"] = "Leche";
row["Total"] = 45.25;
dt.Rows.Add(row);
return dt;
}
Private Function Datos() As DataTable
Dim dt As New DataTable()
dt.Columns.Add("Id")
dt.Columns.Add("Producto")
dt.Columns.Add("Total")
Dim row As DataRow = dt.NewRow()
row("Id") = 1
row("Producto") = "Arroz"
row("Total") = 50.0
dt.Rows.Add(row)
row = dt.NewRow()
row("Id") = 2
row("Producto") = "Pollo"
row("Total") = 75.25
dt.Rows.Add(row)
row = dt.NewRow()
row("Id") = 3
row("Producto") = "Frijoles"
row("Total") = 60.25
dt.Rows.Add(row)
row = dt.NewRow()
row("Id") = 4
row("Producto") = "Leche"
row("Total") = 45.25
dt.Rows.Add(row)
Return dt
End Function
Es un método de tipo datatable que retornara todos los datos en este caso como ya lo dije agrego los datos manualmente en caso de usar una base de datos lo único que cambiaría seria la manera de como se llena el datatable.
Ahora en el evento load del formulario cargamos los datos en el datagriedview y agregamos una nueva fila al datatable.
private void Form1_Load(object sender, EventArgs e)
{
//agregamos una nueva fila al datatable
DataTable dt = Datos();
DataRow row= dt.NewRow();
dt.Rows.Add(row);
//mostramos los datos en el datagriedview
dataGridView1.AutoGenerateColumns = false;
dataGridView1.DataSource = dt;
//Mostramos el valor de 0 en la fila que agregamos
DataGridViewRow rowtotal = dataGridView1.Rows[dataGridView1.Rows.Count - 1];
rowtotal.Cells["Total"].Value = 0;
}
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'agregamos una nueva fila al datatable
Dim dt As DataTable = Datos()
Dim row As DataRow = dt.NewRow()
dt.Rows.Add(row)
'mostramos los datos en el datagriedview
dataGridView1.AutoGenerateColumns = False
dataGridView1.DataSource = dt
'mostramos el valor de 0 en la fila que agregamos
Dim rowtotal As DataGridViewRow = dataGridView1.Rows(dataGridView1.Rows.Count - 1)
rowtotal.Cells("Total").Value = 0
End Sub
Lo primero que hacemos es agregar una nueva fila al datatable que nos servirá para mostrar el total de la suma de la columna, luego cargamos los datos en el datagriedview y por ultimo le asignamos el valor de 0 a la fila que agregamos para calcular la suma.
Lo ultimo que nos queda por hacer es calcular la suma de la columna del datagriedview que en este caso sera la columna Total y mostrar el resultado.
private void btntotal_Click(object sender, EventArgs e)
{
//hacemos la suma de la columna total
double resul = dataGridView1.Rows.Cast<DataGridViewRow>().Sum(x => Convert.ToDouble(x.Cells["Total"].Value));
//mostramos la suma en el textbox y en la fila que agregamos
txttotal.Text = Convert.ToString(resul);
DataGridViewRow rowtotal = dataGridView1.Rows[dataGridView1.Rows.Count - 1];
rowtotal.Cells["Total"].Value = resul;
}
Private Sub btntotal_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btntotal.Click
'hacemos la suma de la columna Total
Dim resul As Double = dataGridView1.Rows.Cast(Of DataGridViewRow)().Sum(Function(x) Convert.ToDouble(x.Cells("Total").Value))
'mostramos la suma en el textbox y en la fila que agregamos
txttotal.Text = Convert.ToString(resul)
Dim rowtotal As DataGridViewRow = dataGridView1.Rows(dataGridView1.Rows.Count - 1)
rowtotal.Cells("Total").Value = resul
End Sub
Como pueden observar si se hace uso de linq se puede obtener la suma de la columna del datagriedview en una sola linea de código sin necesidad de recorrer el datagriedview, luego que se obtiene el resultado lo único que se hace es mostrarlo en el textbox y en la fila adicional que agregamos.
Eso es todo, pueden descargar el ejemplo desde mi blog saludos.
http://cristiantorresalfaro.blogspot.com/2012/08/sumar-columnas-datagridview-usando-linq.html