What is the best way for managing data between classes? - c#

using c# - WinForms, .net Framework 4.5, VS 2012
Try to create small app with some entity.
I create separate class for my entity and put some simple code inside:
public class Car
{
public string Color {get; set;}
public string Make { get; set; }
public string CarModel { get; set; }
}
Then from main form i create some specimen of class Car (creating can be geted by clicking button from main form, after clicking new form with 3 text boxes will be opened, if information entered and button Ok clicked - new Car sample must be created and returned to main form).
For this i try to use next code:
public Car myCar = new Car();
private void buttonAdd_Click(object sender, EventArgs e)
{
myCar.Color = textBoxColor.Text;
myCar.Make = textBoxMake.Text;
myCar.CarModel = textBoxModel.Text;
this.DialogResult = DialogResult.OK;
this.Close();
MessageBox.Show("Added");
this.Close();
}
For moving data from new form to main form I use public field public Car myCar = new Car();, but this is not the best way to do this, due to using of public field.
Another way I found - in main form create next method
static List<Car> carInStock = null;
public static void myCar(string color, string make, string model)
{
Car myCar = new Car
{
Color = color,
CarModel = model,
Make = make
};
MainForm.carInStock.Add(myNewCar);
}
and for button can use method like:
private void buttonAdd_Click(object sender, EventArgs e)
{
MainForm.myCar(textBoxColor.Text,
textBoxMake.Text,
textBoxModel.Text);
MessageBox.Show("Added");
this.Close();
}
But think varian also not hte best and prefered.
Question: What is the best way to move created entity (in this case entity of Car, represented as myCar) from one form to another?

For this kind of GUI Application, I suggest you follow MVC or MVP pattern. The class car is the model, the Windows Forms are the views, the view doesn't hold an instance of the model, and the views are updated through controller or presenter.
You can find more details about MVC/MVP here

Related

Save/Open Dynamically Created Controls In a Form

I am trying to develop a program in which it could create forms and add controls to it at runtime.
It also should be able to save, (Open and Edit) the forms created with the new controls added it at Runtime.The Application starts In the Main form.
CODE BEHIND MAIN Form
private void Btn_CREATE_FORM_Click(object sender, EventArgs e)
{
Form_Properties fp = new Form_Properties();
fp.Show();
}
private void BTn_ADD_BTN_Click(object sender, EventArgs e)
{
/// WHAT CODE SHOULD I ENTER TO ADD BUTON TO NEW FORM
}
Basically the main form is used to create/open/save new forms and add controls to it.
When the user clicks on Create New Form button the user will be presented with the following form (FORM_PROPERTIES) in which the user can customize the name, width and height of the new form.
CODE BEHIND FORM_PROPERTIES Form
public partial class Form_Properties : Form
{
public Form_Properties()
{
InitializeComponent();
}
String form_name;
int form_width;
int form_height;
private void Btn_OK_Click(object sender, EventArgs e)
{
form_name = TBox_NAME.Text;
form_width = Convert.ToInt32(TBox_WIDTH.Text);
form_height = Convert.ToInt32(TBox_HEIGHT.Text);
New_Form nf = new New_Form();
nf.Text = form_name;
nf.Width = form_width;
nf.Height = form_height;
nf.Show();
}
}
The following image shows what happens at runtime based on the code I have written so far.
ISSUES
Need help to Write Code
To add controls to new form created.
To Save/Open/Edit Functionalities.
I also need to know the method to access properties of added controls at runtime.
eg: If the user adds a text box to the NEW FORM and decides to type some text in it, I need a method to save that text.
Is there a way for me to name the added controls?
It seems you want to build some kind of WinForms' form designer. Your program would be similar to Glade (though Glade is much more powerful).
I'm afraid the question is too broad, though. There are many questions to answer, for example, how do you describe the created interface.
While Glade uses XML, you can choose another format, such as JSON. Let's say that you have a TextBox with the word "example" inside it.
{ type:"textbox" text:"example" }
It seems you want to add your components to the form as in a stack. Maybe you could add its position. For example, a form containing a label
("data"), a textbox ("example"), and a button ("ok"), would be:
{
{ pos:0, type:"label", text:"data" },
{ pos:1, type:"textbox", text:"example" },
{ pos:2, type:"button", text:"ok" },
}
But this is just a representation. You need to a) store this when the form is saved, and b) load it back when the form is loaded.
For that, you will need a class representing the components, such as:
public class Component {
public override string ToString()
{
return string.Format( "position:{0}, text:{1}", this.Position, this.Text );
}
public int Position { get; set; }
public string Text { get; set; }
}
public class TextBoxComponent: Component {
public override string ToString()
{
return base.ToString() + "type:\"textbox\"";
}
}
...and so on. This is a big task, I'm afraid, with no simple answer.

Form 2 textbox displays in form 1 listbox

I currently have two forms, one to display information when a user is selected from the listbox(the listbox lists names, when selected it will fill a few textboxes I have, one for city and another for address), the second form allows me to input the information for the user, which when I click submit will display them in my listbox on form1. Currently I am able to add the user from my second form to my first form into the listbox, but I am having issues filling their information in the textbox whenever I click on their names in my listbox.
As of now I have tried implementing different code snippets, but being a beginner I'm not sure how to do this.
My first form is as follows
public Form1()
{
InitializeComponent();
}
private void ButtonAddUser_Click(object sender, EventArgs e)
{
Form2 form = new Form2(textBoxFirstName.Text, listBoxUsers);
form.Owner = this;
form.ShowDialog();
form.Show();
}
private void listBoxUser_SelectedIndexChanged(object sender, EventArgs e)
{
if (listBoxUser.SelectedIndex != -1)
{
User selected = (User)listBoxUser.SelectedItem;
textBoxStreet.Text = selected.Street;
textBoxCity.Text = selected.City;
}
}
My second form where I add the users information is as follows
public partial class Form2 : Form
{
private ListBox _listBoxUsers;
public Form(string value, ListBox listBoxUser)
{
InitializeComponent();
value=($"{textBoxFirstName.Text} {textBoxLastName.Text}");
_listBoxUsers = listBoxUsers;
}
private void ButtonSubmit_Click(object sender, EventArgs e)
{
_listBoxUsers.Items.Add($"{textBoxFirstName.Text}
{textBoxLastName.Text}");
this.Close();
}
}
And my Class where I am trying to store the textbox information
public class User : EventArgs
{
public string Street {get; set;}
public string City {get;set;}
public User(string street, string city)
{
Street = street;
City = city;
}
}
In Short: I'm trying to save information from my second form into my class, and when I select a user from my listbox it will display his street and city into textboxes (my listbox and textboxes are both on my first form.).
Thanks for any help
In the second form you should be creating User object and fill the details like street and city .
private void ButtonSubmit_Click(object sender, EventArgs e)
{
User user = new User(textBoxFirstName.Text, textBoxLastName.Text);
_listBoxUsers.Items.Add(user);
this.Close();
}
Since Listbox.Items expecting object type, you can add anything which is derived from System.Object. But in the form1 you have created list with User Objects and during selected index changed you are type casting as User Object. But in the form2 you have not actually inserted User object during the submit button click .
Because of this, i think you are facing this problem . Try with above code and check
I would suggest decoupling state management from the presentation. For example, try to create a separate class for User that is not derived from EventArgs. And manage its state inside a separate class - for start int will be in-memory storage. But as you flesh out your implementation you can latter move your data to Database with ease as it will not rely on UI and its elements for storage and management.

Full access from Form2 to Form1

How to create a full access from: Form 2 to Form1
So i can use all Textboxes, Datagridviews and the given information from my From1 in my second Form2
My Plan : User choose a Item in my DataGridView and then automatically my Second Form open, where all informations are given in Textboxes and so on... the user can modify them and save them into my SQL Database, Form2 closed and Form1 opens again
I look at Stackoverflow and google but i dont find a soulution, working for me ...
Assume you have person class:
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
And list of persons bound to grid
List<Person> people = GetPeople();
peopleGridView.DataSource = people;
When you double-click on some row, get data bound person and pass it to second form:
private void peopleGridView_DoubleClick(object sender, EventArgs e)
{
if (peopleGridView.CurrentRow == null)
return;
Person person = (Person)peopleGridView.CurrentRow.DataBoundItem;
using (var editForm = new PersonDetailsForm(person))
{
if (editForm.ShowDialog() != DialogResult.OK)
return;
// get updated person data and save them to database
UpdatePerson(editForm.Person);
}
}
In edit form display person data in controls (you can use data-binding also):
public partial class PersonDetailsForm : Form
{
public PersonEditForm(Person person)
{
InitializeComponent();
idLabel.Text = person.Id.ToString();
nameTextBox.Text = person.Name;
// etc
}
public Person Person
{
return new Person {
Id = Int32.Parse(idLabel.Text),
Name = nameTextBox.Text
};
}
}
Benefits - you can change PersonEditForm independently - add/remove controls, change their types, adding data binding etc without changing your main form.
you can create a constructor in your Form2 that takes the parameters that will fill your controls for example:
public Form2(string property1, List<object1> objects)
{
textbox1.text = property1;
gridview1.DataSource = objects;
//and so on
}
and then call them from form1
Form2 form = new Form2(string1,list1);
form.Open();
or you can pass a single object to the constuctor and extend its properties in Form2
Transfer all necessary data to a third class and pass the instance as a parameter to form2.

Mapping custom object to forms

Can I map or automap an object to a Form and from Form to an object?
I have the following code:
// Class model
class Model1
{
Property1;
Property2;
Property3;
...
}
// Form. I use this form to create and update data of Model1
public partial class FormModel1 : Form
{
private Model1 model1;
...
private void LoadData()
{
Property1Txt.Text = model1.Property1;
Property2Txt.Text = model1.Property2;
Property3Txt.Text = model1.Property3;
}
private void SaveButton_Click(object sender, EventArgs e)
{
model1.Property1 = Property1Txt.Text;
model1.Property2 = Property2Txt.Text;
model1.Property3 = Property3Txt.Text;
model1.Save();
}
}
Note that I have simplified the example.
I want to set data from my model to the form and from form to my model dinamically.
How can I do this?
You can implement data bindings as follows
property1Txt.DataBindings.Add("Text", model1, "Property1");
To have this update the textbox when the property changes you also need to implement inotifypropertychanged. See http://msdn.microsoft.com/en-us/library/ms743695.aspx.
then you will need to use
property1Txt.DataBindings.Add("Text", model1, "Property1", false, DataSourceUpdateMode.OnPropertyChanged );
One way you can do to achieve this is by using Reflection.
Another way, is by using the controls' DataBindings property.
Take a look at these, take your time to understand the concepts and come back if you have any questions. In a new question, of course :)
Happy learning!

