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();
Related
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");
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 am making a booking winsform application now. When a user chooses any number of rows, there will be a column called rental price that each row is under. Then the value of this cell under the column called rental price will be gotten and add up and display to the total cost label text.But the problem is the total cost is not displaying. Here is my code:
private void Payment_Load(object sender, EventArgs e)
{
NameOfUser.Text = UserAccounts[0].Name;
EmailOfUser.Text = UserAccounts[0].Email;
PaymentType.Text = UserAccounts[0].PaymentType;
double totalCost = 0;
foreach (DataGridViewRow row in b1.DataGridView1.SelectedRows)
{
int index = 0;
foreach (DataGridViewCell cell in row.Cells)
{
totalCost += (double)dataGridView1.Rows[index].Cells[4].Value;
}
index++;
}
TotalCost.Text = Convert.ToString(totalCost);
}
Yes the Mistake is in the looping, As of now you are iterating the rows in the SelectedRows and by using the inner loop you again looping through the cells of each row But taking values with respect to the actual grid instead for the cell. You can make this simple as you wanted to iterate through the selected rows and need to sums the value of .Cells[4] in each row. for that you have to do something like this:
foreach (DataGridViewRow row in b1.DataGridView1.SelectedRows)
{
string value = row.Cells[4].Value.ToString();
double currentCellValue = 0.0;
if(double.TryParse(value , out currentCellValue)
{
totalCost += currentCellValue;
}
}
TotalCost.Text = totalCost .ToString();
I have gridview with template field of dropdownlist in each row.when i select any value from dropdownlist it will change color of 3rd row below than it.But when i click on another dropdownlist it is changing the color of 3rd row below than it but the index of previous dropdownlist is not changed to 0 i.e"Select".it is still showing the value selected in last dropdown list.I just want when i click on a dropdownlist ,all other dropdownlist should be indexed to 0 i.e "Select" except one which i have clicked.
I am doing following in Selectedindexchange event of dropdownlist:
protected void GridView1_SelectedIndexChanged(object sender,EventArgs e)
{
foreach (GridViewRow gvRow in GridView1.Rows)
{
int g1 = gvRow.RowIndex;
GridView1.Rows[g1].BackColor = Color.White;
}
DropDownList ddl = (DropDownList)sender;
GridViewRow row = (GridViewRow)ddl.NamingContainer;
int g = row.RowIndex + 3;
int current_row_index = row.RowIndex;
int pp = GridView1.Rows.Count;
GridView1.Rows[g].BackColor = Color.Red;
}
}
Thanks in advance.
Just use DropdownName.ClearSelection() for each of your other dropdown except the one where you are calling Selectedindexchange event.
Maybe something like this:
protected void GridView1_SelectedIndexChanged(object sender,EventArgs e)
{
DropDownList ddl = (DropDownList)sender;
GridViewRow row = (GridViewRow)ddl.NamingContainer;
int g = row.RowIndex + 3;
int current_row_index = row.RowIndex;
foreach (GridViewRow gvRow in GridView1.Rows)
{
gvRow.BackColor = Color.White;
if (gvRow.FindControl("nameOfTheDropdown") != null && gvRow.RowIndex != current_row_index)
{
((DropDownList)gvRow.FindControl("nameOfTheDropdown")).SelectedIndex = 0;
}
}
GridView1.Rows[g].BackColor = Color.Red;
}
Regards
I have a Gridview
I have Click Button and two labels. (Risk_label and MV_label)
Risk and MV column has price value.
My Checkbox column names are NameCheckBoxField1 and NameCheckBoxField2
How can i calculate only "Which i selected in Gridview" Risk total and MV total in my labels?
Example;
Risk (Checked rows) --> 10, 20, 30 ---> Risk_label = 60
MV (Checked rows) --> 20, 30, 40 ---> MV_label = 90
EDİT: I try this code;
double sum = 0;
foreach (GridViewRow gvr in GridView1.Rows)
{
CheckBox cb = (CheckBox)gvr.FindControl("NameCheckBoxField1");
if (cb.Checked)
{
double amount = Convert.ToDouble(gvr.Cells[1].Text);
sum += amount;
}
}
Risk_label.Text = sum.ToString();
But i getting an error.
protected void CalculateButton_Click(object sender, EventArgs e)
{
Int32 totalMVValue = 0, totalRiskValue = 0;
// Iterate through the Products.Rows property
foreach (GridViewRow row in GridView1.Rows)
{
// Access the CheckBox
CheckBox mvSelectorCheckBox = (CheckBox)row.FindControl("MVSelector");
if (mvSelectorCheckBox != null && mvSelectorCheckBox.Checked)
{
// First, get the primaryId for the selected row
int mvValue=
Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value);
totalMVValue += mvValue;
}
CheckBox riskSelectorCheckBox = (CheckBox)row.FindControl("RiskSelector");
if (riskSelectorCheckBox != null && riskSelectorCheckBox.Checked)
{
// First, get the primaryId for the selected row
int riskValue =
Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value);
totalRiskValue += riskValue;
}
}
}
Looking at your last comment:
<asp:templatefield headertext=""> <itemtemplate> <asp:CheckBox DataField="NameCheckBoxField1" Checked="True" runat="server"></asp:CheckBox> </itemtemplate> </asp:templatefield>
Is DataField assigned NameCheckBoxField1? Or is it a typo?
It should be ID="NameCheckBoxField1"
I think jQuery would be the best option for you.
1. Add classes for Risk_Label and MV_Label
2. On checkbox click get the value of Risk_Label and MV_Label of the same row using the classes.
3. If it is checked then add value other wise subtract values.
$('.mygrid :checkbox').click(function () {
var amt = parseFloat($(this).parents('tr').find('.ClassRisk_label').text());
//One Fee Case
if (!isNaN(amt)) {
if ($(this).is(':checked')) {
totalAmt = totalAmt + amt;
}
else {
totalAmt = totalAmt - amt;
}
}
//Show the value...
});