I use a button on click event to add a product to my GridControl. On the event, theres a for-loop that calculates the items. My problem is when clicking the event, it adds the product to the grid, but it does not calculate the item.
I use a void method to calculate and call it with gridrowcount changed event, however, I don't want this. I want it to calculate when adding a product.
void Hesapla()
{
decimal Toplam = 0;
for (int i = 0; i < gridView1.RowCount + 1; i++)
{
Toplam += decimal.Parse(gridView1.GetRowCellValue(i, "Tpl").ToString());
}
txtToplam.Text = Toplam.ToString("0.00");
btnAdetText.Text = gridView1.RowCount.ToString() + " Ürün";
}
When I change RowCount to -1 or +1 it gives an error.
My code for adding a product:
SimpleButton urun = (SimpleButton)sender;
UrunID = Convert.ToInt16(urun.Tag);
DataRow Dr = cls.urunSec(UrunID);
Ses2();
gridView1.AddNewRow();
gridView1.SetRowCellValue(DevExpress.XtraGrid.GridControl.NewItemRowHandle, "ID", Dr["ID"].ToString());
gridView1.SetRowCellValue(DevExpress.XtraGrid.GridControl.NewItemRowHandle, "STOKADI", Dr["STOKADI"].ToString());
gridView1.SetRowCellValue(DevExpress.XtraGrid.GridControl.NewItemRowHandle, "ADET", Adet);
gridView1.SetRowCellValue(DevExpress.XtraGrid.GridControl.NewItemRowHandle, "TOPLAM", Dr["SATISFIYAT"].ToString());
private void urn_Click(object sender, EventArgs e)
{
// Hi
// ım add new product from here
SimpleButton urun = (SimpleButton)sender;
UrunID = Convert.ToInt16(urun.Tag);
DataRow Dr = cls.urunSec(UrunID);
Ses2();
gridView1.AddNewRow();
gridView1.SetRowCellValue(DevExpress.XtraGrid.GridControl.NewItemRowHandle, "ID", Dr["ID"].ToString());
gridView1.SetRowCellValue(DevExpress.XtraGrid.GridControl.NewItemRowHandle, "STOKADI", Dr["STOKADI"].ToString());
gridView1.SetRowCellValue(DevExpress.XtraGrid.GridControl.NewItemRowHandle, "MIKTAR", Adet);
gridView1.SetRowCellValue(DevExpress.XtraGrid.GridControl.NewItemRowHandle, "BIRIMFIYAT", Dr["SATISFIYAT"].ToString());
Hesapla();
}
I have added , but did not
Related
I'm working on a chart in asp.net that is dinamically created from a DataTable. Basically I've got a DataTable like this:
So, what I want in my chart is a column for each differente location, and for each diferent Type I want to have a "portion" of the column, meaning I would like to have a column per location divided per type.
I have managed to do something like this, but not quite what I would like:
Now I'll try to explain my code.
First, i add the different locations in my datatable to a list of strings
string loc = "";
for (int i = 0; i < dtTipos.Rows.Count; i++)
{
if (loc != dtTipos.Rows[i]["Location"].ToString())
listaLocais.Add(dtTipos.Rows[i]["Location"].ToString());
loc = dtTipos.Rows[i]["Location"].ToString();
}
After, for each different location, I select the rows to the corresponding location and create a series for each one of them. I proceed to create a point with y=0 and one with y=total
for (int i = 0; i < listaLocais.Count; i++)
{
DataRow[] lRow = dtTipos.Select("Location = '" + listaLocais[i] + "'");
foreach (DataRow dr in lRow)
{
string serie = dr["Location"].ToString().Substring(0, 2) + "_" + dr["Type"].ToString() + " - " + dr["Total"].ToString();
Series s = new Series();
s.Name = serie;
s.Label = dr["Location"].ToString();
s.ChartType = SeriesChartType.StackedColumn;
chartTipo1.Series.Add(s);
s.Points.AddXY(i + 1, 0);
s.Points[0].Label = " ";
s.Points.AddXY(i + 1,Convert.ToInt32(dr["Total"].ToString()));
s.Points[1].Label = " ";// dtTipos.Rows[i]["Total"].ToString();
}
}
The thing is: I think that because I create a serie for each row, everytime I use a diferent column, the y axis starts from where I left it.
Is there any way so I can get this to work?
I'll appreciate any help.
You're adding your series and data points in the same loop. First add your series, then your data points:
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new MyDataTable();
//first add your series
foreach (DataRow row in dt.DefaultView.ToTable(true, new string[] { "Type" }).Rows)
{
Series series = new Series();
series.Name = (string)row["Type"];
series.ChartType = SeriesChartType.StackedColumn;
Chart1.Series.Add(series);
}
// then add your points;
foreach (DataRow row in dt.Rows)
Chart1.Series[(string)row["Type"]].Points.AddXY(row["Location"], new object[] { row["Total"] });
}
}
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();
I just want to ask how I can update or change the cell value of column 'quantity' in my DataGridView when I select a certain row.
I have 3 columns in my DataGridView which are Item Name, Quantity and Price.
Every time I click the button 'add' or 'less' on my form, the quantity of the selected row item will either add to or subtract 1 from the quantity column and the price will also update every time the quantity increments or decrements. Here is my code when I add my item to my DataGridView.
I'm not really sure if I got it right to add items to my datagrid.
cmd = new MySqlCommand("SELECT * FROM tblmenu", dbConn);
MySqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Button btn = new Button();
btn.Text = rdr["menuName"].ToString();
btn.Width = 126;
btn.Height = 80;
btn.Click += delegate
{
MySqlConnection cnn2 = new MySqlConnection(sqlConn.connString);
cnn2.Open();
cmd = new MySqlCommand("SELECT menuName, menuPrice FROM tblmenu WHERE menuName = #name", cnn2);
cmd.Parameters.AddWithValue("#name", btn.Text);
MySqlDataReader rdr2 = cmd.ExecuteReader();
while (rdr2.Read())
{
dataGridView1.Rows.Add(rdr2.GetString("menuName").ToUpper(), 1, rdr2.GetDouble("menuPrice"));
}
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
lblQty.Text = dataGridView1.RowCount.ToString();
};
}
I have tried this but when I click another set of item, the quantity from the previous selected item still increments.
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
Add.Click += delegate
{
dataGridView1.Rows[e.RowIndex].Cells["quantity"].Value = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells["quantity"].Value) + 1;
};
Minus.Click += delegate
{
dataGridView1.Rows[e.RowIndex].Cells["quantity"].Value = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells["quantity"].Value) - 1;
};
}
I suggest you consider binding your DataGridView to a data source. You should not perform data operations on the UI if you can avoid it.
To demonstrate this,
private void quantityChangeClick(object sender, EventArgs e)
{
addToQuantity((Button)sender == this.Add ? 1 : -1);
updateTotal();
}
private void addToQuantity(int howMuch)
{
var selectedRowIndices = dataGridView1.SelectedRows.OfType<DataGridViewRow>().Select(ro => ro.Index);
this.rows.Where((r, i) => selectedRowIndices.Contains(i)).ToList().ForEach(
r => r.Quantity = Math.Max(0, r.Quantity + howMuch));
this.dataGridView1.Refresh();
}
// calculate the total from the data source as well
private void updateTotal()
{
var total = Math.Round(this.rows.Sum(r => r.Quantity * r.Price), 2, MidpointRounding.AwayFromZero);
this.TotalLabel.Text = string.Format("₱{0:0.00}", total);
}
I have used some dummy data to demo this on my end, that is the Row class. Actually, you could do a similar thing, and add a Row to the data source rows with each record from your database.
private class Row
{
public string ItemName { get; set; }
public int Quantity { get; set; }
public double Price { get; set; }
public Row(string i, int q, double p)
{
this.ItemName = i;
this.Quantity = q;
this.Price = p;
}
}
private List<Row> rows = new List<Row>();
private void Form1_Load(object sender, EventArgs e)
{
// instead, here you will add your rows from SQL
rows.AddRange(new Row[]
{
new Row("item1", 0, 500),
new Row("item2", 0, 400),
new Row("item3", 0, 850)
});
this.dataGridView1.DataSource = rows;
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
Add.Click += quantityChangeClick;
Minus.Click += quantityChangeClick;
}
First of all, using dataGridView1_CellContentClick does not serve the purpose at all. You intend to increase or decrease quantity on Add or Minus button click. I would use dataGridView1.CurrentRow property to get hold of CurrentRow and manipulate quantity column.For updating price column, you should have a Rate column or a constant Rate value to multiply it with quantity. Do you have it? If not then I don't see how you arrive on price calculation. However assuming you have one :
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;
//assuming you have rate column...
var rate = Convert.ToDouble(row.Cells["Rate"].Value);
row.Cells["Price"].Value = quantity * rate;
}
Now bind Click event of your Add & Minus Buttons to the method above in Form constructor.
public myForm(){
InitializeComponents();
Add.Click+=quantity_change;
Minus.Click+=quantity_change;
}
You can also use form's Load event if you want.
I have DataGridView in that one combobox the combobox values are loaded from one table after selecting combobox value i want to update other columns with respective data but this is working only for one row i want update all row.. please give any suggestion for code change.
private void dataGridView2_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView2.IsCurrentCellDirty)
{
for (int i = 0; i < (dataGridView2.Rows.Count)-1; i++)
{
try
{
if (dataGridView2.Rows[i].Cells[1].Value.ToString() != "")
{
ConnectionDB gridRdata = new ConnectionDB("SELECT * FROM Ready_Made_Master WHERE RM_Name='" + dataGridView2.Rows[i].Cells[1].Value.ToString() + "';");
DataTable redydata = gridRdata.returntable();
dataGridView2.Rows[i].Cells[2].Value = redydata.Rows[i][2].ToString();
}
}
catch
{
}
}
}
}
After the for loop,try rebinding the gridview ie
for (int i = 0; i < (dataGridView2.Rows.Count)-1; i++)
{
}
ConnectionDB gridRdata = new ConnectionDB("SELECT * FROM Ready_Made_Master");
DataTable redydata = gridRdata.returntable();
gridRdata .Datasource=redydata ;
gridRdata .Databind();
Please make the necessary chnges in Select Statement.
I have a "time duration" column in a grid view, and I wish to sum that particular column in C# and publish the total time taken at a label named Total Time. How can I do this?
Sample code:
int sum = 0;
for (int i = 0; i < dgTestSteps.SelectedColumns.Count; ++i)
{
sum += Convert.ToInt32(dgTestSteps.SelectedColumns.Count.ToString());
//sum += Convert.ToInt32(dgTestSteps.Rows[i].Cells[1].Value);
}
lblTotalTime.Text = sum.ToString();
int sum = 0;
for (int i = 0; i < dgTestSteps.Rows.Count; ++i)
{
sum += Int.Parse(dgTestSteps.Rows[i].Cells[1].Value.ToString());
}
lblTotalTime.Text = sum.To String();
It seems true! Is there any problem with this?
I do this by aggregating the column row values in a class variable thusly:
Code behind:
protected void ItemsGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Get the row variable values
var rowView = (DataRowView)e.Row.DataItem;
var itemId = Convert.ToInt32(rowView["ItemID"]);
var skuId = Convert.ToInt32(rowView["ItemSkuID"]);
var quantity = Convert.ToInt32(rowView["Quantity"]);
// Instantiate instances of the relevant classes
var item = new Item(itemId);
var sku = new Sku(skuId);
var itemPrice = String.Format("{0:n2}", (item.Price + sku.PriceAdj));
var itemPriceLiteral = (Literal)e.Row.FindControl("ItemPrice");
if (itemPriceLiteral != null)
{
itemPriceLiteral.Text = itemPrice;
}
var itemExtendedPriceLiteral = (Literal)e.Row.FindControl("ItemExtendedPrice");
if (itemExtendedPriceLiteral != null)
{
var extendedPrice = price * quantity;
itemExtendedPriceLiteral.Text = String.Format("{0:n2}", extendedPrice);
// Increment the extended price
_totalExtendedPrice += extendedPrice;
}
}
}
// Lots of stuff omitted from this method for clarity
public void GetSummary()
{
// Set the text property of the total literal below the GridView
OrderTotal.Text = string.Format((HttpUtility.HtmlDecode(
(string)GetGlobalResourceObject("ShopStrings", "UsdPrice"))),
_totalExtendedPrice);
}
OrderTotal.Text is localized but you can easily format it without using resources.
You can use this but you should know that number of columns start with 0 and goes up with 1
int sum = 0;
for (int i = 0; i < dgTestSteps.Rows.Count; ++i)
{
sum += Convert.ToInt32(dgTestSteps.Rows[i].Cells[0].Value);
}
lblTotalTime.Text = sum.ToString();
I tried this and has no problem