简体   繁体   English

以另一种形式从datagridview获取所选记录的pk

[英]Getting pk of selected record from datagridview in another form

When I perform the getPkRowReport() it works correctly if I am using the value on the same form (form1). 当我执行getPkRowReport()时,如果我在同一表格(form1)上使用该值,它将正常工作。 If I need the pk for Form 2 it always defaults to the top row and never the row i had selected before I launch form 2. If I look at form 1 after I launch form 2 the correct row is selected but I am still getting the pk for the top record. 如果我需要表格2的pk,则它始终默认为第一行,而不是我在启动表格2之前选择的行。如果在启动表格2之后查看表格1,则选择了正确的行,但仍然可以pk排名第一。 Any help would be appreciated. 任何帮助,将不胜感激。

Form 1: 表格1:

    private int pkFromReport;
    public int PkFromReport
    {
        get
        {
            pkFromReport = getPkRowReport();
            return pkFromReport;
        }
    } 

    private int getPkRowReport()
    {
        if (dgvReportGrid.CurrentRow != null)
        {
            //get selected row index
            int index = this.dgvReportGrid.CurrentRow.Index;
            //get pk of selected row using index
            string cellValue = dgvReportGrid["rptNo", index].Value.ToString();
            //change pk string to int
            int pKey = Int32.Parse(cellValue);

            return pKey;
        }
        else
        {
            return -1;
        }
    }

Form 2: 表格2:

private frmMain mainForm = new frmMain();

private void button1_Click(object sender, EventArgs e)
    {
        textBox1.Text = mainForm.PkFromReport.ToString();
    }

CurrentRow gets the row containing the current cell. CurrentRow获取包含当前单元格的行。 When your form loses focus, your selected row is no longer the current row. 当表单失去焦点时,所选行将不再是当前行。

You should use the SelectedRows collection to get your currently selected row. 您应该使用SelectedRows集合来获取当前选定的行。 Since you plan to have only one selected row, change your code like this: 由于您计划只选择一行,因此请更改代码,如下所示:

private int getPkRowReport()
{
    if (dgvReportGrid.SelectedRows.Count > 0)
    {
        //get selected row index
        int index = this.dgvReportGrid.SelectedRows[0].Index;
        //get pk of selected row using index
        string cellValue = dgvReportGrid["rptNo", index].Value.ToString();
        //change pk string to int
        int pKey = Int32.Parse(cellValue);

        return pKey;
    }
    else
    {
        return -1;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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