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;
}
}
Related
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")
Good day.
I just looking for a solution to my problem. I just trying to make my first program and I have encountered this problem. I have 2 comboboxes, the first one is the list of supplier and the second one is the list of items. Now I need to filter down what will show in the 2nd combobox based on the 1st combobox, but still in the 2nd combobox. It always shows all the item that is listed from my database. All data are coming from SQL Database and below is the code that I am working with:
private void comboBox3_SelectedIndexChanged(object sender, EventArgs e)
{
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from tblmaster where Supplier = '" + comboBox3.SelectedItem.ToString() + "'";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter Da = new SqlDataAdapter(cmd);
Da.Fill(dt);
foreach(DataRow dr in dt.Rows) {
comboBox5.Items.Add(dr["ProductCode"].ToString());
}
conn.Close();
}
Try to clear the items before the loop.
private void comboBox3_SelectedIndexChanged(object sender, EventArgs e)
{
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from tblmaster where Supplier = '" + comboBox3.SelectedItem.ToString() + "'";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter Da = new SqlDataAdapter(cmd);
Da.Fill(dt);
comboBox5.Items.Clear();
foreach(DataRow dr in dt.Rows) {
comboBox5.Items.Add(dr["ProductCode"].ToString());
}
conn.Close();
}
Please can you assist me in a very weird request
I am building a form to represent a table in a datagridview.
I want to change the data that is bound to the datagridview when i select a different value in a combobox. I bound the event to a button.
i get an error when i run the code:
An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll Additional information: Syntax error in query. Incomplete query clause.
the code i have is as follows.
private void Ok_button3_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(#"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = E:\database.accdb; Persist Security Info =False;");
OleDbCommand cmd = new OleDbCommand("Select * From #name ", con);
cmd.Parameters.AddWithValue("#name", comboBox1.SelectedValue);
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
dt.TableName = "Project";
dataGridView1.DataSource = dt;
}
This code will help you:
private void Ok_button3_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(#"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = E:\database.accdb; Persist Security Info =False;");
OleDbCommand cmd = new OleDbCommand(String.Concat("Select * From ",comboBox1.Text), con);
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
dt.TableName = "Project";
dataGridView1.DataSource = dt;
}
you can not pass table name as parameter. you can build sql based on your value selection in your combobox. replace your code with this code and check.
private void Ok_button3_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(#"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = E:\database.accdb; Persist Security Info =False;");
OleDbCommand cmd = new OleDbCommand(String.Concat("Select * From ",comboBox1.SelectedValue), con);
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
dt.TableName = "Project";
dataGridView1.DataSource = dt;
}
If you use Data Bound Items then use comboBox1.SelectedValue. If you use Unbound Mode then use comboBox1.SelectedItem.
private void Ok_button3_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(#"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = E:\database.accdb; Persist Security Info =False;");
//OleDbCommand cmd = new OleDbCommand("Select * From " + comboBox1.SelectedValue.ToString(), con);
OleDbCommand cmd = new OleDbCommand("Select * From " + comboBox1.SelectedItem.ToString(), con);
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
dt.TableName = "Project";
dataGridView1.DataSource = dt;
}
But not advice this way. You can use stored Procedure.
Try This:
private void Ok_button3_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(#"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = E:\database.accdb; Persist Security Info =False;");
string tableName = comboBox1.SelectedValue;
var builder = new SqlCommandBuilder();
string escapedTableName = builder.QuoteIdentifier(tableName);
OleDbCommand cmd = new OleDbCommand("Select * From " + escapedTableName , con);
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
dt.TableName = "Project";
dataGridView1.DataSource = dt;
}
I am trying to change value of a TextBox control after the value of ComboBox changes. My code returns System.Data.DataRowView on the first time ComboBox value changes.
That is why I am getting an Object instead of the actual value on first call to my combobox.
private void radioButton2_CheckedChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["myconnectionString"].ConnectionString);
con.Open();
SqlDataAdapter da = new SqlDataAdapter();
SqlCommand cmd= new SqlCommand("SELECT donor_name,ID FROM donor_detail",con);
cmd.CommandType = CommandType.Text;
da.SelectCommand = cmd;
DataTable dt = new DataTable();
da.Fill(dt);
DonorName.DataSource = dt;
DonorName.DisplayMember = "donor_name";
DonorName.ValueMember = "ID";
con.Close();
}
And this is Event of change Value of ComboBox which is supposed to change value of my TextBox also when value in ComboBox changes.
private void DonorName_SelectionChangeCommitted(object sender, EventArgs e)
{
var id = Convert.ToString(DonorName.SelectedValue);
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["myconnectionString"].ConnectionString);
con.Open();
String sql = "SELECT * from donor_detail WHERE ID=" + id + "";
SqlCommand cmd = new SqlCommand(sql,con);
SqlDataAdapter da = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
da.SelectCommand = cmd;
DataTable dt = new DataTable();
da.Fill(dt);
MessageBox.Show(sql);
mobile.Text = dt.Rows[0]["mobile"].ToString();
con.Close();
}
As mentioned here and several other places, this happens if you don't specify the datasource after the display and value members. This is the correct order:
DonorName.DisplayMember = "donor_name";
DonorName.ValueMember = "ID";
DonorName.DataSource = dt;
I'm trying to make a database search in my app where the user would choose the column and enter the search word and the result would come up in a dataviewgrid.
This is the code i've been working on, the problem is that nothing comes up and i'm pretty sure there are entries in the database. EDIT : it's a windows form application
private void button1_Click(object sender, EventArgs e)
{
conn = new SqlConnection("Server = localhost; database = Clients; Integrated Security = SSPI");
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * From dbo.Tclients WHERE #choice = #input", conn);
cmd.Parameters.AddWithValue("#choice", comboBox1.Text);
cmd.Parameters.AddWithValue("#input", textBox1.Text);
ds = new DataSet();
da = new SqlDataAdapter(cmd);
da.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
conn.Close();
}
You cannot use a parameter to express the name of a column.
You should populate your combobox with the column names and set its DropDownStyle property to DropDownList (do not allow your user to type the name of the column) and then build your query
private void button1_Click(object sender, EventArgs e)
{
string cmdText = "SELECT * From dbo.Tclients WHERE " + comboBox1.Text + " = #input";
using(SqlConnection conn = new SqlConnection(....))
using(SqlCommand cmd = new SqlCommand(cmdText, conn))
{
conn.Open();
cmd.Parameters.AddWithValue("#input", textBox1.Text);
ds = new DataSet();
da = new SqlDataAdapter(cmd);
da.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
}
}
you forgot to bind the grid view with datasource
add this after data source
dataGridView1.DataSource = ds.Tables[0];
dataGridView1.DataBind();
private void bunifuThinButton21_Click(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection();
connection.ConnectionString = (#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\albasheer\Desktop\games\my_school\my_school\school.mdf;Integrated Security=True;User Instance=True");
connection.Open();
string sql = "select name,id,stage,age,cost from STUDENT where stage like '%" + bunifuCustomLabel1.Text + "%' and name like '%" + bunifuMaterialTextbox1.Text + "%'";
SqlDataAdapter adapter = new SqlDataAdapter(sql, connection);
SqlCommand command = new SqlCommand(sql, connection);
DataTable table = new DataTable();
adapter.Fill(table);
var dt = from t in table.AsEnumerable()
select new
{
id = t.Field<int>("id"),
Name = t.Field<string>("name"),
};
bunifuCustomDataGrid1.DataSource = dt.ToList();
}