AutoComplete Textbox with DataGridView [duplicate] - c#

First to my problem: Id like to filter my DataGrid with a TextBox dynamically for the Name.
My current code:
how the DataGrid is filled:
cnb1 = new MySqlConnectionStringBuilder();
cnb1.Server = "xxxxxxxxxxxxxxxxxxx";
cnb1.Database = "xxxxxxxxxxxxxxx";
cnb1.UserID = "xxxxxxxxxxxxxxxxx";
cnb1.Password = "xxxxxxxxxxxxxxxxxx";
cn1 = new MySqlConnection(cnb1.ConnectionString);
cn1.Open();
da = new MySqlDataAdapter("SELECT * FROM AktuelleDaten", cn1);
da.MissingSchemaAction = MissingSchemaAction.AddWithKey;
da.SelectCommand.ExecuteNonQuery();
ds = new DataSet();
da.Fill(ds);
hauptübersichtgrid.ItemsSource = ds.Tables[0].DefaultView;
The Code for the TextBox:
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
DataSet DV = ds;
hauptübersichtgrid.ItemsSource = DV.Tables[0].DefaultView.RowFilter = string.Format("Name like '%{0}%'", Filter.Text);
}
It looks like this:

Change your code to this:
private void TextBox_TextChanged(object sender, EventArgs e)
{
DataView dv = ds.Tables[0].DefaultView;
dv.RowFilter = string.Format("Name like '%{0}%'", Filter.Text);
hauptübersichtgrid.ItemsSource = dv;
}

Related

How can I search a listbox items depending on a variable?

