Get a value from another Form c# - c#

I am trying to get a value from another form in a text box. When I click on a text box, another form appears that is a numeric keypad and I can enter a number.
What I want is for the textbox I click to get the value of that new form.
How could I do this?
Example:
I have the next textbox:
When I do click on this textbox appears the following form to introduce some numbers:
When I click on the enter button of the second form, I would like to close this form and get the value "78552" into the first textbox.
I am trying putting the textbox of the second form as a public static but is not working.
What could I do?
EDIt:
This is what I am trying:
private void micrasmin_Click(object sender, EventArgs e)
{
Tecladojm t = new Tecladojm();
t.Show();
using (var form = new Tecladojm())
{
//var result = form.ShowDialog();
if (Tecladojm.buttonEnterClicked == true)
{
string val = form.DevolverNumeroMarcado();
micrasmin.Text = val;
}
}
}

There are a number of ways to accomplish this, however I usually do the following.
1) Update your constructor in Form2 to include a parameter as so:
public Form2(string form1Text1, string form1Text2, string form1Text3)
{
InitializeComponent();
this.label1.Text = form1Text;
}
2) In your button click that opens the second form, simply do the following:
private void button1_Click(object sender, EventArgs e)
{
var form2 = new Form2(this.textBox1.Text, this.textBox2.Text, this.textBox3.Text);
form2.Show();
}
That should work for you. Let me know if you have any questions.

Related

Creating a temporary name for a button

I've been looking for a solution for days now.
Currently have 2 Forms. Main Form has multiple buttons, lets say (1-10).
All buttons will open up my 2nd Form (say I press Button 4). On my 2nd Form I have a ComboBox with different names and a confirm button. When I choose a name from the ComboBox, then press the confirm button.
I want the name selected in the ComboBox to be displayed as the new button text from my Main form (So name3 from Form 2 ComboBox will replace Button text (Button 4) on Main Form).
Any suggestions on how I can achieve this?
I can get the text from ComboBox to Main Form into a Label or a Button of my choosing, but I can't do it from the pressed button on Main Form which opened Form 2.
I've tried changing the button pressed on Main Form to a buttonTemp name, then letting the text from ComboBox change buttonTemp text, but it's coming up as it doesn't exist on Form 2.
Form 1 code:
public void b1111_Click(object sender, EventArgs e)
{
b1111.BackColor = Color.Red;
buttonTemp.Name = "bTemp2";
b1111.Name = "buttonTemp";
Classroom f4 = new Classroom();
f4.Show();
}
this is on Form 2:
private void button1_Click(object sender, EventArgs e)
{
temp1 = comboBox1.Text;
// trying to figure out the label text
foreach (Term1 Form1 in Application.OpenForms.OfType<Term1>())
{
Form1.buttonTemp.Text = comboBox1.Text;
}
this.Close();
}
Do not operate on the controls of other forms. Instead operate with values.
In your case when you finished and closed Form2 you can return a value back to the Form1 and update button text with a returned value.
In Form2 create public property which will be populated before you close Form2.
public string SelectedName { get; set; }
private void selectNameButton_Click(object sender, EventArgs e)
{
SelectedName = comboBox1.Text;
this.Close();
}
In Form1 use .ShowDialog() method to display form in modal form
public void openForm2Button_Click(object sender, EventArgs e)
{
openForm2Button.BackColor = Color.Red;
using (var form = new Classroom())
{
form.ShowDialog();
// next line will be execute after form2 closed
openForm2Button.Text = form.SelectedName; // update button text
}
}
Suggested by #Enigmativity in the comments:
// Form 2
public string SelectedName => comboBox1.Text;
private void selectNameButton_Click(object sender, EventArgs e)
{
this.Close();
}
// Form 1 remains same
There is many ways to get your goal.
I hope you try to use event.
You can make your own event as below.
private void Form1_Load(object sender, EventArgs e)
{
//define listen event from custom event handler
_form2.OnUserSelectNewText += new Form2.TextChangeHappen(_form2_OnUserSelectNewText);
}
When you have member variable for remember which button clicked by user.
private Control activeControl = null;
and you can get text that user's choice from your custom event at Form2.
//to make simple code, centralize all buttons event to here.
private void button_Click(object sender, EventArgs e)
{
//to remeber which button is clicked.
activeControl = (Button)sender;
_form2.ShowDialog();
}
and then you just change text of "activeControl".
private void _form2_OnUserSelectNewText(string strText)
{
activeControl.Text = strText;
}
please refer this, how to make custom event with delegate.
public partial class Form2 : Form
{
//you can expand your own custom event, string strText can be Control, DataSet, etc
public delegate void TextChangeHappen(string strText); //my custom delegate
public event TextChangeHappen OnUserSelectNewText; //my custom event
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
// to prevent null ref exception, if there is no event handler.
if (OnUserSelectNewText != null)
{
OnUserSelectNewText(this.comboBox1.Text);
}
this.Close();
}
}

