Windows forms pass List to a new form - c#

How can I pass a variable to another form?
I created the following class:
class Cart
{
private string productName;
private int qtd;
private decimal price;
public decimal Price
{
get
{
return price;
}
set
{
price = value;
}
}
public string ProductName
{
get
{
return productName;
}
set
{
productName = value;
}
}
public int Qtd
{
get
{
return qtd;
}
set
{
qtd = value;
}
}
}
I have one form that I add values to my cart:
public partial class frmProducts : Form
{
List<Cart> cartList = new List<Cart>();
private void btnAddCart_Click(object sender, EventArgs e)
{
if(txtQtd.Text == "")
{
MessageBox.Show("Enter how many items do you want.", "Products", MessageBoxButtons.OK);
return;
}
if (Convert.ToInt32(txtQtd.Text) > Convert.ToInt32(lblQtd.Text))
{
MessageBox.Show("We onlye have " + lblQtd.Text + " items in stock.", "Products", MessageBoxButtons.OK);
return;
}
Cart cart = new Cart();
cart.ProductName = lblProductName.Text;
cart.Qtd = Convert.ToInt32(lblQtd.Text);
cart.Price = Convert.ToDecimal(lblPrice.Text);
cartList.Add(cart);
}
}
I haave another WindowsForms that will work with the cartList. How can I send the cartList to the new WindowsForms?

Let frmProcessCart be the next form where you need the cartList to proceed. For that you can use any of the following options:
Get List<Cart> in the Constructor of that form:
Which means you have to pass the cartList as to the new form through its constructor, so you will get the same instance of the list their and you can proceed with that as well. In this case the Constructor of that form looks like this:
public frmProcessCart(List<Cart> cartList)
{
// Something here if needed
}
Another option is make cartList as static field:
In this case you can access the cartList from any other forms in the applications through frmProducts.cartList, you need not to pass any instance or create any instance of the frmProducts. in this case the definition of the cartList will be like this
public partial class frmProducts : Form
{
public static List<Cart> cartList = new List<Cart>();
// Rest of code here
}

In the new windows form declare a property for the cartList. Set the property before you show that form. Then your new form can work with that property.

Related

Sharing values between different Classes in WPF

I have a WPF Project where I want to save DataRows from a DataGrid into an "options" class and retrieve those variables in another window.
Thats how I save my Variable from my DataGrid into my "options" Class (mainWindow.xaml.cs):
options.title = Convert.ToString((showEntries.SelectedItem as DataRowView).Row["title"]);
This Variable im saving via a getter and setter (options.cs):
public string Title
{
get { return title; }
set { title = value; }
}
And now I want to retrieve the saved variable in another window(updateDatabse.xaml):
private void getUpdateEntries()
{
Options returnValues = new Options();
titleBox.Text = returnValues.Title;
}
My Question is: Why is my textbox "titleBox" empty when running my code.
If the logic of your task does not provide for the creation of several instances of classes (and as far as I understand your explanations, this is so), then you can use the Singlton implementation.
Example:
public class Options
{
private string title;
public string Title
{
get { return title; }
set { title = value; }
}
private Options() { }
public static Options Instance { get; } = new Options();
}
Options.Instance.Title = Convert.ToString((showEntries.SelectedItem as DataRowView).Row["title"]);
private void getUpdateEntries()
{
titleBox.Text = Options.Instance.Title;
}
You mixed things up.
private void getUpdateEntries()
{
Options returnValues = new Options();
returnValues.title = Convert.ToString((showEntries.SelectedItem as DataRowView).Row["title"]);
titleBox.Text = returnValues.Title;
}

Can't programmatically set a ComboBox selection