I am new to c# and trying to search a listbox as following :
First i have this :
public partial class FrmCodes : Form
{
...
SqlConnection Cn = new SqlConnection(#"Server = AMR-PC\SQLEXPRESS ; Database=PlanningDB ; Integrated Security = True");
SqlCommand cmd;
SqlDataReader DataRead;
...
public FrmCodes()
{
InitializeComponent();
cmd = new SqlCommand("Select Item from Items", Cn);
Cn.Open();
DataRead = cmd.ExecuteReader();
while (DataRead.Read())
{
ListItems.Items.Add(DataRead["Item"].ToString());
}
DataRead.Close();
Cn.Close();
}
And tried to do this :
private void txtSrch_TextChanged(object sender, EventArgs e)
{
ListItems.Items.Clear();
while (DataRead.Read())
{
string str = DataRead["Item"].ToString();
string srch = txtSrch.Text;
if (str.Contains(srch))
{
ListItems.Items.Add(str);
}
}
}
It did not work , I tried to make a new sql select query that get data depending on txtSrch.Text but got nothing either .
Thanks in advance.
Edit#1
This is the query i mentioned before :
private void txtSrch_TextChanged(object sender, EventArgs e)
{
ListItems.Items.Clear();
SqlConnection Cn2 = new SqlConnection(#"Server = AMR-PC\SQLEXPRESS ; Database=PlanningDB ; Integrated Security = True");
Cn2.Open();
string srch = txtSrch.Text;
using (SqlDataAdapter a2 = new SqlDataAdapter("Select Item from Items WHERE Item LIKE '%" + srch + "%'", Cn2))
{
var t2 = new DataTable();
a2.Fill(t2);
ListItems.DisplayMember = "Item";
ListItems.ValueMember = "Code";
ListItems.DataSource = t2;
}
}
This did not affect the items in the listbox nothing happens on txtSrch Change .
Another solution using Dataview thanks to #Trevor
public partial class FrmCodes : Form
{
...
SqlConnection Cn = new SqlConnection(#"Server = AMR-PC\SQLEXPRESS ; Database=PlanningDB ; Integrated Security = True");
SqlDataAdapter da;
DataTable dt = new DataTable();
...
public FrmCodes()
{
InitializeComponent();
da = new SqlDataAdapter("Select Item from Items", Cn);
da.Fill(dt);
DataView dv = new DataView(dt);
ListItems.DataSource = dv;
ListItems.DisplayMember = "Item";
}
Textbox change :
private void txtSrch_TextChanged(object sender, EventArgs e)
{
ListItems.DataSource = null;
DataView dv = new DataView(dt);
string srch = txtSrch.Text;
dv.RowFilter = string.Format("Item Like '%{0}%'", srch);
ListItems.DataSource = dv;
ListItems.DisplayMember = "Item";
}
Thanks.
Basedon #Olivier Jacot-Descombes’ comments, this worked for me:
private void txtSrch_TextChanged(object sender, EventArgs e)
{
ListItems.DataSource = null;
SqlConnection Cn2 = new SqlConnection(#"Server = AMR-PC\SQLEXPRESS ; Database=PlanningDB ; Integrated Security = True");
Cn2.Open();
string srch = txtSrch.Text;
using (SqlDataAdapter a2 = new SqlDataAdapter("Select Item from Items WHERE Item LIKE '%" + srch + "%'", Cn2))
{
var t2 = new DataTable();
a2.Fill(t2);
ListItems.DisplayMember = "Item";
ListItems.ValueMember = "Code";
ListItems.DataSource = t2;
}
}

C# System.Data.DataRowView

I am almost there trying to filter my datagridview from a combobox avoiding to using the databinding GUI. My problem is now that I see System.Data.DataRowView in my combobox inxtead of the normal values. The code:
private void Form2_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(#"Data SourceXXXXX;Initial Catalog=Studio;Integrated Security=True;");
conn.Open();
SqlCommand sc = new SqlCommand("SELECT Nome FROM DClub order by Nome", conn);
SqlDataReader reader;
reader = sc.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("Nome", typeof(string));
dt.Load(reader);
comboBox1.ValueMember = "Nome";
comboBox1.DisplayMember = "Nome";
comboBox1.DataSource = dt;
conn.Close();
var select = "SELECT *,bell+corp+fasc+app as Obi, bell+corp+fasc+vic+app as Tot,(bell+corp+fasc+vic+app)/5 as Med, (bell+corp+fasc+app)/4 as MedOb FROM DClub order by bell+corp+fasc+vic+app desc";
var c = new SqlConnection("Data Source=DIEGOPC;Initial Catalog=Studio;Integrated Security=True;"); // Your Connection String here
var dataAdapter = new SqlDataAdapter(select, c);
var commandBuilder = new SqlCommandBuilder(dataAdapter);
var ds = new DataSet();
dataAdapter.Fill(ds);
dataGridView1.ReadOnly = true;
dataGridView1.DataSource = ds.Tables[0];
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
var dataView = ((DataTable)dataGridView1.DataSource).DefaultView;
if (comboBox1.Text == "Remove filter")
{
dataView.RowFilter = string.Empty;
}
else
{
dataView.RowFilter = $"Nome = '{comboBox1.Text}'";
}
}
}
}
In your last comment
combo1text contains the values retrieved from the query
is fine however what I meant was what does the string itself look like. I assume it is a string that would match one of the values in the Nome column? Without seeing what this “query” strings values are in the combo box, it is difficult to give a good answer. Below, I added a DataGridView and a ComboBox to a form then populated the DataGridView and ComboBox with two DataTables using some sample data. This seems to work as you describe. I assume the row filter line: dataView.RowFilter = $"Nome = '{comboBox1.Text}'"; is simply filtering on matches in DataTables Nome column. I hope the code below helps.
DataTable dgvData;
DataTable cbData;
public Form1() {
InitializeComponent();
dgvData = GetDVGData();
cbData = GetCBData(dgvData);
dataGridView1.DataSource = dgvData;
this.comboBox1.SelectedIndexChanged -= new System.EventHandler(this.comboBox1_SelectedIndexChanged);
comboBox1.DisplayMember = "Filter";
comboBox1.ValueMember = "Filter";
comboBox1.DataSource = cbData;
this.comboBox1.SelectedIndexChanged += new System.EventHandler(this.comboBox1_SelectedIndexChanged);
}
private DataTable GetCBData(DataTable inDT) {
DataTable dt = new DataTable();
dt.Columns.Add("Filter", typeof(string));
dt.Rows.Add("Remove Filter");
foreach (DataRow dr in inDT.Rows) {
dt.Rows.Add(dr.ItemArray[1].ToString());
}
return dt;
}
private DataTable GetDVGData() {
DataTable dt = new DataTable();
dt.Columns.Add("Number");
dt.Columns.Add("Name");
dt.Columns.Add("Address");
dt.Rows.Add("1", "John", "Texas");
dt.Rows.Add("2", "Mary", "Florida");
dt.Rows.Add("3", "Tom", "New York");
dt.Rows.Add("4", "Marvin", "Moon");
dt.Rows.Add("5", "Jason", "Holland");
dt.Rows.Add("6", "Teddy", "New York");
return dt;
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) {
var dataView = ((DataTable)dataGridView1.DataSource).DefaultView;
if (comboBox1.Text == "Remove Filter") {
dataView.RowFilter = string.Empty;
}
else {
dataView.RowFilter = $"Name = '{comboBox1.Text}'";
}
}

Filter DataGrid for name with TextBox dynamically

First to my problem: Id like to filter my DataGrid with a TextBox dynamically for the Name.
My current code:
how the DataGrid is filled:
cnb1 = new MySqlConnectionStringBuilder();
cnb1.Server = "xxxxxxxxxxxxxxxxxxx";
cnb1.Database = "xxxxxxxxxxxxxxx";
cnb1.UserID = "xxxxxxxxxxxxxxxxx";
cnb1.Password = "xxxxxxxxxxxxxxxxxx";
cn1 = new MySqlConnection(cnb1.ConnectionString);
cn1.Open();
da = new MySqlDataAdapter("SELECT * FROM AktuelleDaten", cn1);
da.MissingSchemaAction = MissingSchemaAction.AddWithKey;
da.SelectCommand.ExecuteNonQuery();
ds = new DataSet();
da.Fill(ds);
hauptübersichtgrid.ItemsSource = ds.Tables[0].DefaultView;
The Code for the TextBox:
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
DataSet DV = ds;
hauptübersichtgrid.ItemsSource = DV.Tables[0].DefaultView.RowFilter = string.Format("Name like '%{0}%'", Filter.Text);
}
It looks like this:
Change your code to this:
private void TextBox_TextChanged(object sender, EventArgs e)
{
DataView dv = ds.Tables[0].DefaultView;
dv.RowFilter = string.Format("Name like '%{0}%'", Filter.Text);
hauptübersichtgrid.ItemsSource = dv;
}

how to display value in listbox from dataview

i have a textbox and listbox in a winform app. when i type a value(i.e,string) in the textbox i want the listbox to show the values from datatable and when i am selecting a particular value from listbox it will display in textbox .
code:
private void txtIName_TextChanged(object sender, EventArgs e)
{
string constring = "Data Source=.;Initial Catalog=Test;User Id=sa;Password=admin#123";
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("SELECT distinct * FROM Item_Details", con))
{
cmd.CommandType = CommandType.Text;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
using (dt = new DataTable())
{
sda.Fill(dt);
DataView dv = new DataView(dt);
dv.RowFilter = string.Format("IName Like '%{0}%'", txtIName.Text);
listBox1.Visible = true;
listBox1.DataSource = dv;
}
}
}
}
}
but i got the output in listbox like "system.data.datarow". By debugging i can seen that rows which i want, in dataview 'dv'. what i am missing here? thanks.
You don't need to load data each time the TextChanged event fires. It's enough to load data in Load event of your form and then in TextChanged just filter the data. Then using an event like DoubleClick of ListBox set the text of TextBox:
private DataTable dataTable = new DataTable();
private void Form1_Load(object sender, EventArgs e)
{
string constring = #"Data Source=.;Initial Catalog=Test;User Id=sa;Password=admin#123";
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlDataAdapter sda = new SqlDataAdapter("SELECT distinct * FROM Item_Details", con))
{
sda.Fill(dataTable);
}
}
this.listBox1.DataSource = new DataView(dataTable);
this.listBox1.DisplayMember = "IName";
this.listBox1.Visible = false;
}
private void txtIName_TextChanged(object sender, EventArgs e)
{
var dv = (DataView)this.listBox1.DataSource;
dv.RowFilter = string.Format("IName Like '%{0}%'", txtIName.Text);
listBox1.Visible = true;
}
private void listBox1_DoubleClick(object sender, EventArgs e)
{
var item = (DataRowView)listBox1.SelectedItem;
if (item != null)
this.txtIName.Text = item["IName"].ToString();
else
this.txtIName.Text = "";
this.listBox1.Visible = false;
}
Don't forget to attach Form1_Load, txtIName_TextChanged and listBox1_DoubleClick handlers to events.
You must specify your DisplayMember, it must be some Field in your DataView
listBox1.DisplayMember = "Your Field"
then you can suscribe to the event SelectedValueChanged :
listBox1.SelectedValueChanged += new EventHandler(listBox1_SelectedValueChanged);
visual studio create for you an event handler
void listBox1_SelectedValueChanged(object sender, EventArgs e)
{
// you get your selected item here
}
hope it helps

Autocomplete with Int values

I have this method auto complete for names(string),
i want to create other method that completes Int Type, i try it but it says
cannot use LIKE for int type only for string
void AutoComplete()
{
textBox1.AutoCompleteMode = AutoCompleteMode.Suggest;
textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
AutoCompleteStringCollection Collection = new AutoCompleteStringCollection();
con.Open();
cmd = new SqlCommand("select * from stagiaire",con);
dr = cmd.ExecuteReader();
while (dr.Read())
{
nom = dr.GetString(1).ToString();
Collection.Add(nom);
}
textBox1.AutoCompleteCustomSource = Collection;
con.Close();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
DataView dv = new DataView(dt);
dv.RowFilter = string.Format("nom like '{0}%'", textBox1.Text);
dataGridView1.DataSource = dv;
}
private void Form1_Load(object sender, EventArgs e)
{
da = new SqlDataAdapter("select * from stagiaire",con);
da.Fill(dt);
}
for Column with DataType INTEGER use query like this:
select * from Table where Id like 1;
or convert it in to varchar:
select * from Table where CAST(Id AS VARCHAR(45)) like '1%'

Categories