将价值从一种形式传递到另一种形式(C#)

时间:2015-04-01 16:15:35

标签: c# winforms forms datagridview

我的程序中有一个搜索表单。当用户双击搜索表单上的(dgv)单元格时,我希望程序关闭该表单并跳转到主表单上的项目。

我这样做是通过识别具有唯一ID的每个项目。

我正在尝试将行id的值传递给另一个表单。问题是,它说我每次都传递零值。但是当我在搜索表单上插入一些消息框时,它表示整数'id'已成功分配给主窗体上的变量:public int CellDoubleClickValue { get; set; }

这是我的代码:

搜索表单:

    private int id;

    private void searchdgv_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
    {
        this.rowIndex1 = e.RowIndex;
        this.id = Convert.ToInt32(this.searchdgv.Rows[this.rowIndex1].Cells["id"].Value);
        invmain inv = new invmain();
        inv.CellDoubleClickValue = this.id;
        this.DialogResult = DialogResult.OK;
        this.Close();
        //MessageBox.Show(inv.CellDoubleClickValue.ToString()); 
        //Above, it shows it got assigned successfully.
    }

主要表格:

    public int CellDoubleClickValue { get; set; }

    private void searchToolStripMenuItem_Click(object sender, EventArgs e)
        {
        search form1 = new search();
        form1.ShowDialog();

        if (form1.DialogResult == DialogResult.OK)
        {
            MessageBox.Show(CellDoubleClickValue.ToString());
        }//Here it shows that the value is: 0

1 个答案:

答案 0 :(得分:3)

我建议你这样做:

搜索表单:

public int SelectedId { get; set; }

private void searchdgv_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
    this.rowIndex1 = e.RowIndex;
    this.SelectedId = Convert.ToInt32(this.searchdgv.Rows[this.rowIndex1].Cells["id"].Value);
    this.DialogResult = DialogResult.OK;
    this.Close();
}

主要形式:

private void searchToolStripMenuItem_Click(object sender, EventArgs e)
{
    search form1 = new search();
    form1.ShowDialog();

    if (form1.DialogResult == DialogResult.OK)
    {
        int selectedId = form1.SelectedId;
        // Do whatever with selectedId...
    }