Как выбрать строку в 2 DataGridView, если она выбрана в третьем DataGridView? - PullRequest
1 голос
/ 09 февраля 2012

У меня есть 3 DataGridViews.С DataGridView1 и DataGridView2 вы можете выбрать строки.После нажатия кнопки сравниваются строки из DataGridView1 и DataGridView2, и каждая строка, имеющая одинаковые значения, задается в DataGridView3.

То, что я хочу, это когда вы выбираете строку в DataGridView3, те же строки выбираются в DataGridView1и DataGridView2.

Код, который у меня есть, а также работает:

private int ShowSelected(int selectedId, Boolean sBool)
{
    DataTable dt = DataGridView1.DataSource;

    if(!sBool)
        currentGrid = DataGridView1;


    int indexCounter = 0;            
        foreach (DataRow dr in dt.Rows)
        {
            int cellIdDgv = Convert.ToInt32(dr["cellId"]);

                if (selectedId == cellIdDgv)
                {
                    if (sBool)
                    {
                        DataGridView1.Rows[indexCounter].Selected = true;
                        DataGridView1.FirstDisplayedCell = DataGridView1.Rows[indexCounter].Cells[0];
                    }
                    else
                    {
                        DataGridView2.Rows[indexCounter].Selected = true;
                        DataGridView2.FirstDisplayedCell = DataGridView2.Rows[indexCounter].Cells[0];
                    }
                }

        indexCounter++;
    }
}

Но мне нужно что-то вроде этого, поэтому вам не нужно перебирать всю Grid:

string selection = "cellId = " + selectedId;
DataRow[] drResult = dt.Select(selection);
int rowId  = drResult.RowId;

if (sBool)
{
    DataGridView1.Rows[rowId].Selected = true;
        DataGridView1.FirstDisplayedCell = DataGridView1.Rows[rowId].Cells[0];
}
else
{
    DataGridView2.Rows[rowId].Selected = true;
        DataGridView2.FirstDisplayedCell = DataGridView2.Rows[rowId].Cells[0];
}

Как я могу сделать эту работу?

1 Ответ

0 голосов
/ 09 февраля 2012

Чтобы расширить мой комментарий и предоставить локальное (stackoverflow) решение:

Фильтрация выполняется с использованием свойства BindingSource.Filter. Пример, представленный в MSDN:

    private void PopulateDataViewAndFilter()
    {
        DataSet set1 = new DataSet();

        // Some xml data to populate the DataSet with.
        string musicXml =
             "<?xml version='1.0' encoding='UTF-8'?>" +
             "<music>" +
             "<recording><artist>Coldplay</artist><cd>X&amp;Y</cd></recording>" +
             "<recording><artist>Dave Matthews</artist><cd>Under the Table and Dreaming</cd></recording>" +
             "<recording><artist>Dave Matthews</artist><cd>Live at Red Rocks</cd></recording>" +
             "<recording><artist>Natalie Merchant</artist><cd>Tigerlily</cd></recording>" +
             "<recording><artist>U2</artist><cd>How to Dismantle an Atomic Bomb</cd></recording>" +
             "</music>";

        // Read the xml.
        StringReader reader = new StringReader(musicXml);
        set1.ReadXml(reader);

        // Get a DataView of the table contained in the dataset.
        DataTableCollection tables = set1.Tables;
        DataView view1 = new DataView(tables[0]);

        // Create a DataGridView control and add it to the form.
        DataGridView datagridview1 = new DataGridView();
        datagridview1.AutoGenerateColumns = true;
        this.Controls.Add(datagridview1);

        // Create a BindingSource and set its DataSource property to
        // the DataView.
        BindingSource source1 = new BindingSource();
        source1.DataSource = view1;

        // Set the data source for the DataGridView.
        datagridview1.DataSource = source1;

        //The Filter string can include Boolean expressions.
        source1.Filter = "artist = 'Dave Matthews' OR cd = 'Tigerlily'";
    }

Чтобы сделать это проще, вы можете создать FilterBuilder.

Редактировать: Чтобы избежать фильтрации или вышеупомянутых циклов, упомянутых в вашем вопросе, создайте DataTable, используя BindingSource и т. Д., Который связан с вашим `DataGridView1 затем:

DataTable DT; // Obtained from the relevent DGV.
DataView view = new DataView(DT);
DataView thisDV = new DataView();

// Then you can use...
thisDV.Find(thisOrThat);
thisDV.FindRows(thisOrThat);

Чтобы найти соответствующие строки в данных, его можно использовать для подачи Selection() в вас DataGridView с.

Надеюсь, это поможет.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...