Click here to Skip to main content
15,892,768 members
Please Sign up or sign in to vote.
4.00/5 (2 votes)
See more:
hello friends,

here i want to make searchbox to my datagrid view, while typing the letters in textbox should display the user details are existing in the datagrid.


when i will type in a searchbox(textbox) by typing only it should filter the values in datagrid .

give me a sample example

please suggest me .

thank you in advance.


here is my data grid code:

<DataGrid RowHeight="50"  CanUserResizeRows="False" HorizontalScrollBarVisibility="Disabled" VerticalScrollBarVisibility="Visible"       
                   BorderBrush="#FF274196" ColumnWidth="100" BorderThickness="6"  Height="391" 
                            Name="dataGrid1" VerticalAlignment="Center" HorizontalAlignment="Center" Width="584"  ItemsSource="{Binding Path=LoadDataBinding}" AutoGenerateColumns="False" FontSize="16" Opacity="1" Visibility="Visible" FontStyle="Italic" FontWeight="Normal" FontStretch="Normal" removed="White" Margin="173,112,45,102" Grid.Column="1">
                    <DataGrid.RowHeaderTemplate>
                        <DataTemplate>
                            <ToggleButton x:Name="RowHeaderToggleButton"
					              
					              Cursor="Hand" />
                        </DataTemplate>
                    </DataGrid.RowHeaderTemplate>
                    <DataGrid.Columns>                        
                        <DataGridTemplateColumn Header="Photo">
                            <DataGridTemplateColumn.CellTemplate>
                                <DataTemplate>
                                    <Image HorizontalAlignment="Center" VerticalAlignment="Center" Height="50" Width="50" Source="{Binding Path=addimage}"/>
                                </DataTemplate>
                            </DataGridTemplateColumn.CellTemplate>
                        </DataGridTemplateColumn>
                        <DataGridTextColumn  Binding="{Binding Path=addname}" Header="Name"  IsReadOnly="True">
                            <DataGridTextColumn.ElementStyle>
                                <Style TargetType="TextBlock">
                                    <Setter Property="HorizontalAlignment" Value="Center" />
                                    <Setter Property="VerticalAlignment" Value="Center" />
                                </Style>
                            </DataGridTextColumn.ElementStyle>
                        </DataGridTextColumn>
                        <DataGridTextColumn Binding="{Binding Path=addnumber1}" Header="Contactno" IsReadOnly="True">
                            <DataGridTextColumn.ElementStyle>
                                <Style TargetType="TextBlock">
                                    <Setter Property="HorizontalAlignment" Value="Center" />
                                    <Setter Property="VerticalAlignment" Value="Center" />
                                </Style>
                            </DataGridTextColumn.ElementStyle>
                        </DataGridTextColumn>
                        <DataGridTemplateColumn Header="View details">
                            <DataGridTemplateColumn.CellTemplate>
                                <DataTemplate>
                                    <Button Click="Button_Click" Height="25" Width="50" Background="#FF274196" Foreground="White" FontSize="14" Cursor="Hand" ToolTip="view full details" >view</Button>
                                </DataTemplate>
                            </DataGridTemplateColumn.CellTemplate>
                        </DataGridTemplateColumn>
                        <DataGridTemplateColumn Header="Delete contact" Width="150">
                            <DataGridTemplateColumn.CellTemplate>
                                <DataTemplate>
                                    <Button Click="Button_Click_1" Height="25" Width="50" Background="#FF274196" Foreground="White" FontSize="14" Cursor="Hand" ToolTip="Delete Record/Contact" >Delete</Button>
                                </DataTemplate>
                            </DataGridTemplateColumn.CellTemplate>
                        </DataGridTemplateColumn>
                    </DataGrid.Columns>
                    <DataGrid.ColumnHeaderStyle>
                        <Style TargetType="{x:Type DataGridColumnHeader}">
                            <Setter Property="HorizontalContentAlignment" Value="Center" />
                            <Setter Property="VerticalContentAlignment" Value="Center" />
                            <Setter Property="Height" Value="35" />
                            <Setter Property="SeparatorBrush" Value="DarkRed" />
                            <Setter Property="FontWeight" Value="Black" />
                            <Setter Property="Foreground" Value="White" />
                            <Setter Property="Template">
                                <Setter.Value>
                                    <ControlTemplate TargetType="{x:Type DataGridColumnHeader}">
                                        <Grid>
	<Border x:Name="columnHeaderBorder"
		BorderThickness="1"
		Padding="3,0,3,0">
		<Border.BorderBrush>
			<LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
				<GradientStop Offset="0" Color="#A5A5A5" />
				<GradientStop Offset="1" Color="#4B4B4B" />
			</LinearGradientBrush>
		</Border.BorderBrush>
		<Border.Background>
			<LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
                                                        <GradientStop Offset="0" Color="#FF274196" />
                                                        <GradientStop Offset="1" Color="#FF274196" />
			</LinearGradientBrush>
		</Border.Background>
	   <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
			     VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
				SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" />
	</Border>
                                            
   </Grid>
                                       
                                    </ControlTemplate>
                                </Setter.Value>

                            </Setter>
                        </Style>
                    </DataGrid.ColumnHeaderStyle>
                </DataGrid>
