c# – 如何使用Form.ShowDialog?

前端之家收集整理的这篇文章主要介绍了c# – 如何使用Form.ShowDialog?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
  1. private void button2_Click(object sender,EventArgs e)
  2. {
  3. ChangeLink cl = new ChangeLink();
  4. // Show testDialog as a modal dialog and determine if DialogResult = OK.
  5. if (cl.ShowDialog() == DialogResult.OK)
  6. {
  7. // Read the contents of testDialog's TextBox.
  8. // cl.AcceptButton.DialogResult = DialogResult.OK;
  9. this.label4.Text = cl.textBox1Text;
  10. }
  11. else
  12. {
  13. this.label4.Text = "Cancelled";
  14. }
  15. cl.Dispose();
  16.  
  17. }

当我点击按钮,我看到新的窗体和textBox1在新窗体,我可以输入textBox1的东西,但我没有看到任何一个OK或CANCEL按钮.我应该在新的表格设计师手册中添加它们吗?那么怎么用呢?

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

  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Windows.Forms;
  9.  
  10. namespace GatherLinks
  11. {
  12. public partial class ChangeLink : Form
  13. {
  14. public ChangeLink()
  15. {
  16. InitializeComponent();
  17.  
  18.  
  19. }
  20.  
  21. public string textBox1Text
  22. {
  23. get
  24. {
  25. return textBox1Text = textBox1.Text;
  26. }
  27. set
  28. {
  29.  
  30. }
  31. }
  32. }
  33. }

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

解决方法

您将需要自己添加,您可以将按钮添加到窗体并设置其 DialogResult属性.这将返回DialogResult并关闭窗体,而无需连接任何代码.以下是使用方法返回Form2上的TextBox的值的示例(Form2上有两个按钮,其DialogResults设置为Cancel并且Ok).

Form1中

  1. public partial class Form1 : Form
  2. {
  3. Form2 frm2;
  4. public Form1()
  5. {
  6. InitializeComponent();
  7. }
  8.  
  9. private void button1_Click(object sender,EventArgs e)
  10. {
  11. frm2 = new Form2();
  12. DialogResult dr = frm2.ShowDialog(this);
  13. if (dr == DialogResult.Cancel)
  14. {
  15. frm2.Close();
  16. }
  17. else if (dr == DialogResult.OK)
  18. {
  19. textBox1.Text = frm2.getText();
  20. frm2.Close();
  21. }
  22. }
  23. }

窗体2

  1. public partial class Form2 : Form
  2. {
  3. public Form2()
  4. {
  5. InitializeComponent();
  6. }
  7.  
  8. public string getText()
  9. {
  10. return textBox1.Text;
  11. }
  12. }

猜你在找的C#相关文章