I would like to show into a label the resul of the sum of all cells of one column. I tried one code that I saw in the net but the code doesnt work.
Here's the code:
foreach (DataGridViewRow row in dgv_Carrinho.Rows.Cast<DataGridViewRow>().Where(t => !string.IsNullOrEmpty(t.Cells["Valor"].Value?.ToString())))
{
lbl_Subtotal.Text += (Convert.ToDouble(row.Cells["Valor"].Value)).ToString();
}
Could someone help me?
You have to calculate sum first, then assign it to lbl_Subtotal.Text, something like
var sum = 0;
foreach (DataGridViewRow row in dgv_Carrinho.Rows.Cast<DataGridViewRow>().Where(t => !string.IsNullOrEmpty(t.Cells["Valor"].Value?.ToString())))
sum += (Convert.ToDouble(row.Cells["Valor"].Value));
//Now assign it to label
lbl_Subtotal.Text = sum.ToString();
Lets try some linq operations,
var sum = dgv_Carrinho.Rows.Cast<DataGridViewRow>()
.Select(double.TryParse(row.Cells["Valor"].Value?.ToString(), out double value) ? value : 0)
.Sum();
//Now assign it to label
lbl_Subtotal.Text = sum.ToString();
var count = 0;
foreach (DataGridViewRow row in dgv_Carrinho.Rows.Cast<DataGridViewRow>().Where(t => !string.IsNullOrEmpty(t.Cells["Valor"].Value?.ToString())))
{
count += (Convert.ToDouble(row.Cells["Valor"].Value)).ToString();
}
lbl_Subtotal.Text = count.ToSring();
u can add extension function for DataGridView
public double getSumCell(this DataGridView GridView, string ColName)
{
double sumValue = (from d in GridView.Rows
select d).Sum(DataGridViewRow x => Convert.ToDouble(x.Cells(ColName).Value));
return sumValue;
}
usage:
lbl_Subtotal.Text = dgv_Carrinho.getSumCell("COLUMN_NAME");
Related
I have some text and a datagridview with 5 columns. How can I find this text in the first column and get values from other columns in the same row?
I think the code lines will give you the datagridview row index for the value:
String searchValue = "somestring";
int rowIndex = -1;
foreach(DataGridViewRow row in DataGridView1.Rows)
{
if(row.Cells[1].Value.ToString().Equals(searchValue))
{
rowIndex = row.Index;
break;
}
}
then you can do:
dataGridView1.Rows[rowIndex].Selected = true;
It would be :
List<string> Values = new List<string>();
foreach (DataRow row in YourDataTable.Rows)
{
if (row["firstColumn"].ToString() == yourText)
{
Values.Add(row["firstColumn"].ToString());
Values.Add(row["secondColumn"].ToString());
Values.Add(row["thirdColumn"].ToString());
Values.Add(row["fourthColumn"].ToString());
Values.Add(row["fifthColumn"].ToString());
}
}
I have several TextBoxes on form. I have assigned them the same Tag value. Now I want to access and sum up values of these TextBoxes. I have tried the following but it didn't work. Even it didn't throw any exception. But the control exit from the function before foreach loop. Any help will be appreciated. Thanks in advance.
private void CalculateExpense()
{
int sum = 0;
var textBoxes = this.Controls
.OfType<TextBox>()
.Where(d => d.Tag.ToString() == "ExpenseField")
.ToList();
foreach (var item in textBoxes)
{
sum = sum + Convert.ToInt16(!string.IsNullOrEmpty(item.Text) ? item.Text : "0");
}
this.TotalExpenseLbl.Text = sum.ToString();
this.TotalMonthlyExpenses.Text = sum.ToString();
}
If all the TextBoxes are directly on the form and not within containers (Panels, GroupBoxes etc).
int sum = Controls
.OfType<TextBox>()
.Where(box => string.Equals("ExpenseField", box.Tag as String))
.Select(box => int.TryParse(box.Text, out var v) ? v : 0)
.Sum();
this.TotalExpenseLbl.Text = sum.ToString();
this.TotalMonthlyExpenses.Text = sum.ToString();
It seems, that the main problem in your code is in d.Tag.ToString() since Tag is null by default.
Edit: in case TextBoxes are within several containes, you have to use recursion instead of Controls collection:
private static IEnumerable<Control> GetAll(Control control) {
var controls = control.Controls.OfType<Control>();
return controls
.SelectMany(ctrl => GetAll(ctrl))
.Concat(controls);
}
...
int sum = GetAll(this)
.OfType<TextBox>()
.Where(box => string.Equals("ExpenseField", box.Tag as String))
.Select(box => int.TryParse(box.Text, out var v) ? v : 0)
.Sum();
this.TotalExpenseLbl.Text = sum.ToString();
this.TotalMonthlyExpenses.Text = sum.ToString();
I have this code trying to make it work but it just wont.
private void Izračunaj_Click(object sender, EventArgs e) //it calculates value on click
{
int total;
foreach(dataGridView1 column in dataGridView1.Rows()) //
{
total = total + int32.Parse(column[2].ToString());
}
textbox text = total; // want to have calculated value displayed in a text box
}
Error I get:
Non-invocable member 'System.Windows.Forms.DataGridView.Rows' cannot be used like a method.
I just dont know which syntax i need to use there.
I think it should solve your problem
int sum = 0;
for (int i = 0; i < dataGridView1.Rows.Count; ++i)
{
sum += Convert.ToInt32(dataGridView1.Rows[i].Cells[2].Value);
}
Rows is a property and you are using () which designates a method. Just remove the brackets.
foreach(dataGridView1 column in dataGridView1.Rows) //No ()
If you want to use LINQ then you can do:
total = dataGridView1.Rows
.OfType<DataGridViewRow>()
.Sum(r => Convert.ToInt32(r.Cells[2]));
You need to access Cell property of the row for your calculation.
To show it in the TextBox
textBox1.text = total.ToString();
I have a Gridview like this;
In my .cs file i calculate value of BV, MV, KV total value with this code and i assign to a Label. Labels are under the Gridview. BUT, some customer names long some of short, because of that, labels location changing according to Gridview. Because of that i don't want use Label.
I calculate a value with this code, and how can i assing BV, MV and KV columns footer this value?
double sumRISK = 0;
foreach (GridViewRow gvr in GridView1.Rows)
{
CheckBox cb = (CheckBox)gvr.FindControl("NameCheckBoxField1");
if (cb.Checked == true)
{
double amountBV = Convert.ToDouble(gvr.Cells[7].Text);
if (amountBV != -1)
{
sumRISK += amountBV;
}
}
}
RISK_Label.Text = String.Format("{0:n}", sumRISK);
You should be able to set the FooterRow like below
GridView1.FooterRow.Cells[0].Text = SumRISK.ToString();
Here is a small working example using the same way of summarizing as you.
int[] values = {1,3,6};
GridView1.DataSource = values;
GridView1.DataBind();
int total = 0;
foreach (GridViewRow item in GridView1.Rows)
{
total += Convert.ToInt32(item.Cells[0].Text);
}
GridView1.FooterRow.Cells[0].Text = total.ToString();
HI, I've a DataGridView with this setting: d
dataGridView1.AllowUserToOrderColumns = true;
(so the users can reorder columns)
My problem is that I want to know the current order of columns.
I've done this methond:
public List<int> getActualTaskOrder() {
List<int> ris = new List<int>();
int i=1;
while(i<this.dataGridView1.Columns.Count){
DataGridViewColumn c= this.dataGridView1.Columns[i];
if (c.Name != "**")
{
Console.WriteLine(c.HeaderText);
ris.Insert(c.Index-1, System.Convert.ToInt32(c.Tag));
}
i++;
}
return ris;
}
my problem is that the result (the order of columns) is always the same (also if I move columns in my gui)
You need to look at the DisplayIndex of your columns; perhaps something like:
var qry = from DataGridViewColumn col in grid.Columns
where col.Name != "**"
orderby col.DisplayIndex
select col.HeaderText;
foreach (string txt in qry) {
Console.WriteLine(txt);
}