C#,winform,ShowDialog,子窗體向父窗體傳值
2024-09-07 17:05:18
供稿:網友
調用showdialog方法后,調用代碼被暫停執行,等到調用showdialog方法的窗體關系后再繼續執行。而且窗體可以返回一個dialogresult值,他描述了窗體關閉的原因,例如OK,Cancel,yes,no等。為了讓窗體返回一個dialogresult,必須設置窗體的dialogresult值,或者在窗體的一個按鈕上設置dialogresult屬性。
例子:
下面是子窗體代碼,要求輸入phone,然后會返回給父窗體。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace WindowsApplication1
{
public partial class Phone : Form
{
public Phone()
{
InitializeComponent();
btnOK.DialogResult = DialogResult.OK;
btnOK.DialogResult = DialogResult.Cancel;
}
public string PhoneNumber
{
get { return textBox1.Text; }
set { textBox1.Text = value; }
}
private void Phone_Load(object sender, EventArgs e)
{
}
}
}
不包含任何處理按鈕單擊事件的代碼,因為設置了每個按鈕的dialogresult屬性,所以單擊OK或者Cancel按鈕后,窗體就消失了。下面的代碼顯示了父窗體中調用Phone對話框的方法。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace WindowsApplication1
{
public partial class Form7 : Form
{
public Form7()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)