I'm working on a school project with C# Winforms where I have to create a vehicle sales invoice and ope a new form with information about the vehicle that was selected from a combobox. How do I get the Vehicle object or its properties based on the SelectedItem in the combobox?
The Vehicle objects are in a list which is bound to a BindingSource which is bound to the combobox.
I was able to pass static strings through to a new form in another component of this assignment, but I can't figure out how to retrieve the object information.
My list of vehicles bound to the combobox. DataRetriever is a class we were given to provide us with the Vehicle objects. They have auto-implemented properties (make, model, id, colour, etc.)
List<Vehicle> vehicles = DataRetriever.GetVehicles();
BindingSource vehiclesBindingSource = new BindingSource();
vehiclesBindingSource.DataSource = vehicles;
this.cboVehicle.DataSource = vehiclesBindingSource;
this.cboVehicle.DisplayMember = "stockID";
this.cboVehicle.ValueMember = "basePrice";
I want to be able to pass information to this form and display information about the selected vehicle with labels.
private void vehicleInformationToolStripMenuItem_Click(object sender, EventArgs e)
{
VehicleInformation vehicleInformation = new VehicleInformation();
vehicleInformation.Show();
}
On Form_Load
List<VecDetails> lstMasterDetails = new List<VecDetails>();
private void frmBarcode_Load(object sender, EventArgs e)
{
VechicleDetails();
BindingSource vehiclesBindingSource = new BindingSource();
vehiclesBindingSource.DataSource = lstMasterDetails;
this.comboBox1.DataSource = vehiclesBindingSource;
this.comboBox1.DisplayMember = "stockID";
this.comboBox1.ValueMember = "basePrice";
}
In VechicleDetails() Method i'm just generating the sample value so i can i them to ComboBox
private void VechicleDetails()
{
//Sample Method to Generate Some value and
//load it to List<VecDetails> and then to ComboBox
for (int n = 0; n < 10; n++)
{
VecDetails ve = new VecDetails();
ve.stockID = "Stock ID " + (n + 1).ToString();
ve.basePrice = "Base Price " + (n + 1).ToString();
lstMasterDetails.Add(ve);
}
}
Now on comboBox1_SelectedIndexChanged event i'm getting the value of the item selected
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
string strStockId = comboBox1.Text.ToString();
string strBasePrice = (comboBox1.SelectedItem as dynamic).basePrice;
label1.Text = strStockId + " - " + strBasePrice;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Related
I have a form that contains two combobox (cmbSection,cmbGrade) and two textbox(txtName,txtSectionSize)
i want to get text from combobox and txtSectionSize and put it in txtName so my code lock like this
public partial class FRM_Item : Form
{
//public string State = "Add";
BL.CLS_Item prd = new BL.CLS_Item();
public FRM_Item()
{
InitializeComponent();
cmbSection.DataSource = prd.Get_All_Items();
cmbSection.DisplayMember = "Name_SectionType";
cmbSection.ValueMember = "ID_SectionType";
cmbGrade.DataSource = prd.Get_All_Grade();
cmbGrade.DisplayMember = "Name_Grade";
cmbGrade.ValueMember = "ID_Grade";
}
private void cmbSection_SelectedIndexChanged(object sender, EventArgs e)
{
this.txtName.Text = cmbSection.Text + txtSectionSize.Text + "-" + cmbGrade.Text;
}
private void cmbGrade_SelectedIndexChanged(object sender, EventArgs e)
{
this.txtName.Text = cmbSection.Text + txtSectionSize.Text + "-" + cmbGrade.Text;
}
private void txtSectionSize_TextChanged(object sender, EventArgs e)
{
this.txtName.Text = cmbSection.Text + txtSectionSize.Text + "-" + cmbGrade.Text;
}
when i open the form i get System.Data.DataRowView in txtName but when i pick up any text from combobox i get the right value in textbox
i solve this problem by moving this code to form load
private void FRM_Item_Load(object sender, EventArgs e)
{
cmbSection.DataSource = prd.Get_All_Items();
cmbSection.DisplayMember = "Name_SectionType";
cmbSection.ValueMember = "ID_SectionType";
cmbGrade.DataSource = prd.Get_All_Grade();
cmbGrade.DisplayMember = "Name_Grade";
cmbGrade.ValueMember = "ID_Grade";
}
the problem that i have now when i open this form from button in another form
the combobox always shwo the first value not the value from datagrid
private void btnEdit_Click(object sender, EventArgs e)
{
FRM_Item frm = new FRM_Item();
frm.txtName.Text = this.dataGridView1.CurrentRow.Cells[1].Value.ToString();
frm.cmbSection.Text = this.dataGridView1.CurrentRow.Cells[2].Value.ToString();
frm.txtSectionSize.Text = this.dataGridView1.CurrentRow.Cells[3].Value.ToString();
frm.cmbGrade.Text = this.dataGridView1.CurrentRow.Cells[4].Value.ToString();
frm.ShowDialog();
}
how i can solve this problem
Populate the comboboxes before you assign them. Right now, its backwards.
I recommend moving this code to the child form constructor, or to a method that can be called before you try to assign properties in the parent form.
cmbSection.DataSource = prd.Get_All_Items();
cmbSection.DisplayMember = "Name_SectionType";
cmbSection.ValueMember = "ID_SectionType";
cmbGrade.DataSource = prd.Get_All_Grade();
cmbGrade.DisplayMember = "Name_Grade";
cmbGrade.ValueMember = "ID_Grade";
As far as the events if you put the code in the constructor, you could have a boolean property to not run the event code if you are not finished with the constructor OR have not have the events in the designer and do it explicitly in the constructor AFTER you populate the comboboxes.
I'm trying to add a second BindingList to a ListBox but can't figure out how. Here is my code.
private Entitycontext context = new Entitycontext();
private BindingList<TblProduct> products = new BindingList<TblProduct>();
private BindingList <TblProductItem> SubProduct = new BindingList <TblProductItem>();
public form1()
{
InitializeComponent();
// here in listbox i want to add the second BindingList but I don't Know how??
// Could some One help me with this please..
ListBox.DataSource = Products;
}
/// here the listbox is format as FormaLIstItem
private void FormaLIstItem(object sender, ListControlConvertEventArgs e)
{
string currentDescription = ((TblProduct)e.ListItem).Description.PadRight(25);
string currentPrice = string.Format("{0:C}"((TblProduct)e.ListItem).Price).PadRight(25);
e.Value = currentDescription + currentPrice;
string currentDescriptions = ((TblProductItem)e.Value).Description.PadRight(25);
string currentPrices = string.Format("{0:C}",((TblProductItem)e.Value).Price).PadRight(25);
e.Value = currentDescriptions + currentPrices;
}
I have dynamic drop down lists that are created based on what's selected in the list box.. When clicking confirm this is when the drop down lists are created. Clicking save is where I attempt to retrieve the values. However I am unable to retrieve that values that are in the drop down lists.
Code:
protected void btnConfirm_Click(object sender, EventArgs e)
{
int ID = 0;
foreach (string value in values)
{
MyStaticValues.alEdit.Add(value);
CreateEditForm(value, ID);
ID += 1;
}
if (values.count != 0)
{
btnSave.Visible = true;
btnConfirm.Enabled = false;
}
}//End of btnConfirm_Click
protected void CreateEditForm(string Value, int ID)
{//Creates an edit form for the value inserted.
string name = value;
//This part adds a header
phEditInventory.Controls.Add(new LiteralControl("<h2>" + name + "</h2>"));
phEditInventory.Controls.Add(new LiteralControl("<div class=\"clearfix\"></div>"));
//Create a label
Label lblName = new Label();
lblName.Text = "Name";
lblName.ID = "lblName" + ID;
lblName.CssClass = "control-label";
//Create a Drop Down List
DropDownList ddlName = new DropDownList();
ddlName.ID = "ddlName" + ID;
ddlName.CssClass = "form-control";
//Set default N/A Values For Drop Down List
ddlName.Items.Add(new ListItem("N/A", Convert.ToString("0")));
//The Rest of the Values are populated with the database
//Adds the controls to the placeholder
phEditInventory.Controls.Add(lblName);
phEditInventory.Controls.Add(ddlName);
phEditInventory.Controls.Add(new LiteralControl("<div class=\"clearfix\"></div>"));
} //End of CreateEditForm
protected void btnSave_Click(object sender, EventArgs e)
{
string name = "";
try
{
for (int i = 0; i < MyStaticValues.alEdit.Count; i++)
{
string nameID = "ddlName" + i.ToString();
DropDownList ddlName = (DropDownList)phEditInventory.FindControl(nameID);
name = ddlName.SelectedValue.ToString();
}
}
catch (Exception ex)
{
}
phEditInventory.Visible = false;
btnSave.Visible = false;
MyStaticValues.alEdit.Clear();
}//End of btnSave_Click Function
Your problem is that the dynamically created dropdown lists are not maintained on postback. When you click the Save button, a postback occurs, and the page is re-rendered without the dynamically created dropdowns. This link may help.
Maintain the state of dynamically added user control on postback?
Working on a project for school that has 2 forms. I want to add items to the listbox in the Display form when I click the show data button. It's showing the form but the form is blank. I think this is because the form object is being created 2x once when I click the add button and another when I click the show data button. How can I create a new object of the display form that can be used in any method in my main form?
Sorry there is a few things in here that I am still working on that were just ideas. I am a beginner so please keep the help in simple terms if at all possible. Thanks :)
private void addEmployee(Employee newEmployee)
{
//Get data from textboxes and use set methods in employee class
newEmployee.Name = EmployeeNameTextBox.Text;
newEmployee.BirthDate = EmployeeBirthDateTextBox.Text;
newEmployee.Dept = EmployeeDeptTextBox.Text;
newEmployee.HireDate = EmployeeHireDateTextBox.Text;
newEmployee.Salary = EmployeeSalaryTextBox.Text;
}
private void AddButton_Click(object sender, EventArgs e)
{
//New list for employee class objects - employeelist
List<Employee> employeeList = new List<Employee>();
//Create new instance of Employee class - newEmployee
Employee newEmployee = new Employee();
bool errorCheck = false;
CheckForms(ref errorCheck);
if (!errorCheck)
{
//Gather input from text boxes and pass newEmployee object
addEmployee(newEmployee);
//Add object to employeeList
employeeList.Add(newEmployee);
Display myDisplay = new Display();
myDisplay.OutputListBox.Items.Add(" Bob");
//" " + newEmployee.BirthDate + " " +
//newEmployee.Dept + " " + newEmployee.HireDate + " " + newEmployee.Salary);
You are creating two separate instances of mydisplay.Create a single instance when the Form Loads and refer to that when you call ShowDataButton_Click
namespace WK4
{
public partial class MainForm : Form
{
Display myDisplay;
public MainForm()
{
InitializeComponent();
}
//Method to clear form input boxes
private void ClearForm()
{
EmployeeNameTextBox.Text = "";
EmployeeBirthDateTextBox.Text = "";
EmployeeDeptTextBox.Text = "";
EmployeeHireDateTextBox.Text = "";
EmployeeSalaryTextBox.Text = "";
FooterLabel.Text = "";
}
//Method to check for blank input on textboxes
private void CheckForms(ref bool error)
{
if (EmployeeNameTextBox.Text == "" || EmployeeBirthDateTextBox.Text == "")
{
MessageBox.Show("Please do not leave any fields blank");
error = true;
}
else if (EmployeeDeptTextBox.Text == "" || EmployeeHireDateTextBox.Text == "")
{
MessageBox.Show("Please do not leave any fields blank");
error = true;
}
else if (EmployeeSalaryTextBox.Text == "")
{
MessageBox.Show("Please do not leave any fields blank");
error = true;
}
else
error = false;
}
private void addEmployee(Employee newEmployee)
{
//Get data from textboxes and use set methods in employee class
newEmployee.Name = EmployeeNameTextBox.Text;
newEmployee.BirthDate = EmployeeBirthDateTextBox.Text;
newEmployee.Dept = EmployeeDeptTextBox.Text;
newEmployee.HireDate = EmployeeHireDateTextBox.Text;
newEmployee.Salary = EmployeeSalaryTextBox.Text;
}
private void AddButton_Click(object sender, EventArgs e)
{
//New list for employee class objects - employeelist
List<Employee> employeeList = new List<Employee>();
//Create new instance of Employee class - newEmployee
Employee newEmployee = new Employee();
bool errorCheck = false;
CheckForms(ref errorCheck);
if (!errorCheck)
{
//Gather input from text boxes and pass newEmployee object
addEmployee(newEmployee);
//Add object to employeeList
employeeList.Add(newEmployee);
Display myDisplay = new Display();
myDisplay.OutputListBox.Items.Add(" Bob");
//" " + newEmployee.BirthDate + " " +
//newEmployee.Dept + " " + newEmployee.HireDate + " " + newEmployee.Salary);
//Clear Form after adding data
ClearForm();
//Print footer employee saved info
FooterLabel.Text = ("Employee " + newEmployee.Name + " saved.");
}
}
//Exit the form/program
private void ExitButton_Click(object sender, EventArgs e)
{
this.Close();
}
//Method to clear the form and reset focus
private void ClearButton_Click(object sender, EventArgs e)
{
ClearForm();
EmployeeNameTextBox.Focus();
}
private void ShowDataButton_Click(object sender, EventArgs e)
{
myDisplay.ShowDialog();
}
private void MainForm_Load(object sender, EventArgs e)
{
myDisplay = new Display();
}
}
}
You are making 2 different instances of display class, in first instance you are adding data and you are displaying it using the second instance thats why you are getting a blank form
create a display class object on your MainForm_Load
private void MainForm_Load(object sender, EventArgs e)
{
Display myDisplay = new Display();
}
and the use this object (myDisplay) to add and display data in your AddButton_Click and ShowDataButton_Click methods respectively.
I have a listview with subitems. The first 5 sub items are the name, items, total price, address and telephone.
The rest of the subitems contain the past list that I displayed for my order.
It is a pizzeria program and I want it to be able to get the customers info and order.
I can get the info but can't get the rest of the order.
I'm wondering how I can display the rest of my order if that makes sense.
Example Order:
Name: Claud
Items: 3
Total: 10.99
Address: (Blank)
Telephone: (Blank)
Order: Small Pizza
-Bacon
BreadSticks
Right now my messagebox looks like this:
Name: Claud
Items: 3
Total: 10.99
Address: (Blank)
Telephone: (Blank)
Order: Small Pizza
So I just want it to display the -Bacon and BreadSticks.
Source Code:
private void CustomerInfo_Click(object sender, EventArgs e)
{
ListViewItem customers = new ListViewItem(fullName.Text);
customers.SubItems.Add(totalcount.ToString());
customers.SubItems.Add(total.ToString());
customers.SubItems.Add(Address.Text);
customers.SubItems.Add(telephone.Text);
for (int i = 0; i < OrderlistBox.Items.Count; i++)
{
customers.SubItems.Add(OrderlistBox.Items[i].ToString());
}
Customers.Items.Add(customers);
MessageBox.Show("Sent order for " + fullName.Text.ToString() + " to screen.");
//CLEAR ALL FIELDS
OrderlistBox.Items.Clear();
fullName.Text = "";
Address.Text = "";
telephone.Text = "";
totalDue.Text = "";
totalItems.Text = "";
}
private void customerInformationToolStripMenuItem_Click(object sender, EventArgs e)
{
if (Customers.SelectedItems.Count != 0)
{
MessageBox.Show("Name: " + Customers.SelectedItems[0].SubItems[0].Text + "\n" +
"Adress: " + Customers.SelectedItems[0].SubItems[3].Text + "\n" +
"Telephone: " + Customers.SelectedItems[0].SubItems[4].Text + "\n" +
"Order: " +Customers.SelectedItems[0].SubItems[5].Text);
}
}
You can create custom message box by creating new winform that act as your messagebox.
Create public property on it to pass the value of your selecteditems something like:
Then on your form :
private void customerInformationToolStripMenuItem_Click(object sender, EventArgs e)
{
if (Customers.SelectedItems.Count != 0)
{
var myformmessagedialog = new MyFormMessageDialog
{
name = Customers.SelectedItems[0].SubItems[0].Text,
adress=Customers.SelectedItems[0].SubItems[3].Text,
telephone=Customers.SelectedItems[0].SubItems[4].Text
};
myformmessagedialog.ShowDialog();
}
}
Your MessageBoxDialogform:
MyFormMessageDialog : Form
{
public MyFormMessageDialog()
{
InitializeComponent();
}
public string name;
public string adress;
public string telephone;
private void MyFormMessageDialog_Load(object sender, EventArgs e)
{
lblName.Text = name;
lbladdress.Text = adress;
telephone.Text telephone;
//if you are saving ado.net stuff
//query username where name = name then bind it on a list box or a combo box
var Orderdata = //you retrieve info via DataTable;
lstOder.Items.Clear();
foreach (DataRow data in Orderdata.Rows)
{
var lvi = new ListViewItem(data["Order"].ToString());
// Add the list items to the ListView
lstlstOder.Items.Add(lvi);
}
}
}
Hope this help you.
Regards