![Quote](images/metro/blue/misc/quote_icon.png)
Originally Posted by
Eisen Japhet Larnx
Good Evening mga programmers....
Does any of you here know how to access a textbox from another form?....
here's my codes:
private void dataGridView1_DoubleClick(object sender, EventArgs e)
{
CreateAccount acc = new CreateAccount();
acc.ShowDialog();
acc.txtcid.Text = dataGridView1.CurrentRow.Cells[0].Value.ToString();
acc.txtfname.Text = dataGridView1.CurrentRow.Cells[1].Value.ToString();
}
but txtcid and txtfname is inaccessible due to its protection level error...
Option 1
Make the access modifier to public - but I don't recommend this one, though it is easier, it is a bad programming practice.
If you really want to expose this member variable, expose it through a property. (I recommend read-only for this case)
Changing access modifiers of Form controls:
Go to NameOfForm.Designer.cs
you should see the member variable of the control like this (usually it is located at the bottom of the file. if i remember it correctly).
private System.Windows.Forms.TextBox nameOfTextBox; <-- change private to public.
Making a read-only property:
If you choose this, then just make a property.
e.g.
public TextBox NameOfTextBox
{
get { return nameOfTextBox; }
}
Option 2
Other way is, access it through Controls property.
e.g.
CreateAccount acc = new CreateAccount();
TextBox text1 = acc.Controls["nameOfTextBox"] as TextBox;
text1.Text = "desired value";
NOTE: This assumes that the textbox is directly under the form. if it is inside another control, you have to make another instance for that to access it.
Option 3
Or you can also pass the values through the form's constructor. Then in the constructor assign the values to the textBoxes. I'm guessing that everytime you double click the grid, a form will pop so this might work for you too.
This isn't accessing the control though, it is simply passing values to a form's control.
e.g.
CreateAccount acc = new CreateAccount(valForTxtbox1, valForTxtbox2);
acc.ShowModal();
in constructor:
public CreateAccount(string cid, string fname)
{
InitializeComponent();
txtCid.Text = cid;
txtfName.Text = fname;
}
So far that's what I can think of. I hope this will help.
Comment
By the way, judging from the given code. The codes highlighted in red will not be executed unless the acc is closed, because, ShowDialog makes acc modal and when it reaches ShowDialog, it will halt in that area. Meaning, the value you assigned in the textboxes will not be reflected. I suggest placing it before ShowDialog.
private void dataGridView1_DoubleClick(object sender, EventArgs e)
{
CreateAccount acc = new CreateAccount();
acc.ShowDialog();
acc.txtcid.Text = dataGridView1.CurrentRow.Cells[0].Value.ToString();
acc.txtfname.Text = dataGridView1.CurrentRow.Cells[1].Value.ToString();
}