У меня две формы Form1 и Form2.
при нажатии кнопки Form1 я хочу открыть форму2, в которой да и нет кнопок в форме2.
Когда пользователь нажимает кнопку "да", текстовое поле формы1 должно отображать значение в текстовом поле form1. Я сделал следующее:
В Form1
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Alert AlertObj = new Alert();
string a=AlertObj.Text.Length.ToString();
string val=Alert.buttonVal();
AlertObj.Show();
if (val == "Yes")
textBox1.Text = val;
else
textBox1.Text = "No";
}
}
по форме 2
public partial class Alert : Form
{
public Alert()
{
InitializeComponent();
}
public static string result = string.Empty;
private void button1_Click(object sender, EventArgs e)
{
result = "Yes";
Form1 obj = new Form1();
this.Close();
}
public static string buttonVal()
{
return result;
}
}
Есть более простые способы сделать это. Но, как вы спросили:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Alert AlertObj = new Alert();
if (AlertObj.ShowDialog() == DialogResult.Yes)
textBox1.Text = AlertObj.ResultText ;
else
textBox1.Text = "No";
}
}
public partial class Alert : Form
{
public Alert()
{
InitializeComponent();
}
public string ResultText {get; set;}
private void button1_Click(object sender, EventArgs e)
{
ResultTest = "Yes";
DialogResult = DialogResult.Yes;
}
}
DialogResult
закроет форму автоматически. Не надо его закрывать
Вы можете сделать это, используя overloaded constructor
, передав его. Reference
Form1 TextBox
Форма 1 Код:
private void button1_Click(object sender, EventArgs e)
{
Alert AlertObj = new Alert(Ref textBox1);
AlertObj.ShowDailog();
}
Код формы 2:
public partial class Alert : Form
{
TextBox txt;
public Alert()
{
InitializeComponent();
}
public Alert(Ref TextBox txt1)
{
InitializeComponent();
txt=txt1;
}
private void button1_Click(object sender, EventArgs e)
{
txt.Text ="Yes";
this.Close();
}
}
Text
. Целью Alert
является возвращаемое значение. Не обновлять другие элементы управления формы
MessageBox
с кнопкамиYes
иNo
??