PJW
PJW

Reputation: 5397

DataGridView Column Sort results in EventArgs being wrong on Double Click

I have a datagridview on my WinForms app which shows a list of cases the client is working on. Double clicking the 'CaseNo' column on the datagridview opens up a new form specific to the slected case. The double click event code is as follows:

private void dataGV_CellCoubleClick(object sender, DataGridCellEventArgs e)
{ 
    if (e.ColumnIndex == 0)
    {
        DataTable table = (DataTable)dataGV.DataSource;
        string strCaseNo = table.Rows[e.RowIndex][e.ColumnIndex].ToString();
        frmCase fC = new frmCase(strCaseNo);
        fC.MdiParent = this.MdiParent;
        fC.Show;
    }
}

The case form opens fine. However, if the user had previously double clicked a column header to apply a sort to the datagridview, then double clicking a data row opens the wrong case.

For example:

Case Name

1 Smith

2 Jones

3 Walter

Initially clicking 2 will open the frmCase for Jones. However if you first double click the Name column to sort alphabetically as follows:

Case Name

2 Jones

1 Smith

3 Walter

Then clicking on 2 now will open the Smith case (instead of Jones as it should).

It seems that after a sort, double clicking a cell returns the value that previously occupied that row (as if the datasource has not been sorted, even though it has been sorted on the users screen).

Can someone please advise how I correct this.

Upvotes: 1

Views: 778

Answers (1)

ron tornambe
ron tornambe

Reputation: 10780

You are accessing the underlying table, not the grid. Try the following:

private void dataGV_CellCoubleClick(object sender, DataGridCellEventArgs e)
{ 
    if (e.ColumnIndex == 0)
    {
        string strCaseNo = ((DataGridView)sender).Rows(e.RowIndex).Cells(e.ColumnIndex).Value.ToString();
        frmCase fC = new frmCase(strCaseNo);
        fC.MdiParent = this.MdiParent;
        fC.Show;
    }
}

Upvotes: 3

Related Questions