如何在单击"确定"时返回值

raz*_*ser 2 c# prompt winforms

我创建了一个custimazibale提示符

public static class Prompt
{
    public static string ShowDialog(int columnnumber, string columnname)
    {
        Form prompt = new Form();
        prompt.Width = 500;
        prompt.Height = 150;
        prompt.FormBorderStyle = FormBorderStyle.FixedDialog;
        prompt.Text = columnname;
        prompt.StartPosition = FormStartPosition.CenterScreen;
        Label textLabel = new Label() { Left = 50, Top = 20 };
        ComboBox comboBox = new ComboBox() { Left = 50, Top = 50, Width = 400 };
        comboBox.Items.AddRange(new string[] { "a","b","c" });
        comboBox.DropDownStyle = ComboBoxStyle.DropDownList;
        comboBox.SelectedItem = columnname;
        Button confirmation = new Button() { Text = "Ok", Left = 350, Width = 100, Top = 80 };
        confirmation.Click += (sender, e) => { prompt.Close(); };
        textLabel.Text = "Colonne " + (columnnumber + 1).ToString() + " : " + columnname;
        prompt.Controls.Add(comboBox);
        prompt.Controls.Add(confirmation);
        prompt.Controls.Add(textLabel);
        prompt.AcceptButton = confirmation;
        prompt.ShowDialog();
        prompt.AcceptButton = confirmation;

        return comboBox.Text;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我在点击标题时以我的主窗体调用它

private void dataGridView1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
     dt.Columns[e.ColumnIndex].ColumnName = Prompt.ShowDialog(e.ColumnIndex, dataGridView1.Columns[e.ColumnIndex].Name);
}
Run Code Online (Sandbox Code Playgroud)

即使单击按钮关闭,问题仍然是我的文本更改.但是我希望它只在用户单击"确定"按钮时才能更改.

Chr*_*Fin 6

您可以评估DialogResult并返回,null如果不是OK:

public static class Prompt
{
    public static string ShowDialog(int columnnumber, string columnname)
    {
        using (Form prompt = new Form())
        {
            // other code
            return prompt.DialogResult == DialogResult.OK ? comboBox.Text : null;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在你的另一种方法:

private void dataGridView1_ColumnHeaderMouseClick(object sender, EventArgs e)
{
    var result = Prompt.ShowDialog(e.ColumnIndex, 
                                   dataGridView1.Columns[e.ColumnIndex].Name);
    if (result != null)
        dt.Columns[e.ColumnIndex].ColumnName = result;
}
Run Code Online (Sandbox Code Playgroud)

在你的内心prompt你应该相应地设置DialogResult:

confirmation.Click += (sender, e) =>
    {
        prompt.DialogResult = DialogResult.OK;
        prompt.Close();
    };
Run Code Online (Sandbox Code Playgroud)

提示:如果输入了某些内容,result != null您也可以使用!String.IsNullOrWhiteSpace(result)仅更新列名称.