Passing value from combobox to form 1 - c#

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

Related

C# Passing string from one form to another

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

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);

Fill combobox when calling from another class

I'm very new to C# and I have a problem filling a combobox when calling the method from another class. My source is like this
class 1
private void btn_login_Click(object sender, EventArgs e)
{
UserControl1 uc1 = new UserControl1();
uc1.fill_cbb();
}
class 2
public void fill_cbb()
{
cbb_table.Items.Add("Text1");
cbb_table.Items.Add("Text2");
cbb_table.SelectedIndex = 0;
}
When I do it that way the combobox is empty.
if it is Asp please take care to the event IsPostBack
Your problem is not calling the method from another class. I suppose UserControl1 is your custom user control, and that the "class 2" you mentioned is a userControl1.
The code would work as it is, but you are calling it on the wrong instance of that control.
In your btn_login_Click method, you are generating a totally new instance of UserControl1. You are of course allowed to do that, which is why Visual Studio would never mark it as an error, but uc1 will not be the control that actually sits in your form.
Let's say in your form you have named the control "cbxOptions". Then in the button click event, you have to write
cbxOptions.fill_cbb();
instead, if that combobox is also of type UserControl1. Then it should work just fine.
Warning, car analogy: It's like when you want a new paint job on your car. Then you buy a new car of the same model and take that to the paint shop, get it painted, then bring it to the junkyard and get it crushed. Your old car will still have the same old color of course.

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.

Removing a Control from a Form

So I've got some serious problems with removing a Control from a Form of my application. It's kinda messed up but I can't change anything. I have a form and I have a separated user Control. The control opens an exe file and shows a progress bar while loading it's bytes. And here comes the problem. I do all of it with a BackgroundWorker and when the worker_DoWorkerCompleted method is called the original form should show a MessageBox and remove the Control.
BackGround_Loader bgLoad = new BackGround_Loader();
bgLoad.Location = new Point(this.Width/2 - bgLoad.Width/2, this.Height/2 - bgLoad.Height/2);
this.Controls.Add(bgLoad);
bgLoad.BringToFront();
bgLoad.AddReferences(this.executableFile, this.SourceReader);
bgLoad.occuredEvent();
At first I set the control's location to be in the middle of the Form itself. Then I add the control to the form, and bring it to the front. After these I send the path of the executable and a RichTextBox's reference to this. With the occuredEvent I start the BackgroundWorker itself. And here comes my problem. I should show a MessageBox in the Form when the in the bgLoad the backgroundworker gets to the DoWorkerCompleted status. Kindly I have no idea how to do it. It works just perfect however the control stays in the middle of the form.
UI actions must be performed on the main UI thread. The events that get raised from the background worker thread are (obviously) in a different thread.
You need something like the following code:
private void backgroundWorker_DoWork(object sender, AlbumInfoEventArgs e)
{
// Check with an element on the form whether this is a cross thread call
if (dataGridView.InvokeRequired)
{
dataGridView.Invoke((MethodInvoker)delegate { AddToGrid(e.AlbumInfo); });
}
else
{
AddToGrid(e.AlbumInfo);
}
}
In this case AddToGrid is my method for adding a row to a DataGridView, but in your case it will be a method that does what you need to do.
Similarly for the backgroundWorker_RunWorkerCompleted method
See this MSDN example
I could find a way to solve the problem but I don't really like it. In the addReferences method I pass the Form itself and an object of the bgLoad class. Then in the RunWorkerCompleted I check if the control is on the form and if it is then I remove it.
bgLoad.AddReferences(this, bgLoad, this.executableFile, this.SourceReader);
...
private void worker_DoWorkerCompleted(object sender, DoWorkerEventArgs e) {
if(this.MainForm.Controls.Contains(this.Control) {
this.MainForm.Controls.Remove(this.Control);
}
}
Like this it works but it's awful for me.

Categories