[英]C# - Display instantly a string in textbox coming from a different form
I'm in the 1st form, so I want to pass the ID to the 2nd Form and display it there in a textbox. 我处于第一种形式,所以我想将ID传递给第二种形式并将其显示在文本框中。 So I did this. 所以我做到了。
In form 1:Assume inside using{} 在表格1中:假设内部使用{}
public partial class First_Form: Form
{
public void test(){
Main_Menu_Form f2 = new Main_Menu_Form();
f2.selectedid = id;
f2.Show();
}
}
In form 2: Assume inside using{} 在表格2中:假设内部使用{}
public partial class Main_Menu_Form: Form
{
public int selectedid;
public Main_Menu_Form()
{
InitializeComponent();
textbox1.Text = selectedid;
}
}
What I want is when I opened the new Form (Form2) I want to display the selected id immediately in the form2 textbox as the Form2 loads. 我想要的是当我打开新的Form(Form2)时,要在加载Form2时立即在form2文本框中显示选定的ID。 I don't know whats wrong with this, this should display because when I tried to place textbox1.Text = selectedid; 我不知道这有什么问题,应该显示出来,因为当我尝试放置textbox1.Text = selectedid; , it will work. ,它将起作用。 But on form initialization or load, It won't. 但是在表单初始化或加载时,它不会。
Form 2: I tried also this but won't work 表格2:我也尝试过此方法,但无法正常工作
private void Main_Menu_Form_Load(object sender, EventArgs e)
{
textbox1.Text = selectedid;
}
One way to do this is to create a public property in Form2
for the selected id, and in the Form_Load
event, set the Text
property of the textbox to that value: 一种方法是在Form2
为选定的ID创建一个公共属性,然后在Form_Load
事件中,将Text
框的Text
属性设置为该值:
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public int SelectedId { get; set; }
private void Form2_Load(object sender, EventArgs e)
{
textBox1.Text = SelectedId.ToString();
}
}
Then in Form1
, you set the value of that property and show the form (I'm using a button Click
event): 然后在Form1
,设置该属性的值并显示该表单(我正在使用按钮Click
事件):
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var f2 = new Form2();
f2.SelectedId = 100;
f2.Show();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.