I am building a Point of Sale system on ASP.net. I have a database table called "tblProduct" and I have used Entity Framework to convert it into a class using code first approach. I created a binding list, which holds items, and have bound the ListBox datasource to the binding list. When a person selects a product, the item goes into the binding list and hence is displayed on the ListBox, everything works correctly up until now. My listbox name is "lbProductsChosen", just for reference.
private static BindingList<tblProduct> blProducts = new BindingList<tblProduct>();
protected void Page_Load(object sender, EventArgs e)
{
lbProductsChosen.DataSource = blProducts;
lbProductsChosen.DataTextField = "Description";
CreateTab();
AddProductsToTab();
ButtonResize();
}
However, while trying to make a "Delete" Button, to try and delete a selected item from the ListBox using:
protected void btnDeleteItem_Click(object sender, EventArgs e)
{
tblProduct selectedItem = (tblProduct)lbProductsChosen.SelectedItem;
blProducts.Remove(selectedItem);
}
It gives me an error and tells me that it "Cannot convert type 'System.Web.UI.WebControls.ListItem' to 'Restoraunt_POS.tblProduct'"
Edit: Here is my button click event, just for clarity. When a product button is pressed, it holds the information in its attributes properties, makes a new instance of the tblProduct class and puts it in the binding list(blProducts).
private void ProductButton_Click(object sender, EventArgs e)
{
Button b = (Button)sender;
string description = b.Attributes["data-name"];
decimal price = Convert.ToDecimal(b.Attributes["data-price"]);
int productID = Convert.ToInt32(b.Attributes["data-prodID"]);
int prodType = Convert.ToInt32(b.Attributes["data-prodType"]);
tblProduct p = new tblProduct() { Description = description , Price = price , ProductID = productID , ProductType = prodType };
blProducts.Add(p);
lbProductsChosen.Items.Clear();
lbProductsChosen.DataBind();
}
Related
I'm working on an inventory system within C# as a small personal project.
I've managed to get the basic functions working within the Form, but I'm having trouble working out how to add a button that will either Increase or decrease the products quantity by 1. The inventory is stored in a ListViewItem object.
Or by having the user enter a value into a textbox, with the product selected and it'll change the quantity of that product without affecting the rest.
The code below shows the code I have written for the user to enter a value manually into a textBox, and clicking the button (with the product selected) will update the quantity. There's no crash, it simply doesn't do anything.
private void PlusOne_Click(object sender, EventArgs e)
{
foreach (ListViewItem list in listView1.SelectedItems)
{
list.SubItems.Add(addBox.Text);
}
}
private void addBox_TextChanged(object sender, EventArgs e)
{
int addOne = int.Parse(addBox.Text);
}
This will increment all the selected items in your list view.
I'm assuming that you have one ListViewItem per product and the first SubItem stores the quantity value. Subitems are shown from the second column onwards. First column corresponds with the item itself
private void PlusOne_Click(object sender, EventArgs e)
{
const int quantityColumn = 0;
int increment = int.Parse(PlusOne.Text);
foreach (ListViewItem list in listView1.SelectedItems)
{
int qty = 0;
if (list.SubItems.Count != 0) {
qty = int.Parse(list.SubItems[quantityColumn].Text);
}
list.SubItems[quantityColumn].Text = (qty + increment).ToString();
}
}
So you can bind various fields to a ComboBox like this so that the selected value of the ComboBox will then autofill the text fields.
var SID = Convert.ToInt32(cbosSID.Text);
using (Entities2 db = new Entities2())
{
var student = (from a in db.Students where a.SID == SID select a).First();
txtsFName.Text = student.FName;
txtsLName.Text = student.LName;
txtsPhone.Text = student.Phone;
txtsAdd1.Text = student.Add1;
txtsAdd2.Text = student.Add2;
txtsState.Text = student.State;
txtsSuburb.Text = student.Suburb;
txtsPost.Text = student.Postcode;
dteDOB.Value = student.DOB;
dteStart.Value = student.SDate;
}
Can you do the same thing to a DataGridView with its individual columns?
I've added two columns to the DataGridView , Student ID and Mark. I tried to do it using editDataGridView.Columns[course.SID].DataPropertyName = "clmSID"; but that doesn't work.
private void cboeCID_SelectedIndexChanged_1(object sender, EventArgs e)
{
var CID = Convert.ToInt32(cboeCID.Text);
using (var db = new Entities2())
{
var course = (from a in db.Student_Course where a.CID == CID select a).First();
editDataGridView.Columns[course.SID].DataPropertyName = "clmSID";
editDataGridView.Columns[course.Mark].DataPropertyName = "clmMark";
};
}
Consider this tips:
To show a List<T> in DataGridView, it's enough to assign it to DataSource of grid.
When you assign List<T> to a DataGridView which had not defined columns for it, by default the grid will show all browsable properties of List<T>
To show only some of column, you can consider this solutions:
○ You can define columns using designer or code and set DataPropertyName property of the column to the property name which you want to show in column. This way only those columns will be added to DataGridView.
○ You can let the columns to be generated automatically and then remove or hide those ones that you don't want to show.
When you create context in a using block, you will loose the ability of change-tracking using your context. If you only want to show data in grid it's OK. But if you want to show data and also edit and save changes, you should not define context this way. Instead you should create a field of type of your context at form level and initialize it in Load event of form and use it for load and save data.
Here I post a sample using Category and Product to be more general.
Category: Id, Name
Product : Id, Name, CategoryId, Price, Description
Relation: Categry [1]---[*] Product
In the below code, first we define db as a filed of Form and will initialize it in Load event of form. This way, it can track changes. Also when perform data binding with a ComboBox this way:
SampleDbEntities db;
void Form1_Load(object sender, EventArgs e)
{
db = new TestDBEntities();
var categories = db.Category.ToList();
this.comboBox1.ValueMember = "Id";
this.comboBox1.DisplayMember = "Name";
this.comboBox1.DataSource = categories;
}
Then handle SelectedIndexChanged event of ComboBox and load Product entities based on selected value of ComboBox. In the below code, we only will show "Price" and "Name" columns in DataGridView:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (this.comboBox1.SelectedValue == null)
return;
var desiredColumns = new[] { "Price", "Name" };
var id = (int)this.comboBox1.SelectedValue;
var data = db.Product.Where(x => x.CategoryId == id).ToList();
dataGridView1.DataSource = data;
dataGridView1.Columns.Cast<DataGridViewColumn>()
.Where(x => !desiredColumns.Contains(x.DataPropertyName))
.ToList().ForEach(x => { x.Visible = false; });
}
To save changes, handle Click event of a button and write such code:
private void button1_Click(object sender, EventArgs e)
{
dataGridView1.EndEdit();
db.SaveChanges();
}
I'm currently working on a shopping basket application in C# at the moment.
Is there a way that when I press the add button it can update the item quantity each time that an item is added to the basket?
Thanks. This is my current code:
protected void btnAdd_Click(object sender, EventArgs e)
{
listBox1.Items.Add(textBox3.Text);
NumericUpDown1.Maximum = 100;
NumericUpDown1.Minimum = 0;
textBox5.Text = listBox1.Items.Count.ToString();
if (NumericUpDown1.Value == 0)
{
NumericUpDown1.Value = +1;
}
}
As I've added two items to the basket the quantity should change to 2 but it doesn't it just stays at 1.
Personally, I would keep a list of objects that store product name/description and value (count) using the product name as the key. Then I'd use databinding to bind the list to the listbox and let databinding do the work of displaying any updates.
The idea being that you can find the object you're interested in by searching your list, then update it's "quantity" property, leaving databinding to update the UI.
Alternatively, you could use the new class you create to add directly to the listbox, but set the ValueMember and DisplayMember properties accordingly.
public class OrderLineViewModel
{
public string Description { get; set; }
public uint Quantity { get; set; }
}
See this answer to this question for more information.
The corrected code, based on the comments:
protected void btnAdd_Click(object sender, EventArgs e) {
listBox1.Items.Add(textBox3.Text);
NumericUpDown1.Maximum = 100;
NumericUpDown1.Minimum = 0;
int previousNoItems;
Int.TryParse(textBox5.Text, out previousNoItems);
textBox5.Text += previousNoItems + NumericUpDown1.Value;
}
attempting to change text based on a combobox selection. C#, windows form, combobox loads on form load.
using an ADO entity data model to map the db, I have the tables added in. I have a combobox which loads the vendors, then a button that says get vendor. upon that I have 3 labels I want to display the vendor name, city and zip. I'm just having trouble figuring out how to make the label binded to the selected item from the combobox (the vendor selected) and make it change.
quick edit: I know the button code is wrong. but its where i'm at so I posted it. Thanks!
PayablesEntities payablesSet = new PayablesEntities();
private void Form1_Load(object sender, EventArgs e)
{
comboBoxVendor.DataSource = payablesSet.Vendors.ToList();
comboBoxVendor.DisplayMember = "Name";
comboBoxVendor.ValueMember = "VendorID";
}
private void buttonGetVendor_Click(object sender, EventArgs e)
{
label5.text = comboBoxVendor.SelectedValue;
}
Take a look at the SelectedIndexChanged & SelectionChangeCommitted events.
Figured it out! needed a query to store that selected item's info, duh!
private void buttonGetVendor_Click(object sender, EventArgs e)
{
int vendorID = (int)comboBoxVendor.SelectedValue;
var selectVendor =
(from vendor in payablesSet.Vendors
where vendor.VendorID == vendorID
select vendor).First();
label5.Text = selectVendor.Name;
label6.Text = selectVendor.City;
label7.Text = selectVendor.ZipCode;
}
i am trying to make favourites in my application and i need to show a form that have the names of the favourite in a ListBox.
When select a name and click the choose button i want to put the name and the Url in different textboxes and this is my code any ideas.
private void EditFourites_Click(object sender, EventArgs e)
{
textBox1.Text = listBox1.SelectedItem.ToString();//put the selected value from the listbox to the textbox1 and this is my problem i want to make textbox1.text takes only the key of the listbox1.text
}
private void ListBox()
{
FavoriteXml FV = new FavoriteXml();//the favouritXml class is a class where i get the information about favourites
Dictionary<string, string> Favourite = FV.GetFavouriteCombo();//GetFavouriteCombo() will get the value as dictionary
listBox1.DataSource = new BindingSource(Favourite, null);
listBox1.ValueMember = "Value";
}
private void EditSpecificFavourite_Click(object sender, EventArgs e)
{
FavoriteXml FV = new FavoriteXml();
FV.EditFavourite(textBox1.Text.ToString(),textBox2.Text.ToString());//this is the EditFavourite where i want to change the specific favourite
ListBox();
}
To get the datavalue of the selected listboxitem into your second textbox you use this code:
textBox2.Text = listBox1.SelectedValue.ToString();