Click to see problem explain by Image 我有两种形式...... 在form1上有一个提交按钮,当按下form2时应该打开用户名文本框和提交按钮.... 当用户按下提交按钮时,form1将再次出现,按钮文本将更改为用户名,并且将出现新的注册按钮....
它适用于第一次按,但在第二个按钮按下第一个按钮文本转到默认文本,如何解决这个问题?
第1课
namespace Internship_Test
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public string b;
public Form1(Form2 obj)
{
InitializeComponent();
if(button1.Name == obj.b2)
{
button1.Text = obj.username;
button2.Visible = true;
}
else if(button2.Name == obj.b2)
{
button2.Visible = true;
button2.Text = obj.username;
button3.Visible = true;
}
else if (button3.Name == obj.b2)
{
button2.Visible = true;
button3.Visible = true;
button3.Text = obj.username;
button4.Visible = true;
}
else if (button4.Name == obj.b2)
{
button2.Visible = true;
button3.Visible = true;
button4.Visible = true;
button4.Text = obj.username;
button5.Visible = true;
}
else if (button4.Name == obj.b2)
{
button2.Visible = true;
button3.Visible = true;
button4.Visible = true;
button5.Visible = true;
button5.Text = obj.username;
}
}
private void button1_Click(object sender, EventArgs e)
{
this.b = ((Button)sender).Name;
Form2 obj = new Form2(this);
obj.ShowDialog();
this.Hide();
}
}
}
第2课
namespace Internship_Test
{
public partial class Form2 : Form
{
string[] user = new string[5];
public Form2()
{
InitializeComponent();
}
public string b2;
public Form2(Form1 obj)
{
InitializeComponent();
b2 = obj.b;
}
public string username;
private void button1_Click(object sender, EventArgs e)
{
username = textBox2.Text;
Form1 obj = new Form1(this);
obj.Show();
this.Hide();
}
}
}[Click to see problem explain by Image ][1]
答案 0 :(得分:1)
作为对你的问题/错误的回应,像Mong Zhu指出的那样:
您的错误可在此处找到:
class 2
namespace Internship_Test
{
public partial class Form2 : Form
{
string[] user = new string[5];
public Form2()
{
InitializeComponent();
}
public string b2;
private Form1 _form1; // you need to create a field for the form1
public Form2(Form1 form1)
{
InitializeComponent();
b2 = obj.b;
_form1 = form1;
}
public string username;
private void button1_Click(object sender, EventArgs e)
{
username = textBox2.Text;
//Form1 obj = new Form1(this);
// instead of creating a new form, just pop it up:
_form1?.Show();
this.Hide();
}
}
}
您应该将obj.ShowDialog();
更改为obj.Show();
答案 1 :(得分:0)
有些问题:
我会像:
那样实现它public class Form1 : Form
{
private void button1_Click(object sender, EventArgs e)
{
using(var form2 = new Form2())
{
// if you want to fill the username before popup..
// do it here:
// form2.UserName = textBox2.Text;
var result = form2.ShowDialog();
if(result != DialogResult.OK)
return;
textBox2.Text = form2.UserName;
}
}
}
public class Form2 : Form
{
public string UserName
{
get { return textBox1.Text; }
set { textBox1.Text = value; }
}
}