c# - 如何使用 Form.ShowDialog?

标签 c#

private void button2_Click(object sender, EventArgs e)
        {
            ChangeLink cl = new ChangeLink();
            // Show testDialog as a modal dialog and determine if DialogResult = OK.
            if (cl.ShowDialog() == DialogResult.OK)
            {
                // Read the contents of testDialog's TextBox. 
               // cl.AcceptButton.DialogResult = DialogResult.OK;
                this.label4.Text = cl.textBox1Text;
            }
            else
            {
                this.label4.Text = "Cancelled";
            }
            cl.Dispose();

        }

当我单击该按钮时,我会看到新窗体和新窗体中的 textBox1。我可以在 textBox1 中输入一些东西,但是我在任何地方都看不到 OK 或 CANCEL 按钮。我应该在新的表单设计器中手动添加它们吗?那么如何使用它们呢?

这是我新表单中的代码,我想做的是在新表单 textBox1 中键入一些内容,并将 textBox1 中的文本传递给 Form1 label4。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace GatherLinks
{
    public partial class ChangeLink : Form
    {
        public ChangeLink()
        {
            InitializeComponent();


        }

        public string textBox1Text
        {
            get
            {
                return textBox1Text = textBox1.Text;
            }
            set
            {
               
            }
        }
    }
}

那么 Form.ShowDialog 的 OK 和 CANCEL 按钮在哪里?

最佳答案

您需要自己添加它们,您可以将按钮添加到您的 Form 并设置它们的 DialogResult属性(property)。这将返回 DialogResult 并关闭窗体,而无需连接任何代码。下面是一个使用方法返回 Form2 上文本框值的示例(Form2 上有两个按钮,它们的 DialogResults 分别设置为 Cancel 和 Ok)。

Form1

public partial class Form1 : Form
{
    Form2 frm2;
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        frm2 = new Form2();
        DialogResult dr = frm2.ShowDialog(this);
        if (dr == DialogResult.Cancel)
        {
            frm2.Close();
        }
        else if (dr == DialogResult.OK)
        {
            textBox1.Text = frm2.getText();
            frm2.Close();
        }
    }
}

Form2

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

    public string getText()
    {
        return textBox1.Text;
    }
}

关于c# - 如何使用 Form.ShowDialog?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12444086/

相关文章:

C# MySql 创建用户

c# - 无法将 T 与 K 相加,因为它返回 T(或数字的通用)

c# - 通用约束,其中 T : struct and where T : class

c# - 如何在 .Net S3 SDK 中按名称获取存储桶?

c# - ASP.Net Core View 作为弹出框

c# - 将 C++ 转换为 C#

c# - 为共享点项目创建类库

c# - 在字符串而不是字符上拆分字符串

c# - 在 wpf 中关闭窗口时是否必须取消订阅事件?

c# - Linq 查询以在列表 c# 的列表中过滤 id