動態改變另一個類的標籤值 (Dynamically changing the value of a label from another class)


問題描述

動態改變另一個類的標籤值 (Dynamically changing the value of a label from another class)

我創建了自己的 MessageBox 類。這很簡單,它有一個標籤和一個關閉它的按鈕。

在我的 System_Functions 類中,我正在驗證用戶名是否存在:

Prompt prompt = new Prompt();
...
if (checkUsername == 0) {
                    prompt.Show();
                    return false;
                }

Prompt 類包含自定義消息框。但是,我不知道如何動態更改標籤,因為我還計劃在其他警告中使用它。

我知道代碼應該是 label.Text="在此處插入字符串"; 但我知道如何實現它。我使用 prompt.Show(); 來顯示自定義消息框,但是如何傳遞參數?

這是我的 Prompt 類,我還沒有添加一個方法接受字符串參數來更改標籤:

public partial class Prompt : Form {
        public Prompt() {
            InitializeComponent();
        }

        private void btnOk_Click(object sender, EventArgs e) {
            this.Hide();
        }
    }

參考解法

方法 1:

This could be one way:

public partial class Prompt : Form {   

            public Prompt(string message) {
                InitializeComponent();
                this.labelforMessage.Text = message;   // Use this string as label text
            }

            private void btnOk_Click(object sender, EventArgs e) {
                this.Hide();
            }
        }

Then from other classes you can Pass the message when you create the Prompt object. Remember C# BCL does similar in MessageBox.Show() method and its overloads

(by d2680837_cPrateek Shrivastava)

參考文件

  1. Dynamically changing the value of a label from another class (CC BY‑SA 2.5/3.0/4.0)

#visual-studio #C#






相關問題

如何在 C# 中使用帶有動態參數的 INSERT INTO SQL 查詢? (How to use a INSERT INTO SQL Query with Dynamic parameters in C#?)

擴展 SSRS 中的圖表功能 (Extending chart functionality in SSRS)

如何將 MVC 5 項目模板添加到 VS 2012? (How can I add the MVC 5 project template to VS 2012?)

Visual Studio - 將按鈕/複選框添加到工具欄以切換只讀文件屬性, (Visual Studio - Add a button/checkbox to a toolbar to switch the readonly file property,)

在 Javascript/Jquery Ajax 調用中使用 WCF 服務 (Consuming WCF service in Javascript/Jquery Ajax call)

Visual Basic 2013 - 控制台輸入令牌? (Visual Basic 2013 - Console Input Tokens?)

您是否知道用於編輯/翻譯資源(.rc)文件的好的程序? (Do you know of a good program for editing/translating resource (.rc) files?)

ADODB.Recordset 數據無法綁定到 datagridview (ADODB.Recordset data cannot bind into datagridview)

Reporting Services - 對數據源視圖 (DSV) 的報表模型 (SDML) 引用 (Reporting Services - Report Model (SDML) reference to Data Source View (DSV))

從 Visual Studio 2005 遷移到 2008 時要注意什麼? (What to look out for when moving from Visual Studio 2005 to 2008?)

動態改變另一個類的標籤值 (Dynamically changing the value of a label from another class)

在同一文件夾中為 .NET 5 和 .NET 6 Preview 3 構建 WebAssembly 項目 (Building WebAssembly project for both .NET 5 and .NET 6 Preview 3 in same folder)







留言討論