I am unable to programmatically set the selection in a ComboBox.
I try setting various properties (SelectedItem, SelectedText, SelectedIndex) but the ComboBox does not display the Name. The first row of the ComboBox, which is blank, is selected. The return value of the setting of the Property is correct.
What am I doing wrong?
...
this.bsConstructionContractors.DataSource = typeof(Contractor);
...
public partial class EditContractorDialog : Form
{
public EditContractorDialog(Contractor contractor)
{
InitializeComponent();
this.cmbEditContractorName.DataBindings.Add(new System.Windows.Forms.Binding("SelectedValue", projectView.bsProject, "ContractorId", true));
// new BindingSource is important here, so as to use a separate CurrencyManager
// because bsConstructionContractors is shared with another ComboBox on another form
this.cmbEditContractorName.DataSource = new BindingSource(projectView.bsConstructionContractors, null);
this.cmbEditContractorName.ValueMember = "ContractorId";
this.cmbEditContractorName.DisplayMember = "Name";
cmbEditContractorName.Enabled = true;
cmbEditContractorName.Focus();
// None of the following cause the ComboBox to display Contractor.Name
// The first entry in the ComboBox, which is a blank, is displayed
object myObject = cmbEditContractorName.SelectedItem = contractor;
System.Diagnostics.Trace.WriteLine("EditContractorDialog(): myObject: " + myObject.GetType()); // type is Contractor
System.Diagnostics.Trace.WriteLine("EditContractorDialog(): myObject: " + myObject); // myObject is the contractor
object myObject2 = cmbEditContractorName.SelectedText = contractor.Name;
System.Diagnostics.Trace.WriteLine("EditContractorDialog(): myObject2: " + myObject2.GetType()); // type is String
System.Diagnostics.Trace.WriteLine("EditContractorDialog(): myObject2: " + myObject2); // myObject2 is the contractor.Name
object myObject3 = cmbEditContractorName.SelectedIndex = 3; // arbitrary index, just to see if it would be selected
System.Diagnostics.Trace.WriteLine("EditContractorDialog(): myObject3: " + myObject3.GetType()); // type is Int32
System.Diagnostics.Trace.WriteLine("EditContractorDialog(): myObject3: " + myObject3); // myObject3 = 3
}
}
public partial class Contractor : System.IComparable
{
protected int id;
protected string name;
protected string licenseNumber;
protected Project project;
public virtual int ContractorId
{
get { return this.id; }
set { this.id = value; }
}
public virtual string Name
{
get { return this.name; }
set { this.name = value; }
}
public virtual string LicenseNumber
{
get { return this.licenseNumber; }
set
{ this.licenseNumber = value; }
}
public virtual int CompareTo(object obj)
{
if (!(obj is Contractor))
{
throw new System.InvalidCastException("This object is not of type Contractor");
}
return this.Name.CompareTo(((Contractor)obj).Name);
}
}
Use SelectedIndex finding the index by contractor name:
cmbEditContractorName.SelectedIndex = cmbEditContractorName.FindString(contractor.Name);
That is because you need to get an object reference to assign from the DataSource of the combobox itself.
Also for comboboxes I suggest you to use an ObservableCollection<T>.
cmbEditContractorName.DataSource = new ObservableCollection<Type>(your List<Type>);
cmbEditContractorName.SelectedItem = ((ObservableCollection<Type>)cmbEditContractorName.DataSource).FirstOrDefault(c=> c.yourProperty = "something"); // this will select the first item meeting your condition
Your code isn't working because you are assigning SelectedItem property with a reference of an object not existing in the combobox DataSource.

Passing parameter value to a new form

I would like to point to a row.
Get the Oid(the parameter I want to pass).
When I click a button on the ribbon. It will open MifarePasswordForm. I would like to pass Oid to MifarePasswordForm so that the Oid can be saved in Mifare Card but I'm stuck at getting the Oid. So far, this is what I've got.
public void barButtonItem1_ItemClick()
{
staff entity = gridView.GetRow(gridView.GetSelectedRows()[0]) as staff;
entity.Oid;
MifarePasswordForm modalForm = new MifarePasswordForm();
modalForm.ShowDialog();
RefreshData();
}
This is my password form.
public MifarePasswordForm(int _iD)
{
InitializeComponent();
int iD = _iD;
}
Updated code
public void barButtonItem1_ItemClick()
{
staff entity = gridView.GetRow(gridView.GetSelectedRows()[0]) as staff;
MifarePasswordForm modalForm = new MifarePasswordForm(entity.Oid);
modalForm.ShowDialog();
RefreshData();
}
public MifarePasswordForm(int _iD)
{
InitializeComponent();
int iD = _iD;
textBox1.Text += iD;
}
What you can do is, pass your parameter to form in the constructor itself OR, make a public property and access it after creating formInstance and assign it your designated value.
e.g.
MifarePasswordForm modalForm = new MifarePasswordForm(entity.Oid);
modalForm.ShowDialog();

C# ComboBox List<object> ==> Show always the same object.name (multiple time)

I just want my ComboBox to show me the
FullName of objects in List(Curator),
but it show me the same "object.FullName" multiple times :-(
-
Basically, it work cause it show me the FullName of ONE of the Curator,
and the good amount of times,
but it show me the same ONE !
public partial class SGIArt : Form
{
public static Gallery gal = new Gallery(); // from a dll i made
List<Curator> curList = new List<Curator>();
public SGIArt()
{
InitializeComponent();
comboCur.DataSource = curList;
comboCur.ValueMember = null;
comboCur.DisplayMember = "FullName";
UpdateCurList();
}
public void UpdateCurList()
{
curList.Clear();
foreach (Curator cur in gal.GetCurList())
// from the same dll : Curators curatorsList = new Curators();
{
curList.Add(cur);
}
}
private void comboCur_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboCur.SelectedValue != null)
{
//show info in textBox (that work fine)
}
}
}
Curator class :
public class Curator : Person
{
private int id;
private double commission;
const double commRate = 0.25;
private int assignedArtists = 0;
public int CuratorID
{
get
{
return id;
}
set
{
id = value;
}
}
...
public Curator()
{
}
public Curator(string First, string Last, int curID)
: base(First, Last) // from : public abstract class Person
{
id = curID;
commission = 0;
assignedArtists = 0;
}
Edit: You might be looking for this answer.
I do not see the FullName member in your code snippet. I think you are looking for something like this:
List<Curator> curList = new List<Curator>();
public SGIArt()
{
InitializeComponent();
comboCur.DataSource = datasource;
comboCur.ValueMember = null;
comboCur.DisplayMember = "FullName";
UpdateCurList();
}
List<string> datasource()
{
List<string> datasource = new List<string>();
foreach(Curator curator in curList)
{
datasource.Add(curator.FullName)//this assume FullName is an accesible member of the Curator class and is a string.
}
return datasource;
}
The comboBox shows you object.FullName, because this is what you are telling it. The curList is empty at the time when you bind it.
You can update your list before using it:
public SGIArt()
{
InitializeComponent();
UpdateCurList();
comboCur.DataSource = curList;
comboCur.ValueMember = null;
comboCur.DisplayMember = "FullName";
}

add data to gridView on form from another class

How can i append data to my dataGridView on form, from another class?
here is class:
class TermSh
{
public HttpWebRequest request_get_page_with_captcha;
public HttpWebResponse response_get_page_with_captcha;
public string url;
public Form1 form1;
public BindingSource bindingSource1 = new BindingSource();
public int id = 0;
public TermSh(Form1 form1)
{
this.form1 = form1;
form1.dataGridView1.DataSource = bindingSource1;
}
public void somemethod()
{
try
{
cookies += response_get_page_with_captcha.Headers["Set-Cookie"];
bindingSource1.Add(new Log(id++, DateTime.Now, cookies));
form1.dataGridView1.Update();
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
and form class:
TermSh term_sh = new TermSh(this);
term_sh.somemethod();
what i do wrong? why my datagridview is empty after code executing, but with debug i see, that bindingSource1 is not empty.
how to add data?
I think , the way you are going to achieve your goal is incorrect.
first of all, I think passing Form class to a class is very very bad. and then you can simply manipulate a list and return the value and using this value (list) in your Form.
I think it's better to do like this:
[EDIT 1] this following class, is your ptimary class that has a method and this method return a new Log, and you can add this return value to the datagridview in the Form1.
class TermSh
{
public HttpWebRequest request_get_page_with_captcha;
public HttpWebResponse response_get_page_with_captcha;
public string url;
public int id = 0;
public List<Log> somemethod()
{
try
{
cookies += response_get_page_with_captcha.Headers["Set-Cookie"];
return new Log(id++, DateTime.Now, cookies); //use this return value in your Form and update datagridview
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
}
[EDIT 2] after that: you must prepare Log Class to be used as a collection in bindingSource (Form1.bindingSource) and update gridView. and the Following code show the Log class:
class Log
{
private int id;
private DateTime datetime;
private string log_text;
public Log(int id, DateTime datetime, string log_text)
{
this.id = id;
this.datetime = datetime;
this.log_text = log_text;
}
#region properties
public int ID { get { return id; } set { id = value; } }
public DateTime DATE_TIME { get { return datetime; } set { datetime = value; } }
public string LOG_TEXT { get { return log_text; } set { log_text = value; } }
#endregion
}
[Edit 3] and this code in the Form1, use the return value of class TermSh, and populate the dataGridView:
TermSh term_sh = new TermSh(city, type, null, null);
logList.Add(term_sh.getPageWithCaptchaConnection());
logBindingSource.DataSource = logList;
logBindingSource.ResetBindings(false);
[EDIT 4] so if you have a question that : "how use this class as a collection in bindingSource??". It's simple, you can populate a dataGridView with objects: this article is helpful.

Categories