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);
Related
Why do I get blank rows when I retrieve rows from MySQL database to dataGridView? I end up getting the amount of rows but its empty (it has no text).
this is my code so far:
private void button2_Click(object sender, EventArgs e)
{
string constring = "Data Source = localhost; port = 3306; username = root; password = 0159";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand("Select * FROM TopShineDB.Table1 ;", conDataBase);
using (MySqlConnection conn = new MySqlConnection(constring))
{
try
{
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = cmdDataBase;
DataTable dt = new DataTable();
sda.Fill(dt);
BindingSource bs = new BindingSource();
bs.DataSource = dt;
dataGridView1.DataSource = bs;
sda.Update(dt);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
I tried below code sample to get data from database and bind to datagridview.
var ConnectionString = "your ConnectionString";
MySqlConnection connect = new MySqlConnection(ConnectionString);
MySqlCommand cmd = new MySqlCommand("your query");
connect.Open();
MySqlDataAdapter adp = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds);
DataTable dt = new DataTable();
dt = DtSet.Tables[0];
dataGridView1.DataSource = DtSet.Tables[0];
connect.Close();
Try This:
private void BindGrid()
{
string conString = #"Data Source=localhost;port=3306;Initial Catalog=TopShineDB;User Id=root;password=0159";
using (MySqlConnection con = new MySqlConnection(conString))
{
using (MySqlCommand cmd = new MySqlCommand("SELECT * FROM Table1", con))
{
cmd.CommandType = CommandType.Text;
using (MySqlDataAdapter sda = new MySqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
dataGridView1.DataSource = dt;
}
}
}
}
}
*Just Clear your Columns you define in DataGridView *
private void button2_Click(object sender, EventArgs e)
{
string constring = "Data Source = localhost; port = 3306; username = root; password = 0159";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand("Select * FROM TopShineDB.Table1 ;", conDataBase);
using (MySqlConnection conn = new MySqlConnection(constring))
{
try
{
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = cmdDataBase;
DataTable dt = new DataTable();
sda.Fill(dt);
dataGridView1.Columns.Clear();
dataGridView1.DataSource = bs;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
c#
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.
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 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;
I'm trying to present query results, but I keep getting a blank data grid.
It's like the data itself is not visible
Here is my code:
private void Employee_Report_Load(object sender, EventArgs e)
{
string select = "SELECT * FROM tblEmployee";
Connection c = new Connection();
SqlDataAdapter dataAdapter = new SqlDataAdapter(select, c.con); //c.con is the connection string
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(table);
bindingSource1.DataSource = table;
dataGridView1.ReadOnly = true;
dataGridView1.DataSource = bindingSource1;
}
What's wrong with this code?
Here's your code fixed up. Next forget bindingsource
var select = "SELECT * FROM tblEmployee";
var c = new SqlConnection(yourConnectionString); // 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];
String strConnection = Properties.Settings.Default.BooksConnectionString;
SqlConnection con = new SqlConnection(strConnection);
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = con;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "Select * from titles";
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);
DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
dataGridView1.DataSource = dtRecord;
You don't need bindingSource1
Just set dataGridView1.DataSource = table;
Try binding your DataGridView to the DefaultView of the DataTable:
dataGridView1.DataSource = table.DefaultView;
This is suppose to be the safest and error pron query :
public void Load_Data()
{
using (SqlConnection connection = new SqlConnection(DatabaseServices.connectionString)) //use your connection string here
{
var bindingSource = new BindingSource();
string fetachSlidesRecentSQL = "select top (50) * from dbo.slides order by created_date desc";
using (SqlDataAdapter dataAdapter = new SqlDataAdapter(fetachSlidesRecentSQL, connection))
{
try
{
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
DataTable table = new DataTable();
dataAdapter.Fill(table);
bindingSource.DataSource = table;
recent_slides_grd_view.ReadOnly = true;
recent_slides_grd_view.DataSource = bindingSource;
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message.ToString(), "ERROR Loading");
}
finally
{
connection.Close();
}
}
}
}
You may get a blank data grid if you set the data Source to a Dataset that you added to the form but is not being used. Set this to None if you are programatically setting your dataSource based on the above codes.
You may try this sample, and always check your Connection String, you can use this example with or with out bindingsource you can load the data to datagridview.
private void Employee_Report_Load(object sender, EventArgs e)
{
var table = new DataTable();
var connection = "ConnectionString";
using (var con = new SqlConnection { ConnectionString = connection })
{
using (var command = new SqlCommand { Connection = con })
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
con.Open();
try
{
command.CommandText = #"SELECT * FROM tblEmployee";
table.Load(command.ExecuteReader());
bindingSource1.DataSource = table;
dataGridView1.ReadOnly = true;
dataGridView1.DataSource = bindingSource1;
}
catch(SqlException ex)
{
MessageBox.Show(ex.Message + " sql query error.");
}
}
}
}
you have to add the property Tables to the DataGridView Data Source
dataGridView1.DataSource = table.Tables[0];
if you are using mysql this code you can use.
string con = "SERVER=localhost; user id=root; password=; database=databasename";
private void loaddata()
{
MySqlConnection connect = new MySqlConnection(con);
connect.Open();
try
{
MySqlCommand cmd = connect.CreateCommand();
cmd.CommandText = "SELECT * FROM DATA1";
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
datagrid.DataSource = dt;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Years late but here's the simplest for others in case.
String connectionString = #"Data Source=LOCALHOST;Initial Catalog=DB;Integrated Security=true";
SqlConnection cnn = new SqlConnection(connectionString);
SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM tblEmployee;", cnn);
DataTable data = new DataTable();
sda.Fill(data);
DataGridView1.DataSource = data;
Using DataSet is not necessary and DataTable should be good enough. SQLCommandBuilder is unnecessary either.
I think this professional way to Write from start, but you can use this code with MySQL bout I think they both are the same:
1/
using System.Data; AND using MySql.Data.MySqlClient;
2/
MySqlConnection con = new MySqlConnection("datasource=172.16.2.104;port=3306;server=localhost;database=DB_Name=root;password=DB_Password;sslmode=none;charset=utf8;");
MySqlCommand cmd = new MySqlCommand();
3/
public void SetCommand(string SQL)
{
cmd.Connection = con;
cmd.CommandText = SQL;
}
private void FillGrid()
{
SetCommand("SELECT * FROM `transport_db`ORDER BY `id` DESC LIMIT 15");
DataTable tbl = new DataTable();
tbl.Load(cmd.ExecuteReader());
dataGridView1.DataSource = tbl;
}
for oracle:
var connString = new ConfigurationBuilder().AddJsonFile("AppSettings.json").Build()["ConnectionString"];
OracleConnection connection = new OracleConnection();
connection.ConnectionString = connString;
connection.Open();
var dataAdapter = new OracleDataAdapter("SELECT * FROM TABLE", connection);
var dataSet = new DataSet();
dataAdapter.Fill(dataSet);