Reputation: 35
I would like to put a string value in my frmCredentials.txtUsername
text box when the form first loads.
Here is the code where the form is first called:
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new frmCredentials());
Upvotes: 2
Views: 27971
Reputation: 4104
Mohit probably has the best answer, but if you ONLY want to be able to create a form with the textbox you don't need to retain the 'default' constructor as he/she did:
public class frmCredentials : Form
{
public frmCredentials(string myValue)
{
InitializeComponent();
txtUsername.Text = myValue;
}
}
Now when you call a new frmCredentials, you'll have to pass it a string, like so
var myForm = new frmCredentials("A string is required.");
Upvotes: 1
Reputation: 31
Yes Form load event is better to load default values when loading the Form
private void Form1_Load(object sender, EventArgs e)
{
txtUsername.Text = "My Username";
}
Upvotes: 2
Reputation: 115
You can create an overloaded constructor that accepts one parameter, and another one will be your default constructor.
public class frmCredentials : Form
{
public frmCredentials()
{
InitializeComponent();
}
public frmCredentials(string myValue )
{
InitializeComponent();
txtUsername.Text = myValue;
}
}
from your code:
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new frmCredentials("Hello World"));
Upvotes: 3
Reputation: 6980
Step 1) Double Click On Your Form: This will create and display the form load event.
Step 2) Type in the {} the following,
txtUsername.Text="MyTextGoesHere";
After you try this if this still does not resolve your homework please comment below and I will try to help further.
Upvotes: 2
Reputation: 66439
You could set it in the constructor of frmCredentials:
public class frmCredentials : Form
{
public frmCredentials()
{
InitializeComponent();
txtUsername.Text = "whatever";
}
}
Upvotes: 1
Reputation: 166336
Why not put the code in the Form.Load event
Occurs before a form is displayed for the first time.
You can use this event to perform tasks such as allocating resources used by the form.
Upvotes: 4