How to search in Data gridview in C# Windows Form application? - c#

I have a form in which a simple gridview is populated by a table in database having columns like TicketID, Name, Company, Product etc. Now I want to add a search feature so that user could search by customer name or company or TicketID.
How can I do that ? I want to place a combox box, textbox and a simple "search" button above datagrid. When the user selects TicketID for example, enters "1" in textbox and presses "Search", it should refresh datagrid with entry where TicketID = 1.
Now I don't have any idea on how to implement it. Googled for it but found nothing useful. So any help in this regard will be appreciated.
Regards.

You may look into:
BindingSource bs = new BindingSource();
bs.DataSource = dataGridView1.DataSource;
bs.Filter = columnNameToSearch + " like '%" + textBox1.Text + "%'";
dataGridView1.DataSource = bs;
This will show you records containing text from textbox1 in column of your choice. I did exactly what you are asking for:)

Create a Textbox for search input and use the following code on its TextChanged event
private void txtSearch_TextChanged(object sender, EventArgs e)
{
(dataGridView.DataSource as DataTable).DefaultView.RowFilter = string.Format("TicketID like '{0}%' OR Product like '{0}%' OR Name like '{0}%' OR Product like '{0}%'", txtSearch.Text);
}

If you want refresh your DataSource depended on the search parameters, then you need to build a new SQL query depended on then "search" controls:
Will be better of you show your code of getting data from database,
but this is my shot with manual SQL-query creating:
//...
StringBuilder query = new StringBuilder();
query.AppendLine("SELECT TicketID, Name, Company, Product");
query.AppendLine("FROM YourTable WHERE 1=1");
if (txtSearch.TextLength > 0)
{
query.AppendLine("AND TicketID = #TicketID");
//Here add sqlparameter with textbox value
}
//... and so on

BindingSource bs = new BindingSource();
bs.DataSource = dataGridView1.DataSource;
bs.Filter = "[database column Name To Search] like '%" + textBox1.Text + "%'";
dataGridView1.DataSource = bs;

BindingSource bs = new BindingSource();
bs.DataSource = dgrid.DataSource;
bs.Filter = "Full_Name like '%" + tsptxt_search.Text + "%'";
dgrid.DataSource = bs;
This works for me.

What you need, filtering, not searching... Searching is highlighting the correct row from the set
Set grid DataSource to the result of DataTable.Select method
dtData.Select("TicketID = 1")
Also take a look to this post

DataSet ds;
DataView dv;
public Form1()
{
InitializeComponent();
ds = new DataSet();
dv = new DataView();
}
private void Form1_Load(object sender, EventArgs e)
{
ds=SelectStudents();
dv.Table = ds.Tables[0];
dataGridView1.DataSource = dv;
}
Now in the text_changed event of the textbox, write below code
dv.RowFilter = "StudentName like '%" + textBox1.Text + "%'";
dataGridView1.DataSource = dv;

Related

Searching for name in dataGridView through more then one table in C#

I have a browse button witch browses 5 different tables into DataGridView. I have a scrollBar to go through them. Now I need to make a search TextBox and if I write in it something like "Milk" it automatically finds all tables witch contain that name/word e.x. there were 5 tables to go through but now only 3, because only 3 contain word milk. Here is my code witch searches only in 1 table (I only got that far). Thank you!
private void textBox5_TextChanged(object sender, EventArgs e)
{
DataView dv = new DataView(dt);
dv.RowFilter = string.Format("Prece LIKE '%{0}%'", textBox5.Text);
dataGridView1.DataSource = dv;
}
What about something like this:
private void textBox5_TextChanged(object sender, EventArgs e)
{
// Your gridViews here
var gridList = new List<DataGridView>() { yourGrid1, yourGrid2};
foreach(DataGridView dv in gridList)
{
dv.RowFilter = string.Format("Prece LIKE '%{0}%'", textBox5.Text);
dataGridView1.DataSource = dv;
}
}
Add your DataGridViews to the List and let it iterate through them. You just have to handle how to output it then.
Note that I havn't edited your searching-method in here. I've just added the loop.
If you have one DataGridView and all DataTables are same
private void textBox5_TextChanged(object sender, EventArgs e)
{
DataView dv = new DataView(dt);
dv.RowFilter = string.Format("Prece LIKE '%{0}%'", textBox5.Text);
DataTable dtMain=dv.ToTable().Copy();
dv = new DataView(dt2);
dv.RowFilter = string.Format("Prece LIKE '%{0}%'", textBox5.Text);
dtMain.Merge(dv.ToTable());
dv = new DataView(dt3);
dv.RowFilter = string.Format("Prece LIKE '%{0}%'", textBox5.Text);
dtMain.Merge(dv.ToTable());
dataGridView1.DataSource = dtMain;
}

How can i filter gridview depend on text changed in text box

I want to filter the GridView depend on the TextBox in form down .. I want when I write for example ec it shows all rows with company name include ec then if I change the string in the TextBox the data changes also in the GridView.
DoubleClick on your TextBox and write code here:
private void textBox1_TextChanged(object sender, EventArgs e)
{
string sql = "SELECT * FROM Table WHERE Name LIKE #Name";
using (SqlCommand cmd= new SqlCommand(sql, cn))
{
cmd.Parameters.AddWithValue("#Name", "%" + textBox1.Text + "%");
//rest of the code
//dataGridView.DataSource = your DataSource;
}
}
Edit: To avoid pulling data from the db on each keystroke, Try this in textBox1_TextChanged Event:
DataSet ds = new DataSet();//Populate ds from a SqlDataAdapter
private void textBox1_TextChanged(object sender, EventArgs e)
{
DataView dv = ds.Tables[0].DefaultView;
dv.RowFilter = string.Format("name LIKE '%{0}%'", textBox1.Text);
dataGridView1.DataSource = dv;
}
Have you tried the row filter property on the datagrid?
(dataGridViewFields.DataSource as DataTable).DefaultView.RowFilter = string.Format("Field = '{0}'", textBoxFilter.Text);
See Brad Bruce's answer here for an example.

