C#在Datagrid中搜索

时间:2015-02-23 15:13:53

标签: c# wpf xaml datagridview datagrid

我想在我的Datagrid中获取搜索方法。我通过数据集中的数据绑定填充我的数据网格。

      <Grid Name="Grid_Kind" Background="#FFFFAF00">
    <DataGrid x:Name="DataGridKind" ItemsSource="{Binding}" AutoGenerateColumns="False" Margin="0,21,0,166">
        <DataGrid.Columns>
            <DataGridTextColumn Binding="{Binding Path=KindID}" Header="ID" Width="Auto" />
            <DataGridTextColumn Binding="{Binding Path=VNaam}" Header="Voornaam" Width="Auto" />
            <DataGridTextColumn Binding="{Binding Path=ANaam}" Header="Achternaam" Width="Auto" />
            <DataGridTextColumn Binding="{Binding Path=Straat}" Header="Straat" Width="Auto" />
            <DataGridTextColumn Binding="{Binding Path=Huisnummer}" Header="Huisnummer" Width="Auto" />
            <DataGridTextColumn Binding="{Binding Path=Plaats}" Header="Plaats" Width="Auto" />
            <DataGridTextColumn Binding="{Binding Path=Postcode}" Header="Postcode" Width="Auto" />
        </DataGrid.Columns>
    </DataGrid>
    <TextBox Height="23" HorizontalAlignment="Left" Name="txtSearch" VerticalAlignment="Top" Width="695" Loaded="txtSearch_Loaded" Text="Zoeken" GotFocus="txtSearch_GotFocus" />

那是我到目前为止的Xaml

这是C#部分

    dsKind KindDataSet = new dsKind();
    dsKindTableAdapters.KindTableAdapter KindTableAdapter = new dsKindTableAdapters.KindTableAdapter();

    private void FillData()
    {
        KindTableAdapter.Fill(KindDataSet.Kind);
        this.DataContext = KindDataSet.Kind.DefaultView;
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        FillData();
    }

1 个答案:

答案 0 :(得分:0)

我已将此代码用作快速搜索选项,其中tsbSearch是ToolStripButton而tsTxtSearch是ToolStripTextBox。

使用DataGridView的BindingSource,它会在文本框中按Enter键或Return键时按说明(NMS_Description),LongDescription(LongDesc)和位置(LOCATION)自动搜索。

private void tsbSearch_Click(object sender, EventArgs e)
    {
        if (tstxtSearch.Text.Length > 0)
        {
            this.nEAR_MISSBindingSource.Filter = "NMS_Description LIKE '*" + tstxtSearch.Text + "*' OR LongDesc LIKE '*" + tstxtSearch.Text + "*' OR LOCATION LIKE '*" + tstxtSearch.Text + "*'";
        }
        else
        {
            this.nEAR_MISSBindingSource.Filter = "";
        }
    }

    private void tstxtSearch_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar == (char)Keys.Return || e.KeyChar == (char)Keys.Enter)
        {
            tsbSearch_Click(sender, e);
        }
    }

希望这有帮助。