Form 2 textbox displays in form 1 listbox - c#

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.

Related

How to transport information from one form to another using dto, C# Windows Forms?

I'm having trouble transporting information from one form to another, is to make a single save, but the information is distributed in 2 forms and I have to do it using dto. I know that for this I have to send the data that I want by the form builder method, as you can see in the code below:
public FrmModalFornecedor(int providerId, int providerDoc)
{
InitializeComponent();
CbxListarFornecedor();
providerDoc = Convert.ToInt32(txtDoc.Text);
providerId = Convert.ToInt32(((Provider)cbxFornecedor.SelectedItem).ProviderId);
}
But now my questions are:
How to make these variables take their respective text box and combo box values?
How to make the next form have access to this data?
You can create additional properties in the second form and you can pass the values from first form to second form.
Hope this gives some ideas for you.
private void button1_Click(object sender, EventArgs e)
{
Form2 frm = new Form2();
frm.MyName = "Pass my name here";
frm.Show();
}
public partial class Form2 : Form
{
public string MyName { get; set }
public Form2()
{
InitializeComponent();
}
}

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.

Why Bindinglist is not updating after database changed?

I am working in Winforms Projects. In which whenever I add or edit record in database and close that from I want my list updated.
But in Search Form my list does not get updated. For that I have to Rebind Data Again from database. When I searched and got know about bindinglist then I used bindinglist instead of list, but it is still not working.
Here is my code
///
/// Represent FirstName Fields
///
public String FirstName { get; set; }
_MemberMaster.FirstName = Convert.ToString(txtFirstName.Text);
string result _IMemberMasterController.UpdateMemberMaster(_MemberMaster);
After update I closed my form, but in search form list not updating. As when list get updated I want datagridview get also updated.
I was about to reply in comments, but I want to give example code.
After the code to create a Form, for example
Form newForm = new Form();
newForm.Show()
or whatever method you use to make that form, add a formClosed event handler:
Form newForm = new Form();
newForm.FormClosed += new FormClosedEventHandler(f_FormClosed);
newForm.Show();
And then you can control what happens when the form is closed, so you can update your bindinglist easily.
void f_FormClosed(object sender, FormClosedEventArgs e)
{
myBindingList.ResetBindings(false);
}
Edit
And in your bindingList constructor: (assuming it contains strings)
private BindingList<string> _mybindinglist;
public BindingList<string> myBindingList
{
get { return _mybindinglist; }
set
{
_mybindinglist= value;
OnPropertyChanged("myBindingList"); // or RaisePropertyChanged or whatever you used
}
}
I Solved my problem with IUNotifyProertyChangedEvent....

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.

Update form from form closing event on another form

I am trying to update a datagridview on my 'switchboard' to solve a concurrency issue. The switchboard has many checkboxes to check off when certain processes are done. When I click a checkbox on a record that has been edited I get a concurrency error as the dgv is not up to date.
I tried doing this:
How to refresh datagridview when closing child form?
to no avail as it raises other errors throughout my project.
Any help on how to refresh my datagridview on my switchboard on the form closing of another form would be great.
Thanks
public partial class frmSwitch : Form
{
public frmSwitch()
{
//'add a label and a buttom to form
InitializeComponent();
}
public void PerformRefresh()
{
this.propertyInformationBindingSource.EndEdit();
this.propertyInformationTableAdapter.Fill(this.newCityCollectionDataSet.PropertyInformation);
this.propertyInformationDataGridView.Refresh() }
}
public partial class frmSummary : Form
{
frmSwitch _owner;
public frmSummary(frmSwitch owner)
//public frmSummary()
{
InitializeComponent();
_owner = owner;
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.frmSummary_FormClosing);
}
private void frmSummary_FormClosing(object sender, FormClosingEventArgs e)
{
_owner.PerformRefresh();
}
That is what I attempted to do but it caused issues in other instances when I needed to open Form2. The issue specifically occurs in the original opening of form 2 which is as follows:
private void propertyInformationDataGridView_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
{
System.Data.DataRowView SelectedRowView;
newCityCollectionDataSet.PropertyInformationRow SelectedRow;
SelectedRowView = (System.Data.DataRowView)propertyInformationBindingSource.Current;
SelectedRow = (newCityCollectionDataSet.PropertyInformationRow)SelectedRowView.Row;
frmSummary SummaryForm = new frmSummary();
SummaryForm.LoadCaseNumberKey(SelectedRow.CaseNumberKey, true, null);
SummaryForm.Show();
}
It sounds like you are trying to create a new instance of your Switchboard form instead of modifying the existing instance of the form. When you open a form from the switchboard, I would suggest passing in instance reference to the switchboard form. Then, when you close the opened form, in your form_closing event you would refer to the passed in instance as the Switchboard form to update.
This method and others are specified in this article:
http://colinmackay.co.uk/blog/2005/04/22/passing-values-between-forms-in-net/

Categories

Resources