How to add a text to CheckBox from form2 to form 1 (C#)

So, I've just started learning C# and I have been looking on tutorials in YouTube but in Console Applications.
I have now made my first WFA and I'm trying to create a Calendar where you can add different times with different texts so you stay informed for example a upcoming test.
So far I've come this far: It's in Swedish
And I've also connected the "Lägg Till" (Add in English) to another form called laggTill
Connection in codeform -
laggTill lgtl = new laggTill ();
lgtl.Show ();
Form2 called laggTill looks like:
Also in Swedish
So my question is, how can I by pressing the "Spara" button (Save in English) put the text from the TextBox in laggTill form to the CheckBox in the "Kommande datum:" CheckBox?
Create public properties in Form2, in the example below you can see how to access them.
you did not asked that, but sometimes you dont want to update Form1 (for example the user pressed on cancel button) - use the DialogResult value of Form 2 in order to determine if there is a need to update Form1, in the example DialogResult is DialogResult.OK but it could be also DialogResult.Cancel.
user presses "Spara" button on Form2:
public string valueToForm1 { get; set; } //public properties to access from form1
public DateTime value2ToForm1 { get; set; }
private void button1_Click(object sender, EventArgs e)
{
this.valueToForm1 = "SomeValue";
this.value2ToForm1 = dateTimePicker1.Value;
this.DialogResult = DialogResult.OK;
this.Close();
}
calling Form2 from Form1:
private void button1_Click(object sender, EventArgs e)
{
using (var form = new Form2())
{
var result = form.ShowDialog();
if (result == DialogResult.OK)
{
//values preserved after close
string val = form.valueToForm1;
DateTime dateValue = form.value2ToForm1;
//for example
this.txtValueFromForm2.Text = val;
this.dateTimePicker1.Value = dateValue;
}
}
}
on another button on Form2 (lets say cancel button) you can do that piece of code, if there is a case that you dont want to update Form1:
private void button2_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.Cancel;
this.Close();
}

C# change textbox text on a modal form from an another form

I'm trying to change a text on a TextBox on a modal main form by clicking on a button from an another active form, need help.
Main form *Modal mode
public void changetext(){
textbox1.text = textnew;
}
form2 *active form
private void btnChange_Click(object sender, EventArgs e)
{
mainform form1 = new mainform;
public String textnew = "NEW"
form1.changetext();
this.close
}
Ive tired to use this code but it gives me the error of : Invoke or BeginInvoke cannot be called on a control until the window handle has been created.:
public void LabelWrite(string value)
{
if (InvokeRequired)
Invoke(new LabelWriteDelegate(LabelWrite), value);
else
{
textBox1.Text = value;
}
}
delegate void LabelWriteDelegate(string value);
i think there's a logic issue. If i understand your requirement, you have a main form which contains a search textbox. When the user launch a serach, you open a modal form where all possible results are displayed. The user selects the value he wants and then you get the result in the main form. Is this correct? If so you should do it this way:
Create a public property on the modal form which contains the result.
Either create a public property or create a new constructor on the modal form to pass the query.
On the main form, you can access the public properties of the modal form as long as it is not disposed.
For instance:
var result = null;
var modal = new ModalForm(query);
if(modal.ShowDialog() == DialogResult.OK) // This means the user has selected a value
{
result = modal.SelectedResult;
}
modal.Close();
modal.Dispose();
The easiest way is to pass the new text to the modal window.
For example:
Main form Modal mode
public void changetext(String textnew){
textbox1.text = textnew;
}
form2 active form
private void btnChange_Click(object sender, EventArgs e)
{
mainform form1 = new mainform;
form1.changetext("NEW");
this.close
}
If I were you I would also change form names, they are a little bit confusing.
P.S. I still don't get what is this.close is needed for.

How to hold the invalid value for NumericUpDown after it loses focus?

