C# System.Windows.Forms.TextBox不更改参考文本
我有以下代码作为一个弹出对话框,从inputBox获取输入。我传入字符串作为引用,希望在对话框关闭时引用字符串会改变,这样我就可以获得用户输入。但在对话框关闭时传入的字符串没有更改。我做错了什么C# System.Windows.Forms.TextBox不更改参考文本,c#,winforms,dialog,inputbox,C#,Winforms,Dialog,Inputbox,我有以下代码作为一个弹出对话框,从inputBox获取输入。我传入字符串作为引用,希望在对话框关闭时引用字符串会改变,这样我就可以获得用户输入。但在对话框关闭时传入的字符串没有更改。我做错了什么 public static DialogResult ShowInputDialog(ref string input1, ref string input2) { var size = new System.Drawing.Size(520, 180); var 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);
我对TableLayoutPanel不太熟悉,但也许您可以做一些简单的事情:
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模式可能会使维护和创建这些类型的属性及其各自的值变得更加容易。用户单击“确定”按钮后,您必须将textbox.text值重新分配给input1和input2如果您使用设计器创建表单,然后设置一些属性来检索信息,您的生活会简单得多。