C# Passing string from one form to another - c#

I have 2 forms called, Main and Kitchen.
In Main I have a textbox called detailName, I need to pass the value of detailName.Text from Main to Kitchen to a TextBox called orderBox.
Kitchen newKitchenForm = new Kitchen();
newKitchenForm.OrderBox.Text = detailName.Text;
That is my code for it but it does not seem to work.
Any help would be appreciated.
Further information:
I'm programming a order food through touchscreen type of thing, so I want the thing that the client orders to be displayed to both the client and to the kitchen, hence the form name "Kitchen".
So after a button called "lockOrder_In" is pressed, I want the food they just chose to be shown to the person ordering and to the kitchen. Here is my code for that button.
private void lockOrder_Click(object sender, EventArgs e)
{
Dish_1.Text += Environment.NewLine + detailName.Text;
Price_1.Text += Environment.NewLine + detailPrice.Text;
// Show the order in the kitchen form
Kitchen newKitchenForm = new Kitchen();
newKitchenForm.ordersBox.Text = detailName.Text;
}
I got the client side to work, but the person order is able to see what they ordered but on the other form "Kitchen" they are not. The food Name which is shown in "detailName.Text" in form "Main", is not displayed in "Kitchen" Form in "orderBox.Text".

You can send it as a parameter in the Kitchen form constructor or define a public property in Kitchen and set its value to the textbox's text property.

This can be achieved easily by creating an instance of Form 1 in Form 2. This is one of the approach.
Follow the steps:
In Form 1 : Make sure that your control is public.
eg: txtForm1.Text = "Bangalore";
In Form 2 :
Step 1: Create an instance of Form 1 globally. If the instance is created locally the value contained by the control cannot be accessed, only null value will be returned even the data has been populated to it.
Step 2 : Retrieve the control's value by Form 1's instance.
eg: Form1 frm1 = new Form1();
string Form1Value = frm1.txtForm1.Text
for more details MSDN Link

Related

Passing value from combobox to form 1

I cannot get my head around this probably simple task, i have 2 forms, my main and a "footprints" one, in the footprints, i have a combobox with various .txt files loaded in, once i select a combobox value i'm trying to send the value to a label on form 1 the main one.
code for form 2:
private void btnUpdateFootprints_Click(object sender, System.EventArgs e)
{
if (File.Exists(#"LogicFiles\footprints.txt"))
{
// add footprints and add to .txt box
File.WriteAllText(#"LogicFiles\" + comboBoxUseFootprints.Text, txtBoxFootprints.Text);
FormMain.lblFootprintsUsed.Text = comboBoxUseFootprints.Text;
this.Hide();
}
}
This part "lblFootprintsUsed.Text" is the name of the label on form 1, the above code is in a button, once clicked it should hide and update the label, i'm getting:
An object reference is required for the non-static field, method, or property 'FormMain.lblFootprintsUsed'
I tried a few things but to be honest i never fully got how to reference form 1 without making a new form instance.
thanks for any help guys
Graham
FormMain.lblFootprintsUsed
This code is trying to set the static label of FormMain. However (correct me if I'm wrong) you have no static method in that form.
I guess that FormMain is the one that creates the footpronts form. In order to actually update the label of the main form you should raise an event from the footpronts form with the new value and subscribe to it from the main form.
http://www.codeproject.com/Tips/55555/Pass-value-between-forms-using-events

set combobox selected item as default for combobox in another form

I have a winforms project for a handheld device where I have multiple forms, I have one form to set the default options for another form, for example there is a comboBox on the default form for Locations which is populated with xml. what I want to do is when the user selects a location from the drop down on the defaults form and hits save, I need the selected location to be set as the default(show first) on the main form.
//Main Form
private void Form1_Load(object sender, EventArgs e)
{
string filePath = "/My Documents/AHWLtTables.txt";
dataSet1.ReadXml(filePath);
comboBox2.DataSource = dataSet1.Tables[8];
comboBox2.ValueMember = "Loc";
comboBox2.DisplayMember = "Desc";
}
This populates the comboBox with the xml data and I know that I can use SelectedIndex to set a default from the list I am just missing how to save the index # from the selection in the default options form and set it to that # in the main form.
Or am I approaching this wrong, should I make the dataSet a public object across all forms and call on it that way somehow?
How do you access to the second form?, you can send the parameter to the other form using a property (its a varible of any type with the get and set method), you can declare a property in the second form:
public int indexCombo {get; set;}
and when you call the form use something like:
Form2 myForm2 as Form2();
myForm2.indexCombo = comboBox2.selectedIndex; //I won't remember exactly the method XD sorry
//As you see first make the instace of the form and second set the value of the property
myForm2.show();
Finally to show the selected index en the new form in the load of the form:
comboBoxForm2.selectedIndex = indexCombo;
You could add a tag to the xml file that would save the index of the combo boxes. Adding the tag to the file is simple. You can just go into the file and do so. You just need to make up for that in your c# code. A good article is this here

Assigning textbox value to a field in a separate form

I am sure this is an easy question to answer, but I am having difficulty implementing it how I need.
I am using Visual Studio 2013 and C#
I have two forms, one that loads when the app starts up which contains user-selectable settings such as user id, how many puzzle pieces that would like on screen... and a confirm button.
The second form is like a puzzle grid, which is generated when the user clicks the confirm button on the first form.
When the person has correctly solved the puzzle, a message box pops up with the time it took to solve.
What I want to be able to do is add the user id field into the messagebox string.
I have seen many examples of using event args and getting and setting fields but most are assuming one form is generated from a previous form, where I just want to 'grab' the information from one form and store it on the second form for use in a string.
Links to tutorials would also be appreciated if that is easier.
I found out what I was doing wrong, with the help of everyone's answers.
I had the variables declared on the first form, but they were declared in the textbox_leave and updownBox_leave methods when they should have been declared at the very top of the class.
Then I just called Form1.IdString and Form1.puzzleNumberString from my Form2 and what-do-you-know everything went as I thought it should.
It's pretty simple.All you need to do is pass your id variable to second form constructor.For example in your Confirm Button click:
Form2 f2 = new Form2(myVariable);
f2.Show();
And you should add a constructor to the Form2:
public string ID { get; set; }
public Form2(string id)
{
InitializeComponent();
ID = id;
}
Then you can use ID variable in your second form.
In your puzzle form create a global Form variable, then give the constructor a Form f parameter and set your global form variable as the passed parameter:
public Form form = null;
public PuzzleForm(Form f) //puzzle form constructor
{
form = f;
}
then go into your first form and where you create an instance of the puzzle form change it so that it passes an instance of this.
PuzzleForm pf = new PuzzleForm(this);
Now from inside your Puzzle form you can access your Form1 variables like so MessageBox.Show("UserID: "+form.userID.Text);

How can I transfer information to another form without using static forms?

I have a Windows form that's generated using code (including buttons and what not). On it, amongst other things, there is a text box and a button. Clicking the button opens a new Windows form which resembles an Outlook contact list. It's basically a data grid view with a few options for filtering. The idea is that the user selects a row in this home-made contact book and hits a button. After hitting that button, the (second) form should close and the email address the user selects should be displayed in the text box on the first form.
I cannot use static forms for this purpose, so is there any way to let the first form know the user has selected something on the second firm? Can you do this with events, or is there another way? Mind that I hardly know anything about delegates and forms yet.
Please advise.
Edit 1 = SOLVED
I can return the email address from the second form to the first form now, but that brings me to another question. I am generating controls and in that process I'm also generating the MouseClick eventhandler, in which the previous procedure for selecting a contact is put.
But how do I, after returning the email address in the MouseClick eventhandler, insert that information into a generated text box? Code to illustrate:
btn.MouseClick += new MouseEventHandler(btn_MouseClick);
That line is put somewhere in the GenerateControls() method.
void btnContacts_MouseClick(object sender, MouseEventArgs e)
{
using (frmContactList f = new frmContactList())
{
if (f.ShowDialog(fPrompt) == DialogResult.Cancel)
{
var address = f.ContactItem;
MessageBox.Show(address.Email1Address.ToString());
}
}
}
That appears separately in the class. So how do I put the email address into a text box I previously generated?
Forms in .Net are normal classes that inherit from a Form class.
You should add a property to the second (popup) form that gets the selected email address.
You should show the popup by calling ShowDialog.
This is a blocking call that will show the second form as a modal dialog.
The call only finishes after the second form closes, so the next line of code will run after the user closes the popup.
You can then check the property in the second form to find out what the user selected.
For example: (In the first form)
using(ContactSelector popup = new ContactSelector(...)) {
if (popup.ShowDialog(this) == DialogResult.Cancel)
return;
var selectedAddress = popup.SelectedAddress;
//Do something
}
In response to my first edit, this is how I solved it. If anyone knows how to make it more elegant, please let me know.
void btnContacts_MouseClick(object sender, MouseEventArgs e)
{
using (frmContactList f = new frmContactList())
{
if (f.ShowDialog(fPrompt) == DialogResult.Cancel)
{
var contact = f.ContactItem;
TextBox tbx = ((Button)sender).Parent.Controls[0] as TextBox;
tbx.Text = contact.Email1Address;
}
}
}
You should keep a reference to your generated TextBox in a variable (private field in your class) and use this instead of looking it up in the Controls array. This way your code would still work even if you some time in the future change the location it has in the array, and you would get a compiler message if you removed that field, but forgot to remove the code that used it.
If the second form is modal, I would recommend that rather than having the first form create an instance of the second form and use ShowModal on it, you should have a Shared/static function in the second form's class which will create an instance of the second form, ShowModal it, copy the appropriate data somewhere, dispose the form, and finally return the appropriate data. If you use that approach, make the second form's constructor Protected, since the form should only be created using the shared function.

Opening a winform from a user control and passing back values to the usercontrol

I was wondering if it is possible to have a user control open a winform that allows a user to select options on it and then when he closes the form - the options / values he selected are returned to the user control?
Why not create some public properies on your dialog form, and access them from the UserControl once the dialog has been closed?
public class OptionsForm : Form
{
// ...
public string Option1 { get; set; }
public bool Option2 { get; set; }
}
And then, within the UserControl:
public void ShowOptionsForm()
{
using (var form = new OptionsForm())
{
if (form.ShowDialog() == DialogResult.OK)
{
var option1Value = form.Option1;
var option2Value = form.Option2;
// use option values...
}
}
}
Please consider this answer as an "extended comment" on Steve Greatrex's now-accepted answer : it's too long for a comment, and I want to demonstrate a few options, add a few "flavours" to the taste. This is not at all a "criticism" of Steve's answer which, imho, hit the "bullseye."
Assumptions : if I had read the question earlier, I would have queried the OP via a comment on each of these points :
the OP did not specify whether the Form to be "shown" was to be shown modally or not.
the OP did not specify whether the Form was to be re-created each time it was shown, or whether one instance of it should be created and re-used.
the OP wrote "open a winform that allows a user to select options on it ... snip ... "options / values he selected are returned" : Steve's code does not show exactly how the Properties exposed as Public are set, but I'm going to assume that the OP probably intended to mean that the user interacted with some Controls on the shown Form, and that the "options / values" he refers to are Properties of Controls on the Form : like the end-user typing some text in a TextBox, or the selected indexes in a ListBox with its SelectionMode set to allow one of two choices of multiple selection.
the OP does not say if it's desireable that the Form (if used repeatedly) retain the results of the last interactions of the end-user with the Controls on the Form as described above.
the OP says nothing about whether the Form shown by the UserControl has its Parent property set to some other valid container : I'll assume they meant the Form to be displayed "parent-less."
Comments :
if the OP intended the Form to be shown modally : in order for Steve's code to work, the 'ControlBox of the Form would have to eliminated as an option, and a Button put on the Form whose 'DialogResult property was set to "OK," and whose 'Click Event closed the Form : without those conditiions being met the result of ShowDialog in Steve's code would never return "OK," and the properties' values would never be set. Note : closing a Form via the 'ControlBox will return a DialogResult of "Cancel."
re-use of the shown Form : if we assume the Form will probably be re-used, then why not create it once and 'Show and 'Close as necessary ? Let's consider the possibility that there may be good reasons to expose the created Form as a Public member of the UserControl.
Consider the following alternative idea : trying to present a solution as "different" as possible from Steve's : just to demonstrate, explore, the options.
Our "shown Form" will have a TextBox and a ListBox that allows multiple selections : our goal is to expose the Text in the TextBox and the current selection of Indices in the ListBox.
Form has a ControlBox : does not require a Button to close as described above.
it doesn't matter if the Form is shown modally or not : will set properties the same way in either case.
the Public properties to be set are to be based on reading the current state of Controls on the shown Form.
the Form is created once and exposed as Public : because of this a "side-effect" is that when the Form is re-displayed it will retain the previous results of what the user selected, etc. Of course there are other ways you could easily control that in your code to make one or all of the Controls "virgin" again.
in The "shown Form" which we have named 'DataEntryForm :
Just as Steve shows we define public properties to expose ;
public string TextEntered { get; set; }
public ListBox.SelectedIndexCollection LBSelection { get; set; }
In the Form Closing Event we update the properties based on the state of the Controls :
private void DataEntryForm_FormClosing(object sender, FormClosingEventArgs e)
{
TextEntered = textBox1.Text;
LBSelection = listBox1.SelectedIndices;
}
in the UserControl we create a public property of type 'DataEntryform (reason why to be explained)
public DataEntryForm theDataEntryForm { get; set; }
We create an instance of the DataEntryForm in the Load Event of the UserControl and assign it to the public Property
private void UserControl1_Load(object sender, EventArgs e)
{
theDataEntryForm = new DataEntryForm();
}
At this point we will leave it to the OP's (and your) imagination to picture when the instance of the DataEntryForm is shown. But of course we want to demonstrate how you would access the properties after the Form has been closed : so we put a Button on the UserControl :
private void button2_Click(object sender, EventArgs e)
{
Console.WriteLine(theDataEntryForm.TextEntered);
Console.WriteLine(theDataEntryForm.LBSelection.ToString());
}
Note : we didn't do any "fancy" analysis of the ListBox selected indices : but we could have written out whether it was null, or how many items had been selected, etc.
Also : we didn't deal with the issue of what if the OP wants to take some action the moment the "shown Form" is closed : that's so simple : you just subscribe to the FormClosed event of the Form in the UserControl, and do what you need to do in your Event Handler code.
Finally we come to the question of why make a Public Property of type 'DataEntryForm :
Well, just consider that by exposing that "shown Form" via a Public Property in the UserControl : we allow the potential containers (probably a Form) of the UserControl instances to also have access to the values of the Controls on the "shown Form" ... which may be valuable, may save us some duplication of properties.
So, if UserControl1 is on Form1, and Form1 wants to know the Text value of the TextBox on the "shown Form" : it could be accessed like so :
this.userControl11.theDataEntryForm.TextEntered
Edit : A friend of mine wrote me to express his opinion that allowing a "higher-level" container to directly access a "component" embedded in a UserControl was a "violation" of good OOD practicem and breaks encapsulation : he issued me a moving violation ticket :) So, keep his warning in mind. From his point of view the properies should be duplicated in the UserControl with different names, and only those UserControls properties made available to the UserControl Container. My bias is to see the "UserContro/Form" as one "compound object" here, which, since the Form is exclusively used by the UserForm, justifies not duplicating the Properties /Edit
Of course we've left out checking for possibly null values of everything-under-the-sun as we all do so religiously.
here's a short example on how you could do it. It's not complete you'll have to fill in some of the blanks but it should give you an idea of how to solve your problem.
this code goes where you construct your control and you form
MyUserControl ctrl = new MyUserControl();
Action<typeYouPassBack> callBack = myUserControl.FormCallBack;
MyOptionForm form = new MyOptionForm(callBack);
the form class would then have to look something like this: (important part is the action argument)
class MyOptionForm : Form
{
private readonly Action<typeYouPassBack> _callBack;
public MyOptionForm(Action<typeYouPassBack> callBack)
{
_callBack = callBack;
Close += form_Close;
}
privatre void form_close(object sender, EventARgs e)
{
typeYouPassBack postBackData = //populate the postback data
_callBack(postBackData);
}
}
the type Action is simply a delegate with the signature void f(T arg). In the above code it's expected for the user control to have amethod called 'FormCallBack' which of course can be named anything you like as long as you use the correct name when assigning it to the 'callback' variable

Categories