Posted
Updated 18-Mar-14 0:39am
v2
Comments
Mr.VJ 18-Mar-14 8:48am    
friends i have done this but getting an error : Null exception at dv.table=ds.table[0];

this code works fine in c# winform but not in Wpf .

please help me out.



public DataView dv
{
get;
set;
}

OleDbCommand cmdd = new OleDbCommand("SELECT addimage,addname,addnumber1 FROM addcontact", conn);
OleDbDataAdapter da = new OleDbDataAdapter(cmdd);
DataTable dt = new DataTable();
da.Fill(ds);
dv.Table = ds.Tables[0];
dataGrid1.DataContext = dv;
dv.RowFilter = "addname like '%" + SearchBox.Text + "%'";
dataGrid1.DataContext = dv;

 
Share this answer
 
 
Share this answer
 
Comments
Mr.VJ 19-Mar-14 1:49am    
thank u so much murali , it helps me a lot
[no name] 19-Mar-14 1:52am    
Thank u.
Member 13112469 3-Sep-19 23:08pm    
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data;
namespace WpfApplication3
{
/// <summary>
/// Interaction logic for MainWindow.xaml
///
public partial class MainWindow : Window
{
DataSet objdatasetsave = null;
DataRow objdatarow = null;
DataColumn objdatacol = null;
DataTable objdatatable = null;
public static int intid = 0;
public MainWindow()
{
objdatasetsave = new DataSet();
objdatatable = new DataTable();
objdatatable.TableName = "Db";
objdatasetsave.Tables.Add(objdatatable);
objdatatable.Columns.Add("Id", typeof(int));
objdatatable.Columns.Add("Name", typeof(string));
objdatatable.Columns.Add("Fathername", typeof(string));
var ID = Guid.NewGuid().ToString();

InitializeComponent();
}

private void Button_Click(object sender, RoutedEventArgs e)
{
try
{
intid++;
objdatarow = objdatatable.NewRow();
objdatarow["Id"] = intid;
objdatarow["Name"] = txtfname.Text;
objdatarow["Fathername"] = fathername.Text;
objdatatable.Rows.Add(objdatarow);
datagridss.ItemsSource = CollectionViewSource.GetDefaultView(objdatasetsave.Tables[0]);
}
catch (Exception)
{
throw;
}
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
DataRow[] objdatarowcollection = null;
string stringvalue=string.Empty;
try
{
stringvalue = (datagridss.SelectedItem as DataRowView)["Id"].ToString();
objdatarowcollection = objdatasetsave.Tables[0].Select("Id='" + stringvalue + "'");
if(objdatarowcollection!=null && objdatarowcollection.Length>0)
{
objdatarowcollection[0]["Name"] = txtfname.Text;
objdatarowcollection[0]["Fathername"] = fathername.Text;
}
}
catch (Exception)
{
throw;
}
}
private void Button_Click_2(object sender, RoutedEventArgs e)
{
string stringvalue=string.Empty;
DataTable objdatatable = null;
DataRow[] objdatarowcollection = null;
try
{
objdatatable = new DataTable();
objdatatable = ((DataRowView)datagridss.SelectedItem).Row.Table.Copy();
stringvalue = (datagridss.SelectedItem as DataRowView)["Id"].ToString();
objdatarowcollection = objdatatable.Select("Id='" + stringvalue + "'");
if(objdatarowcollection!=null && objdatarowcollection.Length>0)
{
txtfname.Text = objdatarowcollection[0]["Name"].ToString();
fathername.Text = objdatarowcollection[0]["Fathername"].ToString();
}
}
catch (Exception)
{
throw;
}
}
}
}


In the above coding i need to add a seperate Textbox and button to search a text(if text found that specific row should be displayed in datagrid)
Code Needed for this logic!
Will be Appreciated :-)
yes, i did myself .... both with name and number i can search .... :)

here is the logic :)


C#
DataTable dt = new DataTable();
           
            OleDbCommand cmdd = new OleDbCommand("SELECT addimage,addname,addnumber1 FROM addcontact", conn);
            OleDbDataAdapter da = new OleDbDataAdapter(cmdd);

            da.Fill(ds);
            
                view.Table = ds.Tables[0];
                System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex("^[a-zA-Z ]+$");
           if(r.IsMatch(SearchBox.Text))
           {
                view.RowFilter = "addname like '%" + SearchBox.Text + "%'";
               dataGrid1.ItemsSource = view;
           }
           else
           {
                view.RowFilter = "addnumber1 like '%" + SearchBox.Text + "%'";
                dataGrid1.ItemsSource = view;
           }
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900