我有以下代码作为弹出对话框,该对话框从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);
答案 0 :(得分:1)
用户单击确定按钮后,必须将textbox.text值分配回input1和input2
答案 1 :(得分:0)
我对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模式可能会使这些类型的属性及其相应值的维护(和创建)更加容易。