Total of Selected Items in Gridview - c#

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...
});

Related

Getting the selected rows' values in datagridview and adding them up

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();

Need to sum up the checked text box values in telerik grid

i have created a telerik grid for small payment module
in this module i have selected two checkbox and enter a amount,i need the total amount to be displayed in the donation amount label
The current code is to sum up the values displayed in the second column,and saving the values in session and passsing to next page.
Gridview
<telerik:GridTemplateColumn FilterControlAltText="Filter TemplateColumn3 column" UniqueName="TemplateColumn3">
<ItemTemplate>
<asp:TextBox ID="txt_amnt" runat="server"></asp:TextBox> </td>
</ItemTemplate>
</telerik:GridTemplateColumn>
c# code
protected void chk_box_CheckedChanged(object sender, EventArgs e)
{
if (ViewState["dt"].ToString().Trim() != "NULL")
{
dt = (DataTable)ViewState["dt"];
}
if (dt.Columns.Count == 0)
{
dt.Columns.Add("Id");
dt.Columns.Add("Name");
dt.Columns.Add("Amount");
}
CheckBox chk = (CheckBox)sender;
if (chk.Checked == true)
{
dt.Rows.Add();
dt.Rows[dt.Rows.Count-1 ]["Id"] = ((Label)chk.FindControl("lb_id")).Text.Trim();
dt.Rows[dt.Rows.Count - 1]["Name"] = ((Label)chk.FindControl("lb_donation")).Text.Trim();
dt.Rows[dt.Rows.Count - 1]["Amount"] = ((Label)chk.FindControl("lb_amount")).Text.Trim();
// dt.Rows[dt.Rows.Count + 1]["chkstatus"] = ((Label)chk.FindControl("lb_amount")).ToString().Trim();
}
else {
for (int i = 0; i < dt.Rows.Count; i++)
{
if(((Label)chk.FindControl("lb_id")).Text.Trim()==dt.Rows[i]["Id"].ToString().Trim())
{ dt.Rows.RemoveAt(i); }
}
}
ViewState["dt"] = dt;
double tamount = 0;
for (int i2 = 0; i2 < dt.Rows.Count; i2++)
{
tamount = tamount + Convert.ToDouble(dt.Rows[i2]["Amount"]);
}
lb_tamount.Text = tamount.ToString() ;
}
I believe your code for the CheckBox will always hit error.
How can you find a control inside a CheckBox ? Secondly your code is not complete as per the result you are showing. Anyway here is the idea how you can get checked item in your RadGrid.
First you need loop the RadGrid to get all checked CheckBox.
Then sum up the total and put it to the label.
This code just to mock up for your scenario. Please use TryParse to get the int value to ensure no converting error.
Code Behind
protected void chkCheck_CheckedChanged(object sender, EventArgs e)
{
// Variable
int total = 0;
int amt = 0;
int donateAmt = 0;
foreach (GridDataItem item in rg.Items)
{
// Find Control
CheckBox chkCheck = item.FindControl("chkCheck") as CheckBox;
Label lblAmount = item.FindControl("lblAmount") as Label;
TextBox txtAmount = item.FindControl("txtAmount") as TextBox;
// Reset Amount
amt = 0;
donateAmt = 0;
// Check
if (chkCheck != null && chkCheck.Checked)
{
// Check & Get Value
if (lblAmount != null && txtAmount != null)
{
// Check & Set
if (lblAmount.Text.Trim() != string.Empty)
amt = Convert.ToInt32(lblAmount.Text.Trim());
// Check & Set
if (txtAmount.Text != string.Empty)
donateAmt = Convert.ToInt32(txtAmount.Text.Trim());
// Check current Amount in stock and donate amt
if (donateAmt > amt)
{
donateAmt = amt;
txtAmount.Text = donateAmt + "";
}
// Reset to the text
}
total += donateAmt;
}
}
lblTotal.Text = total + "";
}

Getting textBox value of checked row in grid view