User Input Validation in Windows Forms Implementing Model View Presenter

I am trying to validate User Input in Windows Forms Application (using MVP design Pattern). Since this is my first project using MVP, I am not very clear where and how to put the user input validation code.
To be specific, I have a Products form which contains two text box controls, Namely ProductName and ProductPrice.
Below is the code for my ProductForm, IProductView and ProductPresenter
IProductView.cs
public interface IProductView
{
string ProductName { get; set; }
int ProductPrice { get; set; }
event EventHandler<EventArgs> Save;
}
frmProduct.cs
public partial class frmProduct : Form,IProductView
{
ProductPresenter pPresenter;
public frmProduct()
{
InitializeComponent();
pPresenter = new ProductPresenter(this);
}
public new string ProductName
{
get
{
return txtName.Text;
}
}
public int ProductPrice
{
get
{
return Convert.ToInt32(txtPrice.Text);
}
}
public event EventHandler<EventArgs> Save;
}
ProductPresenter.cs
public class ProductPresenter
{
private IProductView pView;
public ProductPresenter(IProductView View)
{
this.pView = View;
this.Initialize();
}
private void Initialize()
{
this.pView.Save += new EventHandler<EventArgs>(pView_Save);
void pView_Save(object sender, EventArgs e)
{
throw new NotImplementedException();
}
}
I do want to use the ErrorProvider(EP) Control + since I would be using EP control on many forms, I would really love if I could reuse most of the code by putting the EP code in some method and passing it the controls and appropriate message. Where should I put this validation code?
Regards,
I've used a base form with the error provider on and then had other forms inherit from this. I also put the visual error code in this base form also. This meant the same code is re-used. For Mvp, you could do something similar with a base form and an interface your application views inherit from. Your presenters would then see a uniform interface for setting validation states, messages, etc.

Categories

Resources