Logan Young
Logan Young

Reputation: 431

Data confusion - Selecting data in one DataGridView based on selection in another

This probably isn't the best way to do what I want, but I can't think of anything else to try...

NB: I'm using Visual Basic.NET

My form has 2 DataGridView controls. One of these is bound to a DataSet, the other isn't visible - at least not until the user selects a uniqueidentifier cell in the 1st grid.

When the user makes this selection, the 2nd grid will become visible and display the row from another with the same id as the one selected in the 1st grid.

So, basically, I want to dynamically display data in one grid based on user selection in another grid.

My code looks like this so far...

Private Sub RulesGrid_CellClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles RulesGrid.CellClick
    Try
        FlagsGrid.Visible = True
        ''// MsgBox(RulesGrid.CurrentCell.Value.ToString())
        Dim sql As String = "SELECT * FROM ctblMKA_Status_Flags " + _
            "WHERE intStatusID = '" & RulesGrid.CurrentCell.Value & "'"
        DSFlags = GetDS(sql)
        DSFlags.DataSetName = "FlagsDataSet"
        FlagsGrid.DataSource = DSFlags
        ProgressBar.Visible = False
    Catch ex As Exception
        MsgBox(ex.ToString)
    End Try
End Sub

I feel like I'm missing something here... Any ideas anyone?

Upvotes: 1

Views: 1072

Answers (2)

Michael Buen
Michael Buen

Reputation: 39433

If you are using a DataTable, assign a CurrencyManager, then add PositionChanged on your CurrencyManager variable.

class-level variable:

CurrencyManager _cmShoe;

after loading data to a datatable:

// make a currency(current) manager on DataTable variable
_cmShoe = this.BindingContext[_dtShoe] as CurrencyManager;

// add event on the CurrencyManager variable
_cmShoe.PositionChanged += cmShoe_PositionChanged;

the event:

void cmShoe_PositionChanged(object sender, EventArgs e)
{
    Guid shoeGuid = (Guid)((cmShoe.Current as DataRowView)["shoe_id"]);

    // _dtShoeMaterial is the table of the second datagridview
    _dtShoeMaterial.DefaultView.RowFilter = "shoe_id = '" + shoeGuid.ToString() + "'";
}

If you are using BindingSource(instead of DataTable), just add a PositionChanged event on the BindingSource variable, and use this event:

void cmShoe_PositionChanged(object sender, EventArgs e)
{
    Guid shoeGuid = (Guid)((bdsShoe.Current as DataRowView)["shoe_id"]);

    // bdsShoeMaterial is the table of the second datagridview
    bdsShoeMaterial.Filter = "shoe_id = '" + shoeGuid.ToString() + "'";        
}

Upvotes: 0

Gerrie Schenck
Gerrie Schenck

Reputation: 22368

Use a seperate DataView for the second DataGrid.

Upvotes: 0

Related Questions