【问题标题】:Passing Value from One Form to Another (C#)将值从一种形式传递到另一种形式 (C#)
【发布时间】:2015-06-06 09:28:26
【问题描述】:

我的程序中有一个搜索表单。当用户双击搜索表单上的单元格(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

【问题讨论】:

  • 制作id字段的属性并在主窗体中获取值
  • @Orace 这不是重复的,因为我以前使用过这种方法并且它有效。但由于某种原因,它现在不起作用。
  • @John 我已经为您提供了一个可行的解决方案,但我认为它不会帮助您解决困惑。您对表单工作方式的心理模型不正确。
  • 首先,有一个用代码创建的“主”表单实例,这里没有显示。我相当肯定这发生在应用程序启动代码中。主表单的该实例依次创建并显示搜索表单(在searchToolStripMenuItem_Click 事件处理程序中)。然后在搜索表单的searchdgv_CellDoubleClick 事件处理程序中创建主表单的second 实例。您显然认为声明 invmain inv = new invmain(); 创建了对已经打开的主窗体的引用,但事实并非如此。它是一个单独的实例。

标签: c# winforms forms datagridview


【解决方案1】:

我建议你这样做:

搜索表格:

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

【讨论】:

    猜你喜欢
    • 2015-06-23
    • 2012-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多