简体   繁体   中英

Passing Value from One Form to Another (C#)

I have a search form in my program. When the user double-clicks a cell (of the dgv) on the search form, I want the program to close that form and jump to the item on the main form.

I'm doing this by identifying each item with a unique id.

I'm trying to pass the value of the rows id to the other form. The problem is that, it says that I'm passing the value zero each time. But when I insert some message boxes on the search form, it says that the integer 'id' has successfully been assigned to the variable on the main form: public int CellDoubleClickValue { get; set; } public int CellDoubleClickValue { get; set; }

Here is my code:

Search Form:

    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.
    }

Main Form:

    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

I suggest you do as follows:

Search Form:

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();
}

Main form:

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...
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM