将数据从一个表单传递到另一个表单

时间:2013-02-26 22:22:48

标签: c# winforms

我的一个项目中有两个表单。在form1中我有一个dataGridView和In form2我有4个TextBoxes。 在Form1中,我想使用CellMouseClick事件从datagridview获取变量值,然后将其传递给Form2中的TextBox

我试过这个。

form1#它给我一个错误

public form(int id)
{
    int x;
    x = dataGridView1.CurrentRow.Cells[0].Value.ToString();
}

以及我想在form2中做的事情

3 个答案:

答案 0 :(得分:7)

使用constructor,您construct可以construction具有给定先决条件的类型。

如果这意味着一个整数,那就这样吧:

public MyForm(int id) {
  SomeIdProperty = id;
}

而不是var form = new MyForm();,请执行:

var form = new MyForm(idOfTheRelevantThing);

然后显示它。

答案 1 :(得分:4)

表格1

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    private void button1_Click(object sender, EventArgs e)
    {
        var frm2 = new Form2(dataGridView1.Rows[0].Cells[0].Value.ToString());
        frm2.Show();
    }
}

表格2

public partial class Form2 : Form
{
    public Form2(string s)
    {
        InitializeComponent();
        textBox1.Text = s;
    }
}

答案 2 :(得分:2)

如果您从Form2显示Form1,则可以使用构造函数传递值。像这样:

class Form2 {
    public string Value { get; set; }
    public Form2(string value) {
        Value = value;
    }

    public void Form2_Load() {
        textBox1.Text = Value;
    }
}

并执行此操作(在Form1.cs内):

Form2 f = new Form2("the value here");
f.ShowDialog(); //or f.Show();