将值从datagridview传递到其他表单上的文本框

时间:2016-03-31 20:56:30

标签: c# winforms datagridview

我的Form1有文本框; Form2(当前表单)有datagridview和按钮选择。当我运行Form1以新的方式显示时(我在表单上写的没有数据) 如何将值从Form2传递到Form1以保存所有数据。

    public void btnChoose_Click(object sender, EventArgs e)
    {
        Form1 form = new Form1;
        form.txtMaKeHoach.Text = "value";
        form.Show();
        this.Close();
    }

1 个答案:

答案 0 :(得分:0)

我希望这就是你要找的......

Form1的代码:

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

    private void Form1_Load(object sender, EventArgs e)
    {
        Form2 frm = new Form2();
        DialogResult res = frm.ShowDialog();

        if (res != System.Windows.Forms.DialogResult.OK)
        {
            frm.Dispose();
            return;
        }
        this.txtMaKeHoach.Text = frm.ChosenEntry;
        frm.Dispose();
    }
}

Form2的代码:

public partial class Form2 : Form
{

    private string _ChosenEntry = "";

    public Form2()
    {
        InitializeComponent();
    }

    private void btnChoose_Click(object sender, EventArgs e)
    {
        //...
        _ChosenEntry = this.dataGridView1.SelectedCells[0].Value.ToString();
        this.DialogResult = System.Windows.Forms.DialogResult.OK;
        this.Close();
    }

    public string ChosenEntry
    {
        get { return _ChosenEntry; }
    }
}