i have a form with a panel in it and when a button is presed a usercontrol showes and the panel hides, now i need to hide a button if the textbox in the form1 contains "admin" in it. this is the form1 code
public partial class Form1 : Form
{
public string a;
public Form1()
{
InitializeComponent();
a = textBox1.Text;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
panel1.Controls.Clear();
afterlogin v = new afterlogin();
v.Dock = DockStyle.Fill;
panel1.Controls.Add(v);
v.BringToFront();
}
}
and this is the usercontrol code
public partial class afterlogin : UserControl
{
public afterlogin()
{
InitializeComponent();
Form1 f = new Form1();
if (f.a.Contains("admin"))
{
button1.Hide();
}
}
}
CodePudding user response:
You're creating a new form in the user control, it will not have the same values as the original form you created your user control in. If you wish to take in values from the form, add a constructor parameter to the "afterlogin" class with text of the textbox, such as:
public afterlogin(string text)
{
InitializeComponent();
if (text.Contains("admin"))
{
button1.Hide();
}
}
and pass the text value to the constructor of the "afterLogin" class:
afterlogin v = new afterlogin(a);
CodePudding user response:
Since Form1 creates the UserControl, just have the Form itself turn on or off the Button?
You can make a method in your UserControl that allows you to change the visibility of the control:
public partial class afterlogin : UserControl
{
public void setButton(bool state)
{
button1.Visible = state;
}
}
Now you can call setButton
when you create the UserControl:
private void button1_Click(object sender, EventArgs e)
{
panel1.Controls.Clear();
afterlogin v = new afterlogin();
v.Dock = DockStyle.Fill;
panel1.Controls.Add(v);
v.BringToFront();
v.setButton(!textBox1.Text.Contains("admin"));
}