C# (Search button) that have a function of contains - c#

How to do searching even though it isn't exact but will show in the datagridview
Datagridview
Database
OleDbCommand cmdDatabase = new OleDbCommand("Select User_ID, Firstname, Lastname, Pass, Account_Type from Account where Lastname'"+textBox1.Text+"'", con);
try
{
OleDbDataAdapter sda = new OleDbDataAdapter();
sda.SelectCommand = cmdDatabase;
DataTable dbdataset = new DataTable();
sda.Fill(dbdataset);
BindingSource bSource = new BindingSource();
bSource.DataSource = dbdataset;
dataGridView1.DataSource = bSource;
sda.Update(dbdataset);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

You can use LIKE in the SQL Statement, the % indicates any value before or after the text, so % before the text would accept "asdsad cavite" and the % after the text would accept "cavite dagma" - both together accept both ("asd CAVITE asd").
More to LIKE: SQL LIKE Operator
OleDbCommand cmdDatabase = new OleDbCommand("SELECT User_ID, Firstname, Lastname, Pass, Account_Type FROM Account WHERE Lastname LIKE %'"+textBox1.Text+"%'", con);
try
{
OleDbDataAdapter sda = new OleDbDataAdapter();
sda.SelectCommand = cmdDatabase;
DataTable dbdataset = new DataTable();
sda.Fill(dbdataset);
BindingSource bSource = new BindingSource();
bSource.DataSource = dbdataset;
dataGridView1.DataSource = bSource;
sda.Update(dbdataset);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

I don't know if I've got you right, but if you want a 'contains' like search you can use
OleDbCommand cmdDatabase = new OleDbCommand("Select User_ID, Firstname, Lastname, Pass, Account_Type from Account where Lastname LIKE '%"+textBox1.Text+"%'", con);
keyword is Wildcards
your SQL-statement provides potential for sql-injection by the way

Perhaps something like this:
using(OleDbConnection conn = new OleDbConnection(connString))
{
conn.Open();
using(OleDbCommand cmd = new OleDbCommand()){
DataTable table = null;
cmd.Connection = conn;
table = new DataTable();
cmd.CommandText = String.Format("SELECT SifraPacijenta, Ime, Prezime, DatumRodjenja, Adresa, Telefon FROM Pacijenti WHERE Ime + ' ' + Prezime LIKE '%{0}%' ORDER BY SifraPacijenta", tbPretragaImePrezime.Text);
da = new OleDbDataAdapter(cmd);
da.Fill(table);
}
}
conn.Close();
gridPacijenti.DataSource = table;

Related

How to search between two dates?

I'm really having a bad time when my code doesn't work. Can anybody help me on how to search between two dates using datetimepicker? I have a source code that retrieve the data from database but when I add the "between" in where clause, the data that I want to search, it won't display in datagridview. Also, I tried already putting "MM/dd/yyyy" in the tostring().
Code to retrieve data:
public void showData()
{
string constring = "datasource = localhost;port = 3307; username = root; password =root; database = dbpetsales";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand("SELECT transaction_ID as 'Transaction ID', ProdName as 'Product Name',price as 'Price',subtotal as 'Subtotal', Date FROM dbpetsales.pos", conDataBase);
try
{
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = cmdDataBase;
dbdataset = new DataTable();
sda.Fill(dbdataset);
BindingSource bSource = new BindingSource();
bSource.DataSource = dbdataset;
dataGridView1.DataSource = bSource;
sda.Update(dbdataset);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Code to retrieve data in searching between two dates:
public void showData()
{
string constring = "datasource = localhost;port = 3307; username = root; password =root; database = dbpetsales";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand("SELECT transaction_ID as 'Transaction ID', ProdName as 'Product Name',price as 'Price',subtotal as 'Subtotal', Date FROM dbpetsales.pos where Date between '"+this.dateTimePicker1.Value.ToString()+"' and '"+this.dateTimePicker2.Value.ToString()+"' ", conDataBase);
try
{
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = cmdDataBase;
dbdataset = new DataTable();
sda.Fill(dbdataset);
BindingSource bSource = new BindingSource();
bSource.DataSource = dbdataset;
dataGridView1.DataSource = bSource;
sda.Update(dbdataset);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
First, please use parameters instead of string concat in your query (to prevent sql-injection and send date as dates, no string ), just do like below:
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand("SELECT transaction_ID as 'Transaction ID', ProdName as 'Product Name',price as 'Price',subtotal as 'Subtotal', Date FROM dbpetsales.pos where Date >= #date1 and Date <= #date2, conDataBase);
cmdDataBase.Parameters.AddWithValue("#date1", dateTimePicker1.Value);
cmdDataBase.Parameters.AddWithValue("#date1", dateTimePicker2.Value);

C# MYSQL - Search filtering a datagridview with a combobox and textbox

Hi I'm trying to search filter a datagridview by using a combobox and textbox.
I have successfully done so but it only works properly when I search for the ID column. Other columns just crash display the following message:
You have an error in your SQL syntax; check the manual that
corresponds to your MariaDB server version for the right syntax to use
near 'Name LIKE 'd%'' at line 1
The d letter in that error message is just the letter I was trying to filter the search with.
Could somebody please help me solve this issue?
My code is below
string myConnection = "datasource=localhost;port=3306;username=root;password=;";
MySqlConnection conDatabase = new MySqlConnection(myConnection);
try
{
if (comboBoxSrchPatient.Text == "ID")
{
MySqlCommand cmd = new MySqlCommand("select * from clinic_inventory_system.patient WHERE ID LIKE '" + txtSearchPatient.Text + "%'", conDatabase);
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = cmd;
DataTable dbdataset = new DataTable();
sda.Fill(dbdataset);
dataPatientGridView.DataSource = dbdataset;
}
else if (comboBoxSrchPatient.Text == "FIRST NAME")
{
MySqlCommand cmd = new MySqlCommand("select * from clinic_inventory_system.patient WHERE First Name LIKE '" + txtSearchPatient.Text + "%'", conDatabase);
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = cmd;
DataTable dbdataset = new DataTable();
sda.Fill(dbdataset);
dataPatientGridView.DataSource = dbdataset;
}
else if (comboBoxSrchPatient.Text == "LAST NAME")
{
MySqlCommand cmd = new MySqlCommand("select * from clinic_inventory_system.patient WHERE Last Name LIKE '" + txtSearchPatient.Text + "%'", conDatabase);
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = cmd;
DataTable dbdataset = new DataTable();
sda.Fill(dbdataset);
dataPatientGridView.DataSource = dbdataset;
}
else if (comboBoxSrchPatient.Text == "AGE")
{
MySqlCommand cmd = new MySqlCommand("select * from clinic_inventory_system.patient WHERE Age LIKE '" + txtSearchPatient.Text + "%'", conDatabase);
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = cmd;
DataTable dbdataset = new DataTable();
sda.Fill(dbdataset);
dataPatientGridView.DataSource = dbdataset;
}
else if (comboBoxSrchPatient.Text == "CONTACT NUMBER")
{
MySqlCommand cmd = new MySqlCommand("select * from clinic_inventory_system.patient WHERE Contact Number LIKE '" + txtSearchPatient.Text + "%'", conDatabase);
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = cmd;
DataTable dbdataset = new DataTable();
sda.Fill(dbdataset);
dataPatientGridView.DataSource = dbdataset;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Your field names contains spaces.
To use them in a query your need to enclose them between backticks (ALT+096)
MySqlCommand cmd = new MySqlCommand(#"select * from
clinic_inventory_system.patient WHERE `Last Name` LIKE ....";
Said that, consider, as soon as possible, to change your queries to use a parameterized query
using(MySqlCommand cmd = new MySqlCommand(#"select * from
clinic_inventory_system.patient
WHERE `First Name` LIKE #name", conDatabase);
{
cmd.Parameters.Add("#name", MySqlDbType.VarChar).Value = txtSearchPatient.Text + "%";
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = cmd;
DataTable dbdataset = new DataTable();
sda.Fill(dbdataset);
dataPatientGridView.DataSource = dbdataset;
}
In this way your code is safer because it is no more possible to build an Sql Injection attack against your db and, if the First Name contains a single quote, you don't have a syntax error again
First of all, with First Name, Last Name and Contact Number, you need to escape the columns correctly.
Since you're using MariaDB, you should use backticks (`) to escape the column names.
Secondly, your Age query fails because you can't perform a LIKE on a numeric column. You should use = (equals).
Hope that helps.
Also, considering switching to prepared statements if you're using data the user has provided directly in your SQL. At the moment, you're open to SQL Injection.
you should listen to Huw Jones.
you dont want to get audited by a security firm and have sql injection problems. Parameterized your query is mySql supports it.

updating datagridview from many tables

I have datagridview, that i must fill by 5 tables. I declared SqlCommand and SqlConnection.
After that I use somethine like this:
selCommand.Connection = conn;
dt = new DataTable();
SqlDataAdapter ad = new SqlDataAdapter();
ad.SelectCommand = selCommand;
ad.Fill(dt);
dataGridView1.DataSource = dt;
As a result I have column headers of my query in datagridview, but don't have data.
I tried use this code:
selCommand.Connection = conn;
dt = new DataTable();
SqlDataReader dr = selCommand.ExecuteReader();
dt.Load(dr);
bs = new BindingSource();
bs.DataSource = dt;
dataGridView1.DataSource = bs;
dr.Close();
It was working, but I something change and I can't understand why it does not work.
Try this:
DataTable table = null;
using (SqlConnection connection = new SqlConnection(this.connectionString))
{
try
{
connection.Open();
SqlCommand cmd = connection.CreateCommand();
cmd.CommandText = "SELECT * FROM Something WHERE Id = #Id";
cmd.Parameters.Add(new SqlParameter("#Id", YourValue));
using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
{
table = new DataTable();
adapter.Fill(table);
}
}
catch (Exception ex)
{
//Handle your exception;
}
}
dataGridView1.DataSource = table;

how to display data from multiple tables to dataGridView

I want to display the phonebook and email data in one dataGridView. and the problem is it will only display the email table
MySqlConnection connection = new MySqlConnection(MyConnectionString);
connection.Open();
try
{
MySqlCommand cmd = connection.CreateCommand();
cmd.CommandText = "SELECT * FROM phonebook";
cmd.CommandText = "SELECT * FROM email";
MySqlDataAdapter adap = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
adap.Fill(ds);
dataGridView1.DataSource = ds.Tables[0].DefaultView;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (connection.State == ConnectionState.Open)
{
connection.Clone();
}
}
you need to join two tables and fetch the results as below
using(MySqlConnection connection = new MySqlConnection(MyConnectionString))
using(MySqlCommand cmd = connection.CreateCommand())
{
connection.Open();
cmd.CommandText = "SELECT pb.Id, pb.Name, pb.MobileNo, e.email FROM phonebook pb INNER JOIN email e ON e.Id= pb.Id";
MySqlDataAdapter adap = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
adap.Fill(ds);
dataGridView1.DataSource = ds.Tables[0].DefaultView;
}

how can i fill a combobox using a select C#

I am using the next code.
public void MostrarCombobox(ComboBox cmbIDart)
{
Command = "SELECT idArtigoAvaliar FROM dbo.PorAvaliasao WHERE (avaliado = 0) AND (idAutor ='" + Autor.id2 + "')";
SqlCommand Comm1 = new SqlCommand(Command, Conn);
SqlDataAdapter data = new SqlDataAdapter(Comm1);
SqlCommand sqlCommand = new SqlCommand();
using (Conn)
{
sqlCommand = Conn.CreateCommand();
sqlCommand.CommandText = Command;
SqlDataAdapter sda = new SqlDataAdapter(sqlCommand.CommandText, Conn);
SqlCommandBuilder scb = new SqlCommandBuilder(sda);
//Criar uma tabela para receber os dados
DataTable dTable = new DataTable();
//Preencher a tabela
sda.Fill(dTable);
BindingSource bSource = new BindingSource();
bSource.DataSource = dTable;
cmbIDart.DataSource = bSource;
Conn.Close();
}
}
My problem is that when I am starting to call the ComboBox, it shows System.Data... and I want them to show the value.
What am I doing wrong?
I think in your combobox rows look like showing like;
System.Data.DataRowView
System.Data.DataRowView
System.Data.DataRowView
System.Data.DataRowView
System.Data.DataRowView
You need to set your Combobox DisplayMember and ValueMember properties.
If this is not fix your problem, try to make things more clear dynamically.
Combobox1.Items.Clear();
string Command = "SELECT idArtigoAvaliar FROM dbo.PorAvaliasao WHERE (avaliado = 0) AND (idAutor ='" + Autor.id2 + "')";
SqlCommand cmd = new SqlCommand(Command, Conn);
cmd.CommandText = Command;
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Combobox1.Items.Add(dr["idArtigoAvaliar"].ToString());
}

Categories

Resources