how to calculate datagridview column? - c#

I am a new user in C# winform and also new user in this site, too
I have a datagridview with 4 columns
No. proname price qty total
1 fish 0.0 1 -
2 tofu 0.0 1 -
Data in example like that, I give the default price and qty like above total is empty. Now I need to cellclick on column price to new input value on currentrow after I gave the new value I leave it by press Enter key or anyway just leave the cell I need the price*qty = total on currentrow. Or opposite I new input the qty to 2... and price not "0.0" then Price * qty=total
But if I edit on other cell not two of above the event do nothing.
How do I multiply that ?
Anybody can help me in better solution?
Thank you in advance.

In the code Behind use this
int.Parse(row.Cells[3].Value.toString()) * int.Parse(row.Cells[4].Value.toString())
Your Method look like this
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
int quantity,rate;
if (int.TryParse(dataGridView1.Rows[e.RowIndex].Cells["quantity"].Value.ToString(), out quantity) && int.TryParse(dataGridView1.Rows[e.RowIndex].Cells["rate"].Value.ToString(), out rate))
{
int price = quantity * rate;
dataGridView1.Rows[e.RowIndex].Cells["price"].Value = price.ToString();
}
}
For more find reference here
Another Reference

Here is exactly what you're looking for. Answer
The answer given by this guy is really well explained and it's not going to be hard doing the implementation.
By this way the "Total" column is automatically maintained via an
Expression which means you cannot manually do anything to that column.

Related

Divide between two rows of the same column and store the answer in a already existing column

