【问题标题】:System.Windows.Forms.TextBox does not change ref textSystem.Windows.Forms.TextBox 不会更改参考文本
【发布时间】:2018-09-06 19:36:52
【问题描述】:

我有以下代码作为从 inputBox 获取输入的弹出对话框。我传入字符串作为参考,希望参考字符串会在对话框关闭时发生变化,这样我就可以获得用户输入。但是传入的字符串在对话框关闭时没有改变。我做错了什么?

public static DialogResult ShowInputDialog(ref string input1, ref string input2)
{
    var size = new System.Drawing.Size(520, 180);
    var inputBox = new Form { ClientSize = size };

    var panel = new TableLayoutPanel
    {
        Size = new System.Drawing.Size(460, 180),
        Location = new System.Drawing.Point(25, 15),
        ColumnCount = 2,
        RowCount = 3
    };

    // Add ColumnStyles/RowStyles here

    panel.Controls.Add(new Label { Text = "Input 1", TextAlign = ContentAlignment.BottomRight }, 0, 0);
    panel.Controls.Add(new Label { Text = "Input2", TextAlign = ContentAlignment.BottomRight }, 0, 1);
    panel.Controls.Add(new TextBox { Text = input1, Width = 280 }, 1, 0);
    panel.Controls.Add(new TextBox { Text = input2, Width = 280 }, 1, 1);
    var okButton = new Button{ DialogResult = DialogResult.OK};
    var cancelButton = new Button {DialogResult = DialogResult.Cancel};

    var buttons = new FlowLayoutPanel();
    buttons.Controls.Add(okButton);
    buttons.Controls.Add(cancelButton);
    panel.Controls.Add(buttons, 1, 3);
    inputBox.Controls.Add(panel);

    inputBox.AcceptButton = okButton;
    inputBox.CancelButton = cancelButton;

    var result = inputBox.ShowDialog();
    return result;
}

以上代码的用法是:

string input1 = string.Empty; 
string input2 = string.Empty;
ShowInputDialog(ref input, ref input2);

【问题讨论】:

  • 如果您使用设计器创建表单,然后设置一些属性来检索您的信息,您的生活会简单得多。

标签: c# winforms dialog inputbox


【解决方案1】:

用户点击确定按钮后,您必须将 textbox.text 值分配回 input1 和 input2

【讨论】:

    【解决方案2】:

    我对@9​​87654321@ 不太熟悉,但也许你可以做一些简单的事情:

     if (inputBox.ShowDialog() == DialogResult.OK)
     {
        input1 = (panel.GetControlFromPosition(1, 0) as TextBox).Text;
        input2 = (panel.GetControlFromPosition(1, 1) as TextBox).Text;
        return DialogResult.OK;
     }
    
     return DialogResult.Cancel;
    

    您目前的问题是您实际上并没有在对话框关闭后的任何地方设置值。

    但是,我同意该评论。一种 MVVM 模式可能会使这些类型的属性及其各自值的维护(和创建)变得更加容易。

    【讨论】: