简体   繁体   中英

C# Filter DataGridView with the Values of Array

i want to know how i can search with the BindinSource.Filter. I have my Code like this Suche.Filter = string.Format("{0} = '{1}'", "ID", ergebnis); ergebnis is my Array with all the ID's of my Contacts. Now i want to Show all Contacts with the same ID in the DGV

源代码

This is how I solved it:

private void filter(int selectedID) {
    DataTable dtFilter = new DataTable();

    //speichere GridView zum Filtern
    dtFilter = (DataTable)this.grdMDT.DataSource;

    try {
        dtFilter = dtFilter.Select("ID = " + selectedID).CopyToDataTable();
        this.DGV.DataSource = dtFilter;
    }
    catch (Exception ex) {
        MessageBox.Show(ex.Message);
    }
}

I simply copy the contents of the DataGridView to a new DataTable and use Select to get all the results I need. I then set a new DataSource for the GridView .

You may want to store the original contents of the GridView in a seperate DataTable to clear the filter results.

Of course, you'd need to do this outside of the for-loop.

You can apply a filter by getting the view and making your array an array of objects

ICollectionView view = CollectionViewSource.GetDefaultView(yourdatagridview);
        view.Filter = FilterPerItem;
        yourdatagridview.ItemsSource = view;

In FilterPerItem you add the filter logic

private bool FilterPerItem(Contact item)
    {
        int rightID = 1;
        if (item.ID == rightID)
        {
            return true;
        }
        else return false;
    }

I found a result for my Code, thanks Guys!

            try
            {
                int[] ergebnis = new int[20];
                var filterString = new List<string>();

                for (int i = 1; i < result.Length; i++)
                {
                    int j = Int32.Parse(result[i][12]);

                    ergebnis[i] = j;

                    filterString.Add(string.Format("{0} = '{1}'", "ID", j));
                }

                Suche.Filter = string.Join(" OR ", filterString);
                kitba();
            }
            catch (IndexOutOfRangeException ex)
            {
                Debug.WriteLine(ex);
            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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