I can not find the way to do the addition of a column in a datagridview.
I can not find the way to do the addition of a column in a datagridview.
I made a desktop application as an example. Where I define a datatable with data to feed a grid. Finally there is a button that computes the number of articles in total. In this example, use integers.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication7
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
CargaDatos();
}
public void CargaDatos()
{
DataTable tabla = GetTable();
dataGridView1.DataSource = tabla;
dataGridView1.Show();
}
static DataTable GetTable()
{
DataSet ds = new DataSet();
DataTable tabla = new DataTable();
ds.Tables.Add(tabla);
tabla.Columns.Add("Articulo", typeof(string));
tabla.Columns.Add("Cantidad", typeof(Int32));
tabla.Rows.Add("A",100);
tabla.Rows.Add("B",200);
tabla.Rows.Add("C",300);
return tabla;
}
private void button1_Click(object sender, EventArgs e)
{
int suma = 0;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.Cells["Cantidad"].Value != null)
suma += (Int32)row.Cells["Cantidad"].Value;
}
MessageBox.Show(suma.ToString());
}
}
}
In the handler of the button the sum that in this case was made by the name of the column defined as "Quantity" is observed, it can also be accessed by column number instead of the name.
private void button1_Click(object sender, EventArgs e)
{
int suma = 0;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.Cells["Cantidad"].Value != null)
suma += (Int32)row.Cells["Cantidad"].Value;
}
MessageBox.Show(suma.ToString());
}
}
The same method as the previous one but by number would be as follows
private void button1_Click(object sender, EventArgs e)
{
int suma = 0;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.Cells[1].Value != null) //1 es "Cantidad"
suma += (Int32)row.Cells[1].Value;
}
MessageBox.Show(suma.ToString());
}
Screen output
Greetings.