In my project there is an UserControl which includes a NumericUpDown ctrl, and its valid value range is from 10 to 100,
so if user inputs 200 in NumericUpDown ctrl, then its value will changed to 100 automatically after the focus changed to other ctrl, it looks a little bit curious for customer, because they may click the OK button after input 200 in the NumericUpDown ctrl, they need a message box that tells them the value they input is not in the range.
But the question is the value for NumericUpDown will change automatically after the focus changed if the value input is out of its range.
So how to implement this?
Sameh Serag, this is the code I have tested. I have add a button on the form but did nothing. The result for me is after I input 200 and click the button, only a messagebox with value 100 is shown. After I input 200 and press the tab key, it will only show a messagebox with the value 200 and the text value in NumericUpDown is changed to 100. So curious :-) Anyway thank you very much for your help! BTW, the .Net framework version is 2.0 with sp2 for me.
public partial class Form1 : Form
{
private TextBox txt;
public Form1()
{
InitializeComponent();
txt = (TextBox)numericUpDown1.Controls[1];
txt.Validating += new CancelEventHandler(txt_Validating);
}
void txt_Validating(object sender, CancelEventArgs e)
{
MessageBox.Show(txt.Text);
}
}
The trick is to get the textbox embedded within the numeric updown control, and handle its Validating event.
Here is how to get it done:
Creat a dummy form and add a numeric updown control and some other controls, and when the numeric unpdown control looses the focus, the text of the form will be set to the value that the user entered.
Here it the code of what I have done:
public partial class Form1 : Form
{
TextBox txt;
public Form1()
{
InitializeComponent();
txt = (TextBox)numericUpDown1.Controls[1];//notice the textbox is the 2nd control in the numericupdown control
txt.Validating += new CancelEventHandler(txt_Validating);
}
void txt_Validating(object sender, CancelEventArgs e)
{
this.Text = txt.Text;
}
}
EDIT:
#Carlos_Liu: Ok, I can see now the problem, you can achieve this with the TextChanged event, just save the value in a dummy variable and reuse it at txt_Validating, but be cautious, don't update this variable unless the textbox is focused.
Here is the new sample code:
public partial class Form1 : Form
{
TextBox txt;
string val;
public Form1()
{
InitializeComponent();
txt = (TextBox)numericUpDown1.Controls[1];//notice the textbox is the 2nd control in the numericupdown control
txt.TextChanged += new EventHandler(txt_TextChanged);
txt.Validating += new CancelEventHandler(txt_Validating);
}
void txt_TextChanged(object sender, EventArgs e)
{
if (txt.Focused) //don't save the value unless the textbox is focused, this is the new trick
val = txt.Text;
}
void txt_Validating(object sender, CancelEventArgs e)
{
MessageBox.Show("Val: " + val);
}
}
EDIT#2
#Carlos_Liu: If you need the entered value to be kept, still there is a trick for doing so: # the Validating event of the textbox, check the value, if it is not within the range, cancel loosing the focus!
Here is a new version of the code:
public partial class Form1 : Form
{
TextBox txt;
string val;
public Form1()
{
InitializeComponent();
txt = (TextBox)numericUpDown1.Controls[1];
txt.TextChanged += new EventHandler(txt_TextChanged);
txt.Validating += new CancelEventHandler(txt_Validating);
}
void txt_TextChanged(object sender, EventArgs e)
{
if (txt.Focused)
val = txt.Text;
}
void txt_Validating(object sender, CancelEventArgs e)
{
int enteredVal = 0;
int.TryParse(val, out enteredVal);
if (enteredVal > numericUpDown1.Maximum || enteredVal < numericUpDown1.Minimum)
{
txt.Text = val;
e.Cancel = true;
}
}
}

passing variables into another form

I am developing a windows app in c#. I have used three decimal variables: counter, narrow, and broad which store different values based on some calculations.
On clicking a button, a message box is displayed showing these three decimal values and then the application exits..
Now I want to add another form having three labels in which these variable values needs to be shown. Please explain, how can I pass those variables in the next form to display in individual labels?
One method is to create a new constructor in the 2nd form. THen you can use those values from the 2nd form.
public Form2(decimal x, decimal y, decimal z):this()
{
this.TextBox1.Text = Convert.ToString(x);
this.Label1.Text = Convert.ToString(y);
etc...
};
From main form
Form2 frm2 = new Form2(x,y,z);
frm2.Show();
Create a new Form...
public class CalculationResultForm : Form
{
public CalculationResultForm(){}
public decimal Counter
{
set { labelCounter.Text = value.ToString(); }
}
public decimal Broad
{
set { labelBroad.Text = value.ToString(); }
}
public decimal Narrow
{
set { labelNarrow.Text = value.ToString(); }
}
private void OkButton_Click(object sender, EventArgs e)
{
// This will close the form (same as clicking ok on the message box)
DialogResult = DialogResult.OK;
}
}
Then within your existing form button click handler...
private void MyButton_Click(object sender, EventArgs e)
{
CalculationResultForm resultForm = new CalculationResultForm();
resultForm.Counter = _counter;
resultForm.Narrow = _narrow;
resultForm.Broad = _broad;
resultForm .ShowDialog();
Application.Exit();
}
The easiest way is to probably add a new method, lets call it ShowWithDetails:
public void ShowWithDetails(double Counter, double Narrow, double Broad)
{
CounterLabel.Text = Counter.ToString();
NarrowLabel.Text = Narrow.ToString();
BroadLabel.Text = Broad.ToString();
ShowDialog();
}
An easy way is to use properties. The form you want to pass the values to is just another class.
add something like this to the second form:
public int counter {get; set;}
then from the first form you'd do something along the lines of
Form2 form2 = new Form2();
form2.counter = 1;
form2.ShowDialog();
or something along those lines.
There is a blog post describing how to do this without using ShowDialog().

Categories