I am having some problem for getting the text from textbox in a row which the checkbox was marked check in gridview. When button on click, it supposed to get the checked row index for prodID and the quantity which is the text from textbox:
protected void lbnConfirm_Click(object sender, EventArgs e)
{
string quantity = "" , prodID = "";
foreach (RepeaterItem item in Repeater1.Items)
{
if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
{
Panel pnl = item.FindControl("pBody1") as Panel;
GridView gv = pnl.FindControl("gvProduct") as GridView;
foreach (GridViewRow gr in gv.Rows)
{
CheckBox cb = (CheckBox)gr.Cells[0].FindControl("cbCheckRow");
if (cb.Checked)
{
//Get the productID which set as DataKeyNames for selected row index
prodID = gv.DataKeys[gr.RowIndex].Value.ToString();
var tbQuantity = gr.FindControl("tbQuantity") as TextBox;
if (tbQuantity != null)
{
quantity = tbQuantity.Text;
}
tempList.Add(prodID);
}
}
}
}
for (int i = 0; i < tempList.Count; i++)
{
//Testing
lblTest.Text += tempList[i] + " " + quantity;
}
}
Let's say I got prodID 1 with 50 units, prodID 2 with 77 units, prodID 3 with 90 units. When I loop thru the tempList, this is the result which I supposed to get:
1 50units, 2 77units, 390units
However, the codes does not get the quantity from the textbox for each product independently. Here is the result which I get:
1 90units, 2 90units, 3 90units
It just simply get the quantity of last product in the list. I wonder is there any way to fix this? Thanks in advance.
Edited Portion:
foreach (string key in tempList.Keys)
{
packagesNeeded = 1;
unitQty = prodPackBLL.getUnitQtySPU(tempList[key]);
lblTest.Text += key + " " + tempList[key];
if (Convert.ToInt32(quantity) < (packagesNeeded * unitQty))
{
//Pop up message
Page.ClientScript.RegisterStartupScript(GetType(), "UserDialogScript", "alert(\"Insufficient storage\");", true);
}
}
You can use Dictionary to pair each prodID with its corresponding quantity. Try this code:
protected void lbnConfirm_Click(object sender, EventArgs e)
{
Dictionary<string, string> tempList = new Dictionary<string, string>();
string quantity = "", prodID = "";
foreach (RepeaterItem item in Repeater1.Items)
{
if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
{
Panel pnl = item.FindControl("pBody1") as Panel;
GridView gv = pnl.FindControl("gvProduct") as GridView;
foreach (GridViewRow gr in gv.Rows)
{
CheckBox cb = (CheckBox)gr.Cells[0].FindControl("cbCheckRow");
if (cb.Checked)
{
//Get the productID which set as DataKeyNames for selected row index
prodID = gv.DataKeys[gr.RowIndex].Value.ToString();
var tbQuantity = gr.FindControl("tbQuantity") as TextBox;
if (tbQuantity != null)
{
quantity = tbQuantity.Text;
}
tempList.Add(prodID, quantity);
}
}
}
}
foreach (string key in tempList.Keys)
{
packagesNeeded = 1;
unitQty = prodPackBLL.getUnitQtySPU(key);
lblTest.Text += key + " " + tempList[key];
if (Convert.ToInt32(tempList[key]) < (packagesNeeded * unitQty))
{
//Pop up message
Page.ClientScript.RegisterStartupScript(GetType(), "UserDialogScript", "alert(\"Insufficient storage\");", true);
}
}
}
Based on your examples above, tempList["1"] will produce "50", tempList["2"] will produce "77", and tempList["3"] will produce "90".
It is because you keep overriding variable "quantity" for each row you have the checkbox selected. If you want to store multiple values you need to use List<string> to store the quantities for each row where the checkbox is selected.
Something like below. Note: I haven't tested the code.
protected void lbnConfirm_Click(object sender, EventArgs e)
{
List<string> quantity = new List<string>();
prodID = "";
foreach (RepeaterItem item in Repeater1.Items)
{
if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
{
Panel pnl = item.FindControl("pBody1") as Panel;
GridView gv = pnl.FindControl("gvProduct") as GridView;
foreach (GridViewRow gr in gv.Rows)
{
CheckBox cb = (CheckBox)gr.Cells[0].FindControl("cbCheckRow");
if (cb.Checked)
{
//Get the productID which set as DataKeyNames for selected row index
prodID = gv.DataKeys[gr.RowIndex].Value.ToString();
var tbQuantity = gr.FindControl("tbQuantity") as TextBox;
if (tbQuantity != null)
{
quantity.Add(tbQuantity.Text);
}
tempList.Add(prodID);
}
}
}
}
for (int i = 0; i < tempList.Count; i++)
{
//Testing
lblTest.Text += tempList[i] + " " + quantity[i];
}
}
you can do something like :
foreach (DataGridViewRow item in GV.Rows)
{
if (Convert.ToBoolean(item.Cells[0].Value) == true)
//here you get the rowcell value :
string val = item.Cells[1].Value.ToString();
//If you want to convert to a textbox :
TextBox textBox = (TextBox)item.Cells[1].Value;
}
where GV is the gridview Id
and checkbox is the 0 column and the value you might want to get is the 1 column

How to change the index of previous selected Dropdownlist?

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

Assign a value to special footer column in Gridview

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();

Categories

Resources