I have a table in my database that has columns 'price', 'percentage' and 'ID'.
Percentage column needs to be calculated using colum 'price' and 'id'. There is an initial price, followed by three increased prices, all of them having the same ID. I need to find a method that calculates the percentage column in my database using C#.
I attach a picture for better understanding how it should be.
I am writing an import system using Linq and I have already imported all the columns, but now I need to calculate percentage for the increasing prices and I am really struggeling with this. Maybe someone have some god suggestions of how I can solve this.
UPDATE:
public static void calculateProcentage(string id, double price, double, double percentage)
{
var percentageQuery = from l in db.Table
where l.ID == id
&& l.Price == price && l.Percentage != percentage
select l;
foreach (Table l in percentageQuery)
{
//double newPercentage = (double) l.Percentage;
//DataTable table = new DataTable();
// int rowCount = table.Rows.Count;
DataGridView dataGridView = new DataGridView();
for (int i = 0; i < dataGridView.Rows.Count; i++)
{
if (l.Building_vigor_ID == building_vigor_id)
{
//var priceRows = db.V_Leases.Select(x => x.Price_sqm).ToList();
// get a list of the rows of the price column
// get a list of the rows of the price column
var priceRows = (from r in db.Table
select r.Price).ToList();
percentage = (double)(priceRows[i] / priceRows[i + 1]);
}
}
}
try
{
db.SubmitChanges();
Console.Write("Percentage updated");
//Console.ReadKey();
}
catch (Exception e)
{
Console.WriteLine(e);
Console.Write("Could not update percentage");
//Console.ReadKey();
}
}
That is what I have tried. I bassicaly wanted to make it like an update method with only updating column percentage. But did not actualy work. I am pretty new with Linq sow it may be some bad code written here.
The disclaimer
I am pretty new with Linq sow it may be some bad code written here.
Your question, and the way you've attempted to solve this, are fraught with inconsistencies and seemingly contradictory expectations.
As it stands, the question you've asked is not answerable due to lack of information. However, I do think I understand what the actual problem is that you're trying to solve, so I'll give you that answer. But first, let me explain how I've interpreted your question.
My assumptions about your actual question
As I understand it, you're trying to calculate the percentage based on the previous value.
A more generalized example:
PRICE % ID
------------------------
100 A 1
103 B 1
100 C 2
150 D 2
A and C should both be 0 as they are the "base" price of their respective ID value.
B should be 3% because its price is 103% of A's price.
D should be 50% because its price is 150% of C's price.
My below answer will assume that this is correct.
There is also a problem with your expected values. In your example, you have listed the percentage of 19.79 (compared to 19.21) as 0.3.
This does not make sense. The difference is 3%. There are two different (acceptable) ways to denote this in the percentage column:
3, because it is expressed as a percentage (3%)
0.03, because it is expressed as a decimal value (3% = 0.03)
Your usage of 0.3 makes no sense, as I would interpret this as either 0.3% (option 1) or 30% (option 2).
In order to maintain consistency, my answer will assume that you want the decimal value (0.03 in the above example)
I assume your data class is constructed as follows:
public class Foo
{
public decimal Price { get; set; }
public decimal Percentage { get; set; }
public int ID { get; set; }
}
I don't quite understand how you're using the method. You supply three parameters (string id, double price, double, double percentage), but then you go on to select your data as follows:
var percentageQuery = from l in db.Table
where l.ID == id
&& l.Price == price && l.Percentage != percentage
select l;
It makes little sense to supply a percentage, and then pick everything that's different from that percentage. You have no idea of knowing what data you're going to get, in what order, and whether or not the found entries are "before" or "after" your mentioned percentage.
Instead, my answer will be a method that recalculates all percentages of a given ID. This seems like a much clearer algorithm.
The assumed answer
Retrieving the data
Your attempt is a weird mix of new and old technologies (LINQ, DataTable), I'm going to use LINQ near exclusively, as I feel the use of DataTable is unwarranted here.
public static void CalculatePercentagesForID(int id)
{
Foo[] rows = db.Table.Where(x => x.ID == id).ToArray();
//... (see the next code block)
}
This is much simpler. Note that I am assuming that you wish to process the entries based on the order that they appear in the database. If you need to order them based on something else (e.g. a date value in your Foo objects), then you will have to use an additional OrderBy, e.g. :
Foo[] rows = db.Table.Where(x => x.ID == id).Orderby(x => x.DateCreated).ToArray();
Processing the data
It's important to notice here that a percentage is calculated off of two (subsequent) rows.
//The first entry is always the "base" price, therefore always 0.
rows[0].Percentage = 0;
for(int i = 1; i < rows.Length; i++)
{
var previous = rows[i-1];
var current = rows[i];
current.Percentage = CalculateDifferenceInPercentage(previous.Price, current.Price);
}
//TODO: save all the objects in "rows" back to the database!
Notice how the for loop starts at 1, not at 0. We skip step 0 because the first element is automatically 0 anyway. The for loop will only process every row after the first.
Calculating the percentage
public static Decimal CalculateDifferenceInPercentage(decimal oldPrice, decimal newPrice)
{
//1.The elaborate calculation
//The comments are example output when oldPrice = 19.21, newPrice = 19.79
var theRatio = newPrice / oldPrice;
// = 1.0301...
var theRatioRounded = Math.Round(theRatio,2);
// = 1.03
var thePercentageDifference = theRatioRounded - 1;
// = 0.03
return thePercentageDifference;
}
Or, if you want a shorter (but harder to read) version:
public static Decimal CalculateDifferenceInPercentage(decimal oldPrice, decimal newPrice)
{
return Math.Round(newPrice / oldPrice , 2) - 1;
}
Some caveats
I've omitted some null-checks for the sake of simplicity, e.g. checking if any rows are returned.
I've omitted how to save the updated entities in the database as it is not pertinent to your actual question about calculating the percentages.
This works both for negative and positive percentages.

How to deduct total amount when deleted on the datagridview

So I have a school program which is the ordering system.
I have 3 buttons namely add order, delete order, update order.
I need some help on the subtraction part
in which the selected rows and the cell where column name Amount belong will be deducted from the txtTotalAmount
I already did the addition part like when add order button clicked total Amount textbox sum it
Here's the code:
int totalx = 0;
int Totalxr = int.Parse(txtTotal.Text);
totalx += Totalxr;
txtTotalAmount.Text = totalx.ToString();
I tried the subtraction part but I failed to do it.
Here's my code
int Totalxr = int.Parse(txtTotal.Text);
int txrs = int.Parse(txtTotalAmount.Text);
int str = txrs - Totalxr;
txtTotalAmount.Text = str.ToString();
clarification of what I want to achieved.
Example the total would be 7300.
if selected row has an amount of 4300 which is shown in the image above then totalamount textbox should update when it is deleted and making the total amount of 3000. then again if user again selects the row with 3000 under the column amount the totalamount will be updated from 3000 to 0 since the selected row amount has 3000 and the current total is 3000.
Hope I already clarify what I wanted to do.
Lastly Why I can't remove the txtAmount.textwhich I will be doing after add order is successful
like when I used txtAmount.Clear(); the text is still there. while the other txts which I use the clear function works.

