C#实现两个窗体之间数值传送的方法


本文实例讲述了C#实现两个窗体之间数值传送的方法。分享给大家供大家参考,具体如下:

以下是本人常用的方法,其实方法很多,但我觉得这两种我比较好理解,要是哪位朋友有比较简单的易懂的其他方法,希望不吝赐教。

方法一:

比如要在FORM2里得到FORM1里的值,先在FORM1里定义一个公有的字符串

复制代码 代码如下:
public string zhi="xxxxxx";

然后FORM2里用FORM1去实例化一个对象

复制代码 代码如下:
FORM1 f=new FORM1();

最后用 f.zhi来取得FORM1里的值。(f.Show()也是一个道理,即对象名.方法名)

方法二:

比如要在FORM1里得到FORM2里的值,利用GET,SET方法。
在FORM2里放一个TEXTBOX,写一个公有属性

public string transsformValue
{
 get
   {
    return this.textBox1.Text;
   }
 set
   {
    this.textBox1.Text=value; 
  }
}

在FORM1里这么写(在里面也加一个TEXTBOX):.

FORM2 f=new FORM2();
f.transsformValue="aaaa";
textBox1=f.transsformValue;
f.Show();

这样运行后是将FORM2的文本框的值设为“aaaa”,并且显示在FORM1里的文本框里

实例演示

FORM1里这么写:

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 WindowsFormsApplication17
{
  public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent();
    }
    private void Form1_Load(object sender, EventArgs e)
    {
    }
    private void button1_Click(object sender, EventArgs e)
    {
      InputBox f = new InputBox();
      f.Title = "请输入对话框";
      f.TipText = "请输入年龄";
      if (f.ShowDialog() == DialogResult.OK)
        this.label1.Text = f.Message;
    }
  }
}
//InputBox的FORMl里这么写
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 WindowsFormsApplication17
{
  public partial class InputBox : Form
  {
    public InputBox()
    {
      InitializeComponent();
    }
    public string Title
    {
      set { this.Text = value; }
    }
    public string Message
    {
      get { return this.Input.Text; }
    }
    public string TipText
    {
      set { this.Tip.Text = value; }
    }
    private void InputBox_Load(object sender, EventArgs e)
    {
      this.AcceptButton = this.btnOK;
      this.CancelButton = this.btnCancel;
      this.btnOK.DialogResult = DialogResult.OK;
      this.btnCancel.DialogResult = DialogResult.Cancel;
    }
  }
}

运行效果截图如下:

希望本文所述对大家C#程序设计有所帮助。


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3