搜索数据网格 wpf

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12768355/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 05:41:51  来源:igfitidea点击:

search on data grid wpf

.netwpfdata-bindingdatagrid

提问by Alfred Angkasa

i already bind all the data into my data grid. Now i want to perform a search.

我已经将所有数据绑定到我的数据网格中。现在我想进行搜索。

i figured it out, i can do sql connection to search. but i only want to do search on my datagrid. because my data already bind to my datagrid.

我想通了,我可以做 sql 连接来搜索。但我只想在我的数据网格上进行搜索。因为我的数据已经绑定到我的数据网格。

here is the pic enter image description here

这是图片 在此处输入图片说明

at the top, i have a textbox. how can i do a search / filtering by using the textbox? maybe i could type 'Bahan Baku', it will search on 'Nama Kategori'. or i also can type 'Sayur', it will search on 'Keterangan Kategori'. and what i type, will affect on my datagrid.

在顶部,我有一个文本框。如何使用文本框进行搜索/过滤?也许我可以输入“Bahan Baku”,它会搜索“Nama Kategori”。或者我也可以输入“Sayur”,它会搜索“Keterangan Kategori”。我输入的内容会影响我的数据网格。

any advice? thanks.

有什么建议吗?谢谢。

EDIT

编辑

Here is my code.

这是我的代码。

public partial class MainWindow : Window
{
    //private ICollectionView MyData;
    //string SearchText = string.Empty;
    ObservableCollection<Category> _data = new ObservableCollection<Category>();
    public ObservableCollection<Category> data { get { return _data; } }

    public MainWindow()
    {
        InitializeComponent();
        showData();
    }

    private void showData()
    {
        OleDbConnection conn = null;
        OleDbCommand cmd = null;

        try
        {
            conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=dbDemo1.accdb");
            cmd = new OleDbCommand("select categoryID, categoryDesc, categoryItem from t_category", conn);
            conn.Open();
            using (var reader = cmd.ExecuteReader())
            {
                while (reader.Read())
                {
                    data.Add(new Category
                        {
                            nCateogryID = int.Parse(reader[0].ToString()),
                            sCategoryDesc = reader[1].ToString(),
                            sCategoryItems = reader[2].ToString()
                        }
                    );
                }
            }
        }
        catch (Exception e)
        {
            MessageBox.Show(e.Message);
        }
        finally
        {
            conn.Close();
        }
    }
    private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
        {
            TextBox t = sender as TextBox;
            SearchText = t.Text.ToString();
            MyData.Filter = FilterData;
        }

    private bool FilterData(object item)
    {
        var value = (Category)item;
        if (value == null || value.nCateogryID == null)
            return false;
        return value.sCategoryDesc.ToLower().StartsWith(SearchText.ToLower()) || value.sCategoryItems.ToLower().StartsWith(SearchText.ToLower());
        //return value.Book_Id.ToLower().StartsWith(SearchText.ToLower()) || value.Book_Name.ToLower().StartsWith(SearchText.ToLower()) || value.Author_Name.ToLower().ToString().StartsWith(SearchText.ToLower()) || value.Publisher_Name.ToLower().ToString().StartsWith(SearchText.ToLower().ToString()) || value.Book_Genre.ToLower().ToString().StartsWith(SearchText.ToLower().ToString()) || value.Language.ToLower().ToString().StartsWith(SearchText.ToLower().ToString()) || value.Book_EntryDate.ToLower().ToString().StartsWith(SearchText.ToLower().ToString());
    }
}

this is my class category looks like:

这是我的班级类别:

public class Category
{
    public int nCateogryID { get; set; } 
    public int nCategoryMaster { get; set; }
    public int nCategoryDetail { get; set; }

    public string sCategoryDesc { get; set; }
    public string sCategoryItems { get; set; }
}

and this is my xaml

这是我的 xaml

<Window x:Class="SearchGrid.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        DataContext="{Binding RelativeSource={RelativeSource Self}}"
        Title="MainWindow" Height="350" Width="525">
<Grid>
    <DataGrid AutoGenerateColumns="False" Height="258" HorizontalAlignment="Left" Margin="12,0,0,12" Name="dataGrid1" VerticalAlignment="Bottom" Width="479">
        <DataGrid.Columns>
            <DataGridTextColumn Binding="{Binding ncategoryID}" Header="No." IsReadOnly="True" Width="30" />
            <DataGridTextColumn Binding="{Binding sCategoryDesc}" Header="Nama Kategori" IsReadOnly="True" Width="160" />
            <DataGridTextColumn Binding="{Binding sCategoryItems}" Header="Keterangan Kategori" IsReadOnly="True" Width="247" />
        </DataGrid.Columns>
    </DataGrid>
    <TextBox Height="23" HorizontalAlignment="Left" Margin="12,12,0,0" Name="textBox1" VerticalAlignment="Top" Width="479" TextChanged="textBox1_TextChanged" />
</Grid>
</Window>

I got this error:

我收到此错误:

Object reference not set to an instance of an object.

你调用的对象是空的。

回答by Dhaval Patel

You have to add TextChanged Event in xaml like

您必须在 xaml 中添加 TextChanged 事件,例如

<TextBox Text="" Width="115" Canvas.Left="210" Canvas.Top="37" Height="23" TextChanged="TextBox_TextChanged" />

in your cs file Your TextChanged event look like

在您的 cs 文件中您的 TextChanged 事件看起来像

 private ICollectionView MyData;
    string SearchText=string.Empty;
    private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
          TextBox t= sender as TextBox;
          SearchText=t.Text.ToString();
          MyData.Filter = FilterData;
        }
    private bool FilterData(object item)
        {
        var value = (Book_Information)item;
        if (value == null || value.Book_Id == null)
            return false;
        return value.Book_Id.ToLower().StartsWith(SearchText.ToLower()) || value.Book_Name.ToLower().StartsWith(SearchText.ToLower()) || value.Author_Name.ToLower().ToString().StartsWith(SearchText.ToLower()) || value.Publisher_Name.ToLower().ToString().StartsWith(SearchText.ToLower().ToString()) || value.Book_Genre.ToLower().ToString().StartsWith(SearchText.ToLower().ToString()) || value.Language.ToLower().ToString().StartsWith(SearchText.ToLower().ToString()) || value.Book_EntryDate.ToLower().ToString().StartsWith(SearchText.ToLower().ToString());
        }

MyData Contains your Whole Collection of Data here is example

MyData 包含您的整个数据集合,这里是示例

ViewBook=new ObservableCollection<Book_Information>();
dataGrid1.ItemsSource=ViewBook;
MyData=CollectionViewSource.GetDefaultView(ViewBook);

回答by Rohit Vats

You can filter the dataGrid by binding it to ICollectionViewwhich provides support of filtering on source collection. Details can be found hereand this might helpyou too.

您可以通过绑定它来过滤 dataGrid,它ICollectionView提供了对源集合过滤的支持。可以在此处找到详细信息,这也可能有所帮助