Multiplying the sum of numbers in a column with the sum of numbers in another column? Access to C#

This program displays database information in a Data Grid View. I need to add all the numbers in column 1, add all the numbers in column 3, and multiply the two sums together.
This code only multiplies column 1 and column 3 from the last row. Any suggestions?
This is my first time connecting to a database, so I apologize if this seems like a dumb question
foreach (DataRow currentRow in itemDS.Tables[0].Rows)
{
// add to data grid view
invoiceDataGridView.Rows.Add(currentRow[1].ToString(), currentRow[2].ToString(), currentRow[3].ToString());
var itemQuant = Convert.ToDecimal(currentRow[1]);
var priceEach = Convert.ToDecimal(currentRow[3]);
decimal subTotal = itemQuant * priceEach;
subTotalOutput.Text = subTotal.ToString();
}
Do you mean you're not sure how to keep a running total in the looping construction? If so:
decimal total = 0; //declare outside the foreach
foreach (DataRow currentRow in itemDS.Tables[0].Rows)
{
// add to data grid view
invoiceDataGridView.Rows.Add(currentRow[1].ToString(), currentRow[2].ToString(), currentRow[3].ToString());
var itemQuant = Convert.ToDecimal(currentRow[1]);
var priceEach = Convert.ToDecimal(currentRow[3]);
decimal subTotal = itemQuant * priceEach;
total += subTotal;
}
//do something with total here, after for each finishes
you can use linq for taking sum of a column.
var sum = itemDS.Tables[0].AsEnumerable().Sum(dr => dr.Field<int>("value"));
"value" will be the column name of the datatable inside the itemDS. you have to specify your column name here.
Take the sum of next column like the above statement. add multiply it..
Hope this helps.. :)

datagridview multiplying cell value

I have a problem with DataGridView. I want to multiply two cells and display the result in a third cell.
I have two DataGridViews. The first DataGridView gets data from database. The second DataGridView gets values after I select row from first DataGridView and adds that row to second DataGridView. Column A gets from first DataGridView (from database); in column B the user inserts values manually.
example of second datagridview:
Price | Amount | Total
10.50 | 2 | 21.00
5.20 | 4 | 20.80
7.30 | 5 | 36.50
After that I want to sum column C and display the sum in a text box.
Column A is type decimal; Column B is integer; Column C should be decimal too.
This is solution that one guy gave me on internet but it works only for DataGridView that gets data manually, it doesn't work if data is from database:
decimal sum = 0.0m;
for (int i = 0; i < gridProizvodi.Rows.Count; i++)
{
DataGridViewRow row = gridProizvodi.Rows[i];
if (row.IsNewRow) break;
decimal product = Convert.ToDecimal(row.Cells[1].Value)
* Convert.ToInt32(row.Cells[2].Value);
sum += product;
row.Cells[3].Value = product;
}
txtCijena.Text= sum.ToString();
I get an argument out of range exception was unhandled error in this line
decimal product = Convert.ToDecimal(row.Cells[1].Value)
* Convert.ToInt32(row.Cells[2].Value);
Can someone help me find a solution?
I am not sure if you are using forms or webapp... The folloing option is ususally aplicable to webapps, I don't know about forms.
This usually happens when the GridView columns are generated automatically, i.e. gridview.AutoGenerateColumns = true;. It does not know that there are any columns, therefore gives you anout of range exception. You would need to set it to false and tell it what columns to display. In the template field for the third column, you can simply change the binding property to a multiplicated value.
Another oprion would be to return three columns from the database, third column being your multiplied values.
Hope this helps...
if error happened on the line as you sad. Then faster solution will be to use a column names.
As #Andres mentioned it is better practice then using of indexes.
From form designer check a columns name and then use like this:
decimal product = Convert.ToDecimal(row.Cells[datagridviewTextBoxColumn1.Name].Value)
* Convert.ToInt32(row.Cells[datagridviewTextBoxColumn2.Name].Value);
Or much better will be to used custom names of columns.
Have your second datargidview a predefined columns or it created programmatically?
if they have a predefined names-> then use them
if they not -> then, because you have always same columns in second datagridview, then will be better to create columns once in designer for example
How if you change it like this
decimal sum = 0.0m;
decimal product = 0;
for (int i = 0; i < gridProizvodi.Rows.Count; i++)
{
DataGridViewRow row = gridProizvodi.Rows[i];
if (row.IsNewRow) break;
product = row.item("Price") * row.item("Amount");
'--- if your price and amount field is numeric type, you dont have to convert it
sum += product;
row.item("Total") = product;
}
If you want to do it in VB.NET then......
Dim sum As Decimal = 0D
For i As Integer = 0 To DataGridView1.Rows.Count - 1
Dim row As DataGridViewRow = DataGridView1.Rows(i)
If row.IsNewRow Then
Exit For
End If
Dim product As Decimal = Convert.ToDecimal(row.Cells("Column1").Value) * _
Convert.ToDecimal(row.Cells("Column2").Value)
'sum += product
row.Cells("Column3").Value = product
Next
Thank You!!

