首頁 >後端開發 >C++ >在 Windows 窗體中,如何將字串值從子窗體傳遞到其父窗體?

在 Windows 窗體中,如何將字串值從子窗體傳遞到其父窗體?

Susan Sarandon
Susan Sarandon原創
2025-01-07 18:51:41849瀏覽

How to Pass a String Value from a Child Form to its Parent Form in Windows Forms?

在 Windows 窗體中有效率地將資料從子窗體傳送到父窗體

本指南示範了在 Windows 窗體應用程式中將字串資料從子窗體傳回其父窗體的簡單方法。這是許多應用程式中的常見要求。

場景: 父表單使用 FormOptions 開啟子表單 (ShowDialog())。 目標是在子窗體關閉後從子窗體中檢索字串值。 父表單的初始程式碼可能如下所示:

<code class="language-csharp">FormOptions formOptions = new FormOptions();
formOptions.ShowDialog();</code>

解決方案:解決方案包括在子表單中新增一個公共屬性來保存字串值。 子窗體關閉後,父窗體將存取此屬性。

實作:

為您的 FormOptions 類別新增公共屬性:

<code class="language-csharp">public string ResultString { get; set; }</code>

在子窗體的程式碼中,在關閉之前設定 ResultString 屬性:

<code class="language-csharp">// ... some code in your child form ...

this.ResultString = "Your String Value Here"; // Set the value before closing
this.Close();</code>

然後父表單可以擷取值:

<code class="language-csharp">using (FormOptions formOptions = new FormOptions())
{
    formOptions.ShowDialog();

    string receivedValue = formOptions.ResultString;

    // Use the receivedValue variable...
    MessageBox.Show("Received Value: " + receivedValue);
}</code>

這個改進的範例清楚地展示瞭如何設定和檢索字串值,提高了表單之間資料傳輸的清晰度和效率。 using 語句確保正確的資源管理。

以上是在 Windows 窗體中,如何將字串值從子窗體傳遞到其父窗體?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn