Hi StackOverflow members, I decided to build a library project to improve myself.
I created a class to code Book Operations but i couldn't find out how to fill datagrid via class method.
When i text this method into a button action it didn't work. I found out a solution to make it happen. And here's some code from my BookOperation class;
public void GetBookByName(Yönetici f1)
{
conn.Open();
SqlCommand cmd = new SqlCommand("Select * from Kitaplar where Kitap_Adi like '%" + f1.textBox1.Text.Trim() + "%'", conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
f1.dataGridView1.DataSource = dt;
conn.Close();
}
public void GetBookByAuthor(Yönetici f1)
{
conn.Open();
SqlCommand cmd = new SqlCommand("Select * from kitaplar where Yazar like '%" + f1.textBox1.Text.Trim() + "%'", conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
f1.dataGridView1.DataSource = dt;
conn.Close();
}
public void GetBookByGenre(Yönetici f1)
{
conn.Open();
SqlCommand cmd = new SqlCommand("Select * from kitaplar where Tür like '%" + f1.textBox1.Text.Trim() + "%'", conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
f1.dataGridView1.DataSource = dt;
conn.Close();
}
Yönetici is the name of my application screen of book operations.
In the button action, it includes;
Kitap_islemleri ki = new Kitap_islemleri();
ki.GetBookByName(this);
is it okay for single responsibility or is there any different way? Can you please help me?
That's kind of weird using somemethod(this), is it wrong or good for a start? what do you think. How can i get data without using (this)? If there's a way, can you hit it?
I suggest you to change your method parameters and return type with what you need. It seems your queries need just 1 criteria.
public DataTable GetBookByName(string bookName)
{
conn.Open();
SqlCommand cmd = new SqlCommand("Select * from Kitaplar where Kitap_Adi like '%" + bookName.Trim() + "%'", conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
conn.Close();
return dt;
}
So you won't need all the Yonetici page on your data access layer and with returned DataTable, you can bind it to your gridview on presentation layer.
var bookName = f1.textBox1.Text;
f1.dataGridView1.DataSource = ki.GetBookByName(bookname);
Part 2
public DataTable GetBooks(string filter, string criteria)
{
conn.Open();
SqlCommand cmd = new SqlCommand("Select * from Kitaplar where " + filter + " like '%" + criteria.Trim() + "%'", conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
conn.Close();
return dt;
}
Usage
GetBooks("Kitap_Adi", "name");
GetBooks("Yazar", "author");
GetBooks("Tür", "kind")
Related
How can I search my date into the datagrid view? I have a sample code which I think is correct but why does it not search?
private void textBox3_TextChanged(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBox3.Text))
{
SqlDataAdapter sda = new SqlDataAdapter("Select * from STUDENT_RESEARCH_PROJECTS WHERE COURSE LIKE '" + comboBox2.Text + "%'", con);
DataTable data = new DataTable();
sda.Fill(data);
dataGridView1.DataSource = data;
}
else
{
SqlDataAdapter sda = new SqlDataAdapter("SELECT ACCESSION_NO,TITLE_PROJECT,CATEGORY,YEAR,COURSE,DATE,Student_Name1,Student_Name2,Student_Name3,Student_Name4,Student_Name5,RELATED_TITLE1,RELATED_TITLE2,RELATED_TITLE3,RELATED_TITLE4,RELATED_TITLE5 FROM STUDENT_RESEARCH_PROJECTS WHERE DATE LIKE'" + textBox3.Text + "%'", con);
DataTable data = new DataTable();
sda.Fill(data);
dataGridView1.DataSource = data;
}
}
You cannot use LIKE for date comparison unless your DATE field is a string
Also you need to check how is the date data saved into database
For example in my database I am using datetime which is being saved like 2018-03-20 07:25:58.557
So when you are querying you need to put a format of your date in order to be accepted
First be aware SQL injection.
you cannot use like operator on Date Column.
Your search TextBox value date format is 03/20/2018(mm/dd/yyyy) and database column contains something different which is usually 2018-03-20 00:00:00.000 to search with the date change the format when querying from database like this.
private void textBox3_TextChanged(object sender, EventArgs e)
{
if (string.IsNullOrEmpty("textBox3.Text"))
{
string query = "Select * from STUDENT_RESEARCH_PROJECTS WHERE COURSE LIKE #COURSE";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#COURSE", comboBox2.Text);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable data = new DataTable();
sda.Fill(data);
dataGridView1.DataSource = data;
}
else
{
string query = "SELECT ACCESSION_NO,TITLE_PROJECT,CATEGORY,YEAR,COURSE,DATE,Student_Name1,Student_Name2,Student_Name3,Student_Name4,Student_Name5,RELATED_TITLE1,RELATED_TITLE2,RELATED_TITLE3,RELATED_TITLE4,RELATED_TITLE5 FROM STUDENT_RESEARCH_PROJECTS WHERE CONVERT(varchar(10) ,DATE, 101) = #DATE";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#DATE", textBox3.Text);
SqlDataAdapter sda = new SqlDataAdapter();
DataTable data = new DataTable();
sda.Fill(data);
dataGridView1.DataSource = data;
}
}
I have this code in the server side.
public DataTable DIS(int IID)
{
SqlConnection con = new
SqlConnection(Properties.Settings.Default.ADP_C1ConnectionString);
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select * from Paper";
cmd.ExecuteNonQuery();
DataTable DT = new DataTable();
SqlDataAdapter DA = new SqlDataAdapter(cmd);
DA.Fill(DT);
con.Close();
return DT;
}
I want to make the grid view in the client side take its source from that function like this:
public void dis_data()
{
DataTable DT = mgr.DIS(JouranlIID);
sda.Fill(DT);
dataGridView1.DataSource = DT;
}
How to do that?
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.
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;
It's my first time to implement INNER JOIN query in SQL.NET and C#.NET. I get this error:
A field or property with the name 'Prep_By' was not found on the selected data source.
I don't understand what is the problem, the field 'Prep_By' is existing in my database.
Here's what I got:
private void LoadFeedback()
{
con = new SqlConnection(Connectiontxt);
con.Open();
SqlCommand cmd;
if (seardata == "")
{
cmd = new SqlCommand("SELECT [Articles_Tbl].[Article_ID], [Articles_Tbl].[Title], [Articles_Tbl].[Mod_Date], [Users_Tbl].[Name] FROM [Articles_Tbl] INNER JOIN [Users_Tbl] ON [Users_Tbl].[User_ID] = [Articles_Tbl].[Prep_By] where [Articles_Tbl].[Status] = 'Approved' and (Article_ID = '')", con);
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "ss");
gridrfqheader0.DataSource = ds.Tables["ss"];
gridrfqheader0.DataBind();
}
else {
cmd = new SqlCommand("SELECT [Articles_Tbl].[Article_ID], [Articles_Tbl].[Title], [Articles_Tbl].[Mod_Date], [Users_Tbl].[Name] FROM [Articles_Tbl] INNER JOIN [Users_Tbl] ON [Users_Tbl].[User_ID] = [Articles_Tbl].[Prep_By] where [Articles_Tbl].[Status] = 'Approved' and (Article_ID LIKE '%" + seardata + "%' or Title LIKE '%" + seardata + "%')", con);
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "ss");
gridrfqheader0.DataSource = ds.Tables["ss"];
gridrfqheader0.DataBind();
}
}
It means that gridrfqheader0 contains a binding reference to Prep_By, but you are not including it in your SELECT statement.
Try adding it:
cmd = new SqlCommand("SELECT [Articles_Tbl].[Prep_By], [Articles_Tbl].[Article_ID])...
As a side note, your conditional statements contain a lot of duplicate code. Consider moving the code that gets data into one location so that you do't have duplicate code. For example:
if (isNullOrEmpty(seardata))
{
cmd = new SqlCommand(your query);
}
else
{
cmd = new SqlCommand(your other query);
}
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "ss");
gridrfqheader0.DataSource = ds.Tables["ss"];
gridrfqheader0.DataBind();
It can be further refactored, but this is a good start.
You are using Dataset to bind Grid, and in Grid you are using [Prep_By] field which not in your dataset.
So Simply just
Add "[Articles_Tbl].[Prep_By]" in your select statenment.
cmd = new SqlCommand("SELECT [Articles_Tbl].[Prep_By], [Articles_Tbl].[Article_ID], [Articles_Tbl].[Title], [Articles_Tbl].[Mod_Date], [Users_Tbl].[Name] FROM [Articles_Tbl] INNER JOIN [Users_Tbl] ON [Users_Tbl].[User_ID] = [Articles_Tbl].[Prep_By] where [Articles_Tbl].[Status] = 'Approved' and (Article_ID = '')", con);
make change in both sql queries..
If the grid has the column created with the source name Prep_By you have to select that column from the database.