Displaying results in table of data in a ListBox from TextBoxes

I am doing an assignment on the population of organisms where there are three TextBoxes in my application, that would get the user's input on the "Starting number of organisms" (StartingNumOfOrganismsTextBox), "Average daily increase" (DailyIncreaseTextBox), and "Days to multiply" (NumOfDaysTextBox).
int NumOfOrganisms = 0, DailyIncrease = 0, NumOfDays = 1;
StartingNumOfOrganisms = int.Parse(StartingNumOfOrganismsTextBox.Text);
DailyIncrease = int.Parse(DailyIncreaseTextBox.Text);
NumOfDays = int.Parse(NumOfDaysTextBox.Text);
When the user inputs int numbers in those textboxes, there should be a Calculate Button, when pressed, it should automatically display the users inputs into a separate ListBox named (PopulationsListBox), as a table of data like this:
For example, if a user enters the following inputs in the TextBoxes mentioned:
StartingNumOfOrganismsTextBox: 2 DailyIncreaseTextBox: 30% NumOfDaysTextBox: 5
Pressing the calculate button, the application should display the following table of data in a ListBox control in two columns. (Day) column, and (Approximate Population) column.
Day 1, Approximate Population 2. Day 2, Approximate Population 2.6. Day 3, Approximate Population 3.38. Day 4 Approximate Population 4.394. Day 5, Approximate Population 5.7122.
Will someone give me hints on how to take all three of the user inputs, (StartingNumOfOrgranisms, DailyIncrease[%] and then the NumOfDays the organisms will be left to multiply, and display the data of table ina ListBox control? This is very confusing for me, I will be extremely grateful if anyone could help me with this assignment. Thanks.
Also, I have tried to use the ListView code format to add my data:
PopulationsListBox.Items.Add("1");
PopulationsListBox.Items[0].SubItems.Add(StartingNumOfOrganisms.ToString());
for (int i=2;i<=NumOfDays;++i)
{
PopulationsListBox.Items.Add(i.ToString());
PopulationsListBox.Items[PopulationsListBox.Items.Count-1].SubItems.Add((StartingNumOfOrganisms+StartingNumOfOrganisms*DailyIncrease).ToString());
But, "SubItems" is not a property ListBoxes use. Perhaps someone could suggest trying something similar to that for me? I will be thankful.
I haven't tested this but you want to do something like this:
listbox.Items.Add("Day 1, Approximate Population:" + txtStartingNumberOfOrganisms.Text);
int ApproximatePopulation = Convert.ToInt16(txtStartingNumberOfOrganisms.Text);
for (int i = 2; i <= numOfDays; i++)
{
ApproximatePopulation = ApproximatePopulation + ((ApproximatePopulation * Convert.ToDouble(txtDailyIncrease.text)) / 100);
listbox.Items.Add("Day " + Convert.ToString(i) + ", Approximate Population:" + Convert.ToString(ApproximatePopulation));
}
Apologies if the sums are all over the place but you can figure those out ;)

Categories