c# datagridview interactive filtering

I'm trying to make interactive filter for datagridview
I'm using EF to fetch data
var query = from client in db.Clients
select new
{
client.Id,
client.Code,
client.Title
};
clientsBs.DataSource = query.ToList();
dataGridView1.DataSource = clientsBs;
what's the best way to filter datagridview without another database query?
I tried this way, but it gives me no result/error...
private void textBox1_TextChanged(object sender, EventArgs e)
{
BindingSource bs = new BindingSource();
bs.DataSource = dataGridView1.DataSource;
bs.Filter = "Code like '%" + textBox1.Text + "%'";
dataGridView1.DataSource = bs;
}
any ideas?
Please indicate the errors if any. I think before setting the DataSource you should set it to null:
dataGridView1.DataSource = null;
dataGridView1.DataSource = bs;
UPDATE:
for Filtering the DataGridView you should change the DataSource and then bind it again:
var dataview = yourDataSet.Tables[tableIndex].DefaultView;
dataview.RowFilter = "Code like '%" + textBox1.Text + "%'";
var newDT = dataview.ToTable();
var newDS = new DataSet();
newDS.Tables.Add(newDT);
dataGridView1.DataSource = null;
dataGridView1.DataSource = newDS;

How to filter a datagridview by a textbox after loading an excel file into it

I am at the VERY beggining with C#. I am creating a program for making offers for clients. I got first form with offer and a subform with an excel file loaded into datagridview. When I double click the row it is copied to the datagridview in the first row. It works fine. But I want to add a TextBox with the TextChanged event so when user puts some text there a datagridview (in second form, that one with excel data) should show only rows that contain this text. If it is not possible to search all calumns at once it's fine. But I cannot make it work. I found some sollution and i copied it but i doesn't work. So here's the code:
private void button1_Click(object sender, EventArgs e)
{
try
{
System.Data.OleDb.OleDbConnection PolaczenieBazyDanych = new System.Data.OleDb.OleDbConnection("provider=Microsoft.ACE.OLEDB.12.0;Data Source='C:\\Users\\user\\Desktop\\My Dropbox\\Cenniki\\Cennik.xlsx';Extended Properties=Excel 8.0;");
System.Data.DataSet DtSet = new System.Data.DataSet();
System.Data.OleDb.OleDbDataAdapter Adapter = new System.Data.OleDb.OleDbDataAdapter("select * from [Tabelle1$]", PolaczenieBazyDanych);
//Adapter.TableMappings.Add("Tabela", "TabelaTestowa");
Adapter.Fill(DtSet);
dataGridView1.DataSource = DtSet.Tables[0];
PolaczenieBazyDanych.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
DataView dv = ((DataTable)dataGridView1.DataSource).DefaultView;
dv.RowFilter = "FromColumn like '%" + textBox1.Text + "%'";
dataGridView1.DataSource = dv;
}
This did work:
BindingSource bs = new BindingSource();
bs.DataSource = dataGridView1.DataSource;
bs.Filter = sColumnaDoPrzeszukania + " like '%" + textBox1.Text + "%'";
dataGridView1.DataSource = bs;

search in datagridview C# winfom

I want to put a search option in DataGridView, i.e., User types the string or int in TextBox and similar records the DataGridView should be highlighted. I tried it using KeyPress event but didn't work.
if (Char.IsLetter(e.KeyChar))
{
for (int i = 0; i < (dgemployee.Rows.Count); i++)
{
if (dgemployee.Rows[i].Cells["Employee"].Value.ToString().
StartsWith(e.KeyChar.ToString(), true,
CultureInfo.InvariantCulture))
{
dgemployee.Rows[i].Cells[0].Selected = true;
return;
}
}
Actually, I need to search the whole DataGridView, not only one column and row. So any best solution?
If your DataGridView is bound to a DataTable or a DataView, you can do this:
Create a BindingSource and make BindingSource.DataSource the Datatable or DataView that your DGV is currently using. Then set your DataGridView.DataSource to the BindingSource. Then you can use the BindingSource.Filter property to query your datasource by setting the BindingSource.Filterto your query string which will automatically filter the DGV. You can find the syntax here - it is very similar to basic SQL queries, except you can only use wild cards on the beginning and end of the string.
Use the DataView.RowFilter property.
Also take a look at DataTable.DefaultView
Take a look at this article I wrote some time back on filtering data real time.
private void txtsearchgroup_KeyUp(object sender, KeyEventArgs e) {
SqlConnection objconnection = new SqlConnection(servername and ...);
DataView Dv = new DataView();
objcommand = new SqlCommand("select name from groupitems", objconnection);
objdataadapter = new SqlDataAdapter();
objdataadapter.SelectCommand = new SqlCommand();
objdataadapter.SelectCommand = objcommand;
objdataset = new DataSet();
objconnection.Open();
objdataadapter.Fill(objdataset);
Dv.Table = objdataset.Tables[0];
Dv.RowFilter = " name LIKE '%" + txtsearchgroup.Text + "%'";
dataGridView1.DataSource = Dv;
objconnection.Close(); }
txtsearchgroup : name of textbox for search word in datagridview1 and
txtsearchgroup_KeyUp : event of keyup for search and filter word in datagridview1 and
select name from groupitems : name is field for groupitems table and
Dv.Table = objdataset.Tables[0] : zero (0) is first table in dataset

Categories