I have created two forms in my Windows Application.
One Form acts as a Form and the other form acts as a MODAL DIALOG BOX.
The Form Dialog Box contains a button and One textBox. When this button is clicked the MODAL DIALOGBOX should be displayed. This dialog box also contains One Textbox and Two Buttons(Ok and Cancel).
Now when this dialog box is displayed the TextBox of the dialog box should contain the value entered in the textbox of Form1.
I have used the following coding to accomplish this task. Form1 Coding:
public string UserName;
private void btnFn_Click(object sender, EventArgs e)
{
UserName = txtUserName.Text;
frmFnC objFnC = new frmFnC();
objFnC.ShowDialog();
objFnC.txtUserName.Text = UserName;
}
Code in MODAL DIALOGBOX OK button:
Please note that the Cancel button is enabled only when the OK button is clicked.
Coding:
private void btnOk_Click(object sender, EventArgs e)
{
btnCancel.Enabled=true;
}
private void btnCancel_Click(object sender,EventArgs e)
{
this.Close();
}
The problem I am facing is the value entered by the User in the USERNAME textbox is not displayed in the TEXTBOX in the MODAL DIALOG BOX. Instead it is displaying the textbox as empty.
What should I do to get the values entered by the user in the textbox to this modal dialog box?
Can anybody help me out in performing the desired task?
Thanks in advance!!!
The problem you've got is that you're showing the dialog before you set the username.
//this shows your dialog
objFnC.ShowDialog();
//this won't happen until the dialog is closed
objFnC.txtUserName.Text = UserName;
Because the dialog is modal it won't go to the next line until the dialog is closed. You want to swap those lines round and it'll be fine.
//do this first
objFnC.txtUserName.Text = UserName;
//then show your dialog
objFnC.ShowDialog();
I'd like to point out that exposing the textbox publically isn't a really good idea though. You don't want the consumer to have implementational knowledge of your dialog.
It would be better if you added a parameter to the form constructor and then set the textbox text from within that. Then you could do the following:
//get the username
string userName = txtUserName.Text;
//create a new form passing in the username
frmFnC objFnC = new frmFnC(userName);
//display the form
objFnC.ShowDialog();
That way, the consumer isn't relying on frmFnC having a textbox named txtUserName which means you're free to change the inner workings of how you display the username. For example, you could change it to a label and you wouldn't break the consumer's code! All the consumer needs to know is that they should pass a username into the constructor.