I have a main Form with an event to open another Form.
Inside the first Form I define the event like this:
private void softToolStripMenuItem_Click(object sender, EventArgs e)
{
_frmSetting = new frmSetting();
_frmSetting.ShowDialog();
}
The event open a Form in the Dialog box. Everything is ok.
Inside the Form2 before the InitializeComponent();, I want to change the content of a TextBox on the Form 2.
So I do this this.textBox1.Text = "New text"; but it didn't work then I output to console:
this.textBox1.Text = "New text";
System.Console.WriteLine(this.textBox1.Text);
But this takes effect when immediately when the Form1 starts..I can see the console output.
Normally the Console output were supposed to ve viewed only when I call Form2.
Does someone understand my needs?
EDIT
public form2()
{
InitializeComponent();
try
{
this.txtServer = new TextBox();
//this._parameter = new Parameter();
//this._get_parameter = new Dictionary<string, string>();
String _server_name;
//this._parameter.get_db_connection_parameters().TryGetValue("server", out _server_name);
this.txtServer.Text = _server_name.ToString();
System.Console.WriteLine(txtServer.Text + "---");
}
catch (Exception er) { System.Console.WriteLine("An error occurs :" + er.Message + " - " + er.StackTrace); }
}
Please don't bother about the commented lines, it works _server_name variable is getting its value from a text file and it works at this stage. The problem is around this line:
this.txtServer.Text = _server_name.ToString();
You're overcomplicating this. First, as others have said, you can't do it before the call to InitializeComponent. Also, you don't need to create a new text box after the call to InitializeComponent. Once that method has been called, the txtServer text box will already be created and properly initialized. All you need to do then is set the value of its Text property:
public form2()
{
InitializeComponent();
try
{
String _server_name;
// set value of _server_name
txtServer.Text = _server_name;
}
catch (Exception er) { System.Console.WriteLine("An error occurs :" + er.Message + " - " + er.StackTrace); }
}
You can't set any values to textbox before initializeComponent();. If you look into initializeComponent function, you will see, that it does initialize all controls added in designer and your textbox as well.
You can't set the TextBox.Text property before initialisation, it will fail, that's it.
Many thanks to all,
everything works fine now. In fact, I was initialising Form2 in Form1() constructor and was getting this error Object reference to non object initialising (something like that).
I move it here:
private void softToolStripMenuItem_Click(object sender, EventArgs e)
{
_frmSetting = new frmSetting();
_frmSetting.ShowDialog();
}
and now inside the Form2() after initializeComponent()
I just do this
this.txtServer = _server_name;
and it works
Related
Using VS 2015 and C#...
I have this simple modal Form with just a MaskedTextBox control on it.
Each time after the first that ModalForm is shown with .ShowDialog(), the PromptChar in the control is gone.
To reproduce this issue:
public ModalForm()
{
InitializeComponent();
maskedTextBox1.Mask = "00/00/0000"; // happens with any
maskedTextBox1.TextMaskFormat = MaskFormat.IncludeLiterals;
}
Code for main Form:
public partial class Form1 : Form
{
private ModalForm modalForm = new ModalForm();
private void button1_Click(object sender, EventArgs e)
{
modalForm.ShowDialog();
}
}
The control's prompt appears again when its content changes, but at first view isn't present.
Setting the TextMaskFormat property to IncludePromptAndLiterals could be a solution, but then, .Text has to be cleaned up.
Is there another way to handle this?. Has become necessary for me, that all MaskedTextBox controls must always show its default prompt.
Try this on Form's Shown event,
private void ModalForm_Shown(object sender, EventArgs e){
if (!maskedTextBox1.MaskCompleted) // if there is missing parts it will return false, every false means prompts need in control
{
string tempText = maskedTextBox1.MaskedTextProvider.ToDisplayString(); // get the last value with prompts
maskedTextBox1.Text = "";
maskedTextBox1.Text = tempText; // then set the last value.
}
}
Hope helps,
I have looked at various answers, i have googled my nut off for a good few hours now, and still cant seem to get this to work.
I am trying to update a textbox on a form. i have simplified the code i am using in the hope that it was just something i was adding unnecessarily, but still cant get it to work.
I know the text is being passed to the textbox and stored in the box, but it will not display in the actual box.
In form one (Form_DMM);
private void BtnTest_Click(object sender, EventArgs e)
{
ErrorHandling EH = new ErrorHandling();
EH.updatetbtest();
}
in separate class;
public void updatetbtest()
{
string FailedMessagePB = "Test Message" + "\n";
Form_DMM FormDMM = new Form_DMM();
FormDMM.TextBoxAppend(FailedMessagePB);
FormDMM.TextBoxAppend2 = FailedMessagePB;
FormDMM = null;
}
passed back to form one;
public void TextBoxAppend(string WriteMessage)
{
TB_Issues.AppendText(WriteMessage + "\n");
System.Windows.Forms.Application.DoEvents();
TB_Issues.Invalidate();
TB_Issues.Update();
TB_Issues.Refresh();
MessageBox.Show(TB_Issues.Text);
}
public string TextBoxAppend2
{
get
{
return TB_Issues.Text;
}
set
{
TB_Issues.Text = TB_Issues.Text + value + "\n";
System.Windows.Forms.Application.DoEvents();
TB_Issues.Invalidate();
TB_Issues.Update();
TB_Issues.Refresh();
MessageBox.Show(TB_Issues.Text);
}
}
As you can see i have two separate attempts at updating the textbox, neither of which will display the test message in the textbox, but the messagebox that pops up will show the test message. it will even show the double test message from the TB_Issues.AppendText().
Can someone please help and tell me where i'm going wrong. This is driving me insane!
you can use like this
public void updatetbtest(Form_DMM FormDMM)
{
string FailedMessagePB = "Test Message" + "\n";
FormDMM.TextBoxAppend(FailedMessagePB);
FormDMM.TextBoxAppend2 = FailedMessagePB;
}
and in your buttontest_Click
private void BtnTest_Click(object sender, EventArgs e)
{
ErrorHandling EH = new ErrorHandling();
EH.updatetbtest(this);
}
From the problem posted the error is in the ErrorHandling class.
In the method updatetbtest you create a new Insance of the form object. So you create a separate form object, change the text and then you lose any reference because you set the variable to null. The message box is displayed because the TextBoxAppend method is called and the messagebox is a separate instance. The new instance you create is never displayed.
You have to hand over your calling form instance to the updatetbtest method.
Something like this:
private void BtnTest_Click(object sender, EventArgs e)
{
ErrorHandling EH = new ErrorHandling();
EH.updatetbtest(this);
}
public void updatetbtest(Form_DMM form)
{
string FailedMessagePB = "Test Message" + "\n";
form.TextBoxAppend(FailedMessagePB);
}
You try to create new form. But you must use existing.
You can pass existing form calling EH.updatetbtest(this);
And of course adding parameter to declaration like updatetbtest(Form_DMM FormDMM). And delete declaration and new in the function body.
I have a form with a tab control on it, and on one of these tabs, I have a ComboBox. Depending on the value the user selects in this ComboBox, different controls need to populate. This is working fine, however, when I attempt to retrieve the text the user has put into a TextBox control that I have populating, TextBox.Text returns nothing to me. TextBox.Text works fine when I add a TextBox to the same form, but include it in the form initialization (rather than populating it on the form later with the method below), which makes me think I am missing a property on the control.
I am not wanting to populate the control with text in it, I want the string that the user enters in runtime - I want to use TextBox.Text to obtain that value, not the value of a string I already have in the control.
Snippet from the method I'm using to populate the TextBox and other controls onto the tab control:
private System.Windows.Forms.TextBox filePathBox;
private void populateControls(string someText)
{
if (someText == "Something")
{
//
// TextBox
//
this.filePathBox.Location = new System.Drawing.Point(6, 61);
this.filePathBox.Name = "filePathBox";
this.filePathBox.Size = new System.Drawing.Size(220, 20);
this.tabPage1.Controls.Add(this.filePathBox);
this.filePathBox.Show();
}
else if (someText == "SomethingElse")
{
//populate other controls.
}
}
And, to test, I have a button that simply displays a MessageBox of the string that is in the TextBox, which results in nothing.
private void button2_Click(object sender, EventArgs e)
{
MessageBox.Show(filePathBox.Text);
}
Again, it makes me think I am missing some properties from the TextBox, but anything would be appreciated at this point.
change your:
this.filePathBox = new TextBox();
to:
if(this.filePathBox==null)
{
this.filePathBox = new TextBox();
}
I suppose you correctly initialized filePathBox in your InitializeComponents() (form designer content) so... the filePathBox.Text will be initially empty. You have to fill it with content before it shows something... like this:
filePathBox.Text = "something";
MessageBox.Show(filePathBox.Text);
I created a quick sample and saw no issues. Make sure your constructor calls InitializeComponents,hope this helps
private System.Windows.Forms.TextBox filePathBox = new TextBox();
public Form1()
{
InitializeComponent();
PopulateControls("Something");
}
public void PopulateControls(string someText)
{
if (someText == "Something")
{
this.filePathBox.Location = new System.Drawing.Point(6, 61);
this.filePathBox.Name = "filePathBox";
this.filePathBox.Size = new System.Drawing.Size(220, 20);
this.tabPage1.Controls.Add(this.filePathBox);
this.filePathBox.Show();
}
}
private void button1_Click(object sender, EventArgs e)
{
if (filePathBox != null)
{
MessageBox.Show(filePathBox.Text);
}
}
I was not able to locate an answer on stackoverflow so here it goes. I am attempting to change the text of a MenuStrip subitem when clicking a button on a sub form. Below is the code from my Submit button on my sub form. when clicked it should change the text of "Log In" to "Log Out". Code seems fine and no errors but does not update the text.
public AccessForm()
{
InitializeComponent();
}
private void btnSubmit_Click(object sender, EventArgs e)
{
try
{
if (txtUser.Text == "admin" && txtPass.Text == "1234")
{
MessageBox.Show("Access granted.", "Access");
playgroundPlannersForm mainForm = new playgroundPlannersForm();
mainForm.logInToolStripMenuItem.Text = "Log Out";
this.Close();
}
else
{
MessageBox.Show("Incorrect Username or Password.", "Warning");
txtUser.Clear();
txtPass.Clear();
txtUser.Focus();
}
}
catch (Exception ex)
{
MessageBox.Show("Message: " + ex, "Error");
}
}
private void btnCancel_Click(object sender, EventArgs e)
{
this.Close();
}
You're creating a new instance of the main form and changing that; you need to be passing along the reference to the original form and using that to update it.
Here's one way to do it. In your sub form.. add this property:
public playgroundPlannersForm ParentForm { get; set; }
..then, in your code above, use this:
MessageBox.Show("Access granted.", "Access");
//playgroundPlannersForm mainForm = new playgroundPlannersForm(); <--- not needed anymore
ParentForm.logInToolStripMenuItem.Text = "Log Out";
In your main form, before you show your subform.. do this:
SubForm subform = new SubForm();
subform.ParentForm = this;
subform.Show();
That sets the parent to the form that's creating it (which, according to your code, is the correct form). You may also need to go into your form designer code and make the loginToolStripMenuItem public (if it isn't already).
I am trying to set a condition that would change the writing inside the title bar...
But how do I change the title bar text?
For changing the Title of a form at runtime we can code as below
public partial class FormMain : Form
{
public FormMain()
{
InitializeComponent();
this.Text = "This Is My Title";
}
}
You can change the text in the titlebar in Windows Forms by using the Text property.
For C#
// This class is added to the namespace containing the Form1 class.
class MainApplication
{
public static void Main()
{
// Instantiate a new instance of Form1.
Form1 f1 = new Form1();
// Display a messagebox. This shows the application
// is running, yet there is nothing shown to the user.
// This is the point at which you customize your form.
System.Windows.Forms.MessageBox.Show("The application "
+ "is running now, but no forms have been shown.");
// Customize the form.
f1.Text = "Running Form";
// Show the instance of the form modally.
f1.ShowDialog();
}
}
All the answers that include creating an new object from Form class are absolutely creating new form. But you can use Text property of ActiveForm subclass in Form class. For example:
public Form1()
{
InitializeComponent();
Form1.ActiveForm.Text = "Your Title";
}
Since nobody has given a proper answer that doesn't use the keyword this over and over or the property window has been "uncluttered" so that nothing is there anymore, here is 2022 code in a WinForm .net core app that will change the text and display the form when you run it.
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form1 form = new Form1();
form.Text = "Your Text Here";
Application.Run( form);
}
public partial class Form1 : Form
{
DateTime date = new DateTime();
public Form1()
{
InitializeComponent();
}
private void timer1_Tick(object sender, EventArgs e)
{
date = DateTime.Now;
this.Text = "Date: "+date;
}
}
I was having some problems with inserting date and time into the name of the form. Finally found the error. I'm posting this in case anyone has the same problem and doesn't have to spend years googling solutions.
this.Text = "Your Text Here"
Place this under Initialize Component and it should change on form load.
If you want to update it later, once "this" no longer references it, I had some luck with assigning a variable to point to the main form.
static Form f0;
public OrdUpdate()
{
InitializeComponent();
f0=this;
}
// then later you can say
f0.Text="New text";