I Have a DataGridView, with columns Item, description, quantity, rate & total.
I have two types of items, one item have vapasi == yes (vapasi is a kind of deposite amount), & another item have vapasi == No.I want to calculate the sum of 'total' column by differentiating items with vapasi & items without vapasi, & want to display this calculated total into two respective textboxes that is 'txtboxwithvapasi', n 'txtboxwithoutvapasi' which are there after the grid.I did following code :
private void grdPurchase_CellEndEdit_1(object sender, DataGridViewCellEventArgs e)
{
try
{
try
{
string value = grdPurchase.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
if (e.ColumnIndex == 2)
{
int val = int.Parse(value);
quantity = val;
}
if (e.ColumnIndex == 4)
{
float val = float.Parse(value);
total = val;
if (vapasi1 == "Yes")
{
vtot += total; //vtot=0+10
txt_forvapasitotal.Text = vtot.ToString(); //10
float vapsitot =float.Parse(txt_forvapasitotal.Text);
float vapsicalculate = (vapsitot * a);
float tax = vapsicalculate / 100;
float with_vapasi = vtot + tax;
txt_withvapasi.Text =Convert.ToString(with_vapasi);
}
else
{
nvtot = 0;
for (int i = 0; i < grdPurchase.Rows.Count; i++)
{
if (vapasi1 == "No")
{
if (grdPurchase.Rows[e.RowIndex].Cells[3].Selected == true)
{
nvtot += float.Parse(grdPurchase[4, i].EditedFormattedValue.ToString());
txt_withoutvapasitot.Text = nvtot.ToString();
}
}
}
}
txt_vapasiincludedtot.Text =(float.Parse(txt_withvapasi.Text) +float.Parse(txt_withoutvapasitot.Text)).ToString();
}
if (e.ColumnIndex == 1)
{
int val = int.Parse(value);
materialid = val;
string vapasi = "Select material_vapasi from tbl_material_master where active_flag=1 AND material_id =" + materialid + "";
SqlCommand cmd = new SqlCommand(vapasi, con);
sdr = cmd.ExecuteReader();
if (sdr.HasRows)
{
while (sdr.Read())
{
vapasi1 = sdr["material_vapasi"].ToString();
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
grdPurchase.Columns[3].ReadOnly = false;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
Problem is:-when I am selecting item with vapasi in first row & in second row item without vapasi , its working properly.But if i Select any item at third row ,then its doing sum of all the three items in 'txtboxwithoutvapasi' without differentiating items.
You need to keep track of vapasi being "Yes" or "No" for each row in the grid, but you are using a single variable. Can't you add this column to the grid (as a hidden column if you don't want to show this to the user)? Then whenever you need to calculate the totals you simply iterate through the grid rows and check the vapasi column in stead of the vapasi1 variable.
Related
When search button is pressed, im trying to count how many results have the same 'username' and then sum their 'earned' (earned is a decimal)
private void button5_Click(object sender, EventArgs e)
{
string searchValue = textBox5.Text;
int rowIndex = 1;
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
try
{
bool valueResult = true;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.Cells[1].Value.ToString().Equals(searchValue))
{
rowIndex = row.Index;
dataGridView1.Rows[1].Selected = true;
rowIndex++;
valueResult = false;
var count = this.dataGridView1.Rows.Cast<DataGridViewRow>()
.Count(roww => row.Cells[1].Value.ToString() == searchValue);
this.textBox6.Text = count.ToString();
}
}
if (valueResult != false)
{
MessageBox.Show("Record is not avalable for this Name: " + textBox5.Text, "Not Found");
return;
}
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
}
1) But for some reason textbox6would display the last number in 'id' column regardless of username searched
2) Also, I cant figure out how to sum the every cell in 'earned' for that specific user searched
[Example of datagridview from MySql]1
Im still a beginner in c#
Since you're already iterating through the rows with the foreach there's no need to recalculate the count of matches each time within the foreach. Instead you can increment a counter and add to an earned total for all of the rows that match.
The reason why textbox6 seemed to have the value of the last row's "id" column (which was actually a count of all of the rows in the grid) is because of the Count condition:
.Count(roww => row.Cells[1].Value.ToString() == searchValue)
which should be:
.Count(roww => roww.Cells[1].Value.ToString() == searchValue)
With it as roww => row and being within the if condition it would return the count of all rows not just the matched rows. But again, having the .Count is unnecessary.
Here's a modified version that iterates through the rows and increments a counter and adds to the earned total for the rows that match the selection criteria:
private void button5_Click(object sender, EventArgs e)
{
string searchValue = textBox5.Text;
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
try
{
decimal earnedTotal = 0;
int matches = 0;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if(!row.IsNewRow)
{
if((string)row.Cells[1].Value == searchValue)
{
row.Selected = true;
decimal earned;
if (decimal.TryParse((string)row.Cells[2].Value, out earned))
earnedTotal += earned;
matches++;
}
else
{
row.Selected = false;
}
}
}
if(matches == 0)
MessageBox.Show("Record is not avalable for this Name: " + textBox5.Text, "Not Found");
textBox6.Text = matches.ToString();
txtEarnedTotal.Text = earnedTotal.ToString();
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
}
So I'm creating a project, which is a Point of Sale, like those in fast food chains.
The buttons on my POS is created dynamically, depends on the values from my database, and now I'm having a hard time to compute the subtotal when I change the quantity of each item. I used DataGrid to list all the products ordered by the customer.
I created two buttons which is add and minus that can set the quantity of the selected row in the datagridview, I'm not sure if I got it right but the code is also provided below which computes the price of the selected item multiplied to the quantity.
My problem is, how can I compute the subtotal price, and the total quantity of items in my datagridview everytime I add items in my datagrid or I add or subtract in the quantity of the item.? The subtotal should reflect immediately EVERYTIME I add an item, or add or subtract an item.
Provided is a sample image to understand better what I want to happen in my project.
public void quantity_change(object sender, EventArgs e)
{
var row = dataGridView1.CurrentRow;
if (row == null || row.Index < 0)
return;
var unit = (sender == add) ? 1 : -1;
var quantity = Convert.ToInt32(row.Cells["Quantity"].Value) + unit;
row.Cells["Quantity"].Value = quantity;
var rate = Convert.ToDouble(row.Cells["SellingPrice"].Value);
row.Cells["TotalPrice"].Value = quantity * rate;
}
private void frmPOS_Load(object sender, EventArgs e)
{
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
add.Click += quantity_change;
minus.Click += quantity_change;
cmd = new MySqlCommand("SELECT * FROM tblmenu", dbConn);
MySqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Button btn = new Button();
btn.Text = rdr["menuName"].ToString();
btn.Name = rdr["menuID"].ToString();
btn.Width = 126;
btn.Height = 80;
btn.Click += delegate
{
dataGridView1.ClearSelection();
MySqlConnection cnn2 = new MySqlConnection(sqlConn.connString);
cnn2.Open();
cmd = new MySqlCommand("SELECT menuName, menuPrice FROM tblmenu WHERE menuID = #id", cnn2);
cmd.Parameters.AddWithValue("#id", btn.Name);
MySqlDataReader rdr2 = cmd.ExecuteReader();
while (rdr2.Read())
{
//I added the item in my datagridview, with the button name, 1 = 1quantity, and Selling Price
dataGridView1.Rows.Add(rdr2.GetString("menuName").ToUpper(), 1, rdr2.GetDouble("menuPrice"));
}
//I copied the value of Selling Price Column to the Total Price Column in this part
foreach (DataGridViewRow row in dataGridView1.Rows)
{
value = row.Cells["SellingPrice"].Value.ToString();
row.Cells["TotalPrice"].Value = value;
}
};
if (rdr["menuAvailability"].ToString() == "yes")
{
if (rdr["menuCategory"].ToString() == "Sandwiches")
{
flpSandwiches.Controls.Add(btn);
}
else if (rdr["menuCategory"].ToString() == "Appetizers")
{
flpAppetizers.Controls.Add(btn);
}
}
}
rdr.Close();
}
What I can see in your quantity_change method:
row.Cells["TotalPrice"].Value = quantity * rate;
for me it is subtotal for given product.
You you wan't to calculate total price of whole order (all products in data grid) you need to sum all subtotals for all products.
For example, at the end of quantity_Change:
double Total=0;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
Total+=row.Cells["TotalPrice"].Value;
}
// now you can set this value for example label under data grid
labelTotal.Text = Total.ToString();
This is all of the code i have done so far. The system has a listview that has a column header:
subject name | 1st | 2nd | 3rd | 4th | Final Grades
If the column 1st to 4th contains value it will compute for the final grade of the student. sum(1st to 4th) / 4 *50 + 50. if one of the column does not have a value then the user will be prompted and no final grades will be computed.
I am confused on how do i get all the listview value from 1st to 4th then automatically computes the final grade.
PLease help
private void button1_Click(object sender, EventArgs e)
{
flag = false;
if (txt_numValue.Text != "")
{
char[] entereddata = txt_numValue.Text.ToCharArray();
foreach (char aChar in entereddata.AsEnumerable())
{
if (!Char.IsDigit(aChar))
{
MessageBox.Show("Please enter only numbers.", "In the field Numeric Value");
flag = true;
break;
}
}
}
else if (txt_numValue.Text == "")
{
MessageBox.Show("Please do not leave the field, 'Numeric Value', blank.", "Attention!");
flag = true;
}
if (flag == false)
{
string period = txt_gradingPeriod.Text;
string numeric = txt_numValue.Text;
int cell = 0;
if (period == "1st") { cell = 1; }
else if (period == "2nd") { cell = 2; }
else if (period == "3rd") { cell = 3; }
else if (period == "4th") { cell = 4; }
foreach (ColumnHeader header in listView1.Columns)
{
if (header.Text == period)
{
listView1.Items[0].SubItems[cell].Text = numeric;
break;
}
}
}
}
Once you have got all the data in your list view you can do something like this,
int sum = 0;
foreach (ListViewItem v in listView1.Items)
{
bool hasBlank = false;
for (int i = 0; i < v.SubItems.Count;i++ )
{
if (v.SubItems[i].Text == null || v.SubItems[i].Text == string.Empty)
{
//code
hasBlank = true;
break;
}
else
{
sum += Convert.ToInt16(v.SubItems[i].Text);
}
}
if (!hasBlank)
{
string grade="something";
//formula to calculate grade based on sum.set the result to string grade
v.SubItems[4].Text = grade;
}
else
{
v.SubItems[4].Text = "has blank";
}
sum = 0;
}
This will fill grade if all values are present else a message that it has a blank value.
I have a datagrid view which is editable. I'm getting the value of a cell and then calculate the value of another cell. To do this I have handled CellEndEdit and CellBeginEdit events.
quantity = 0, quantity1 = 0, quantity_wt1 = 0, quantity_wt = 0, ekundag = 0;
private void grdCaret_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
try
{
string value = grdCaret.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
if (e.ColumnIndex == 1)
{
int val = int.Parse(value);
quantity = val;
ekundag = ekundag + quantity;
tbTotDag_cr.Text = ekundag.ToString();
}
if (e.ColumnIndex == 2)
{
float val = float.Parse(value);
total = val;
ekunrakam = ekunrakam + total;
tbTotPrice_cr.Text = ekunrakam.ToString();
}
grdCaret.Columns[3].ReadOnly = false;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
private void grdCaret_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
rate = 0;
quantity1 = quantity;
total1 = total;
rate = (total1 / quantity1);
if (e.ColumnIndex == 3)
{
grdCaret.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = rate.ToString();
grdCaret.Rows[e.RowIndex].Cells[e.ColumnIndex].ReadOnly = true;
// quantity = 0;
// total = 0;
}
}
In the grid I have columns as quantity, total and rate. I get the above error here:
if (e.ColumnIndex == 1)
{
int val = int.Parse(value);
quantity = val;
ekundag = ekundag + quantity;
tbTotDag_cr.Text = ekundag.ToString();
}
When I enter quantity and click on the total column in gridview. Please help me fix this
AFAIK the int.Parse() function can possibly cause this kind of exceptions.
Have you tried to check the value in the cell? Isn't it possible, that some other characters are in the cell, not only the numbers? White spaces for example.
The value you have entered into your Cell can't be parsed as Integer, so it will fail #
int val = int.Parse(value);
Your input string 'value' is not in a valid format to be parsed to an integer. Take a look at this: http://www.codeproject.com/Articles/32885/Difference-Between-Int32-Parse-Convert-ToInt32-and
try using Text instead of ToString()
string value = grdCaret.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.Text;
in place of
string value = grdCaret.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
int rowsCount = 0;
//This checks to see that both textbox for items and subitems do not gain focus at the same time
if (textBoxSubItems.Text != string.Empty)
txtItems.Enabled = false;
else
txtItems.Enabled = true;
if (comboBoxItems.SelectedItem != null)
{
int idx = dataGridViewTimesheet.Rows.Add();
DataGridViewRow row = dataGridViewTimesheet.Rows[idx];
row.Cells["items"].Value = comboBoxItems.SelectedItem.ToString() + "-" + textBoxSubItems.Text;
row.Cells["fromTime"].Value = DateTime.Now.ToLongTimeString();
row.Cells["toTime"].Value = null;
row.Cells["duration"].Value = null;
row.Cells["subTotal"].Value = null;
// row.Cells["comments"].Value = "1";
}
else
MessageBox.Show("Please select an item");
string strGetColumnValue;
if (dataGridViewTimesheet.Rows.Count != 0)
rowsCount = dataGridViewTimesheet.Rows.Count;
else
MessageBox.Show("No row in the datagridview");
while (dataGridViewTimesheet.Rows.Count > 0)
{
try
{
if (dataGridViewTimesheet.CurrentRow != null)
for (int counter = 0; counter < dataGridViewTimesheet.Columns.Count; counter++)
{
if (dataGridViewTimesheet.Columns[counter].Index == 3)
{
strGetColumnValue = dataGridViewTimesheet.Rows[rowsCount].Cells[counter].Value.ToString();
dataGridViewTimesheet.Rows[rowsCount - 1].Cells[3].Value = strGetColumnValue;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Please i have 6 columns in a datagridview, the rows are added dynamically. What i want is when rows are more than one in the datagridview it should assign the value of the second column on the current(the last row created) row to the third column of the previous row. How do I achieve this.
Try this kind of thing
int count =1;
foreach (DataGridRow row in dataGridViewTimesheet.Rows)
{
if (count % 2 == 0)
{
string secondColumn = dataGridViewTimesheet.Rows[count -1].Cells[1].ToString();
dataGridViewTimesheet.Rows[count].Cells[2].Value = secondColumn;
}
count++;
}