C# and Access Data Base Searching Via Name - c#

Searching via the InqID is working properly but when I give the code to Search with InqName it gives me an error (All connections are given Properly I guess) Thanks..
ERROR DETAILS
An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
Additional information: No value given for one or more required parameters.
private void btnSearch_Click(object sender, EventArgs e)
{
DA.SelectCommand = new OleDbCommand("SELECT * FROM INQUIREt WHERE InqID=" +txtInqID.Text, CON);
DS.Clear();
DA.Fill(DS);
dataGridView.DataSource = DS.Tables[0];
CON.Open();
DA.SelectCommand.ExecuteNonQuery();
CON.Close();
}
private void btnNameSearch_Click(object sender, EventArgs e)
{
DA.SelectCommand = new OleDbCommand("SELECT * FROM INQUIREt WHERE InqName=" + txtInqName.Text, CON);
DS.Clear();
DA.Fill(DS);
dataGridView.DataSource = DS.Tables[0];
CON.Open();
DA.SelectCommand.ExecuteNonQuery();
CON.Close();
}

Most of the answers tell you that you should use parameters and that is good.
They also tell you that it would be correct if you included single quotes around it, which is incorrect. Adding single quotes is NOT a solution and would only work for some values (well many but not all) and is wide open to SQL injection attack.
There is only one way of doing it correct and that is to use parameters. With OleDb the parameters are NOT named but positional. With access however you can use named parameters by prefixing them with #.
private void btnSearch_Click(object sender, EventArgs e)
{
DA.SelectCommand = new OleDbCommand("SELECT * FROM INQUIREt WHERE InqID=#ID", CON);
DA.SelectCommand.Parameters.Add("#ID", OleDbType.VarChar).Value = txtInqID.Text;
DS.Clear();
DA.Fill(DS);
dataGridView.DataSource = null;
dataGridView.DataSource = DS.Tables[0];
}
private void btnNameSearch_Click(object sender, EventArgs e)
{
DA.SelectCommand = new OleDbCommand("SELECT * FROM INQUIREt WHERE InqName=#name", CON);
DA.SelectCommand.Parameters.Add("#name", OleDbType.VarChar).Value = txtInqName.Text;
DS.Clear();
DA.Fill(DS);
dataGridView.DataSource = null;
dataGridView.DataSource = DS.Tables[0];
}
PS: You are using DataSet and DataAdapter in a weird way, but that is acceptable and works.

You are not specifying the search string parameter, you should add quotes as follows:
DA.SelectCommand = new OleDbCommand("SELECT * FROM INQUIREt WHERE InqName='" + txtInqName.Text + "'", CON);
However, constructing the query string as string is not an effective and readable way, the good practice is to use OleDbParameters as follows:
DA.SelectCommand = new OleDbCommand("SELECT * FROM INQUIREt WHERE InqName=?", CON);
DA.SelectCommand.Parameters.AddWithValue("?", txtInqName.Text);

You are missing quotes that enclose your txtInqID.Text and InqName.Text values in your query:
DA.SelectCommand = new OleDbCommand("SELECT * FROM INQUIREt WHERE InqID = '" + txtInqID.Text + "'", CON);
DA.SelectCommand = new OleDbCommand("SELECT * FROM INQUIREt WHERE InqName = '" + txtInqName.Text + "'", CON);
Also building dynamically your query string like that is a very bad practice. Consider using command parameters instead:
DA.SelectCommand = new OleDbCommand("SELECT * FROM INQUIREt WHERE InqID = ?", CON);
DA.SelectCommand.Parameters.Add("InqID").Value = txtInqID.Text;
DA.SelectCommand = new OleDbCommand("SELECT * FROM INQUIREt WHERE InqName = ?" , CON);
DA.SelectCommand.Parameters.Add("InqName").Value = txtInqName.Text;

You need to surround the value of Name in quotes but it would be better to use Parameterized Sql.
DA.SelectCommand = new OleDbCommand("SELECT * FROM INQUIREt WHERE InqName=#Name " , CON);
DS.Clear();
DA.SelectCommand.Parameters.AddWithValue("#Name",txtInqName.Text);
DA.Fill(DS);
dataGridView.DataSource = DS.Tables[0];
Also you don't need below code as data is already selected using DataAdapter
CON.Open();
DA.SelectCommand.ExecuteNonQuery();
CON.Close();

Related

Search in the database

This Messages form display table with these informations (ID,FROM,TO,TITLE,MESSAGE).
I am trying to search for all the messages send to a certain user . user will enter his name in the Search_textBox then it will filter the table to keep only messages to this user.
private void Search_button_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = cmd.CommandText = "Select * from MessagesTable where To =" + Search_textBox.Text;
cmd.Parameters.AddWithValue("#To", Search_textBox.Text);
DataSet dataSet = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dataSet);
dataGridView1.DataSource = dataSet.Tables[0];
}
I get this error :
System.Data.SqlClient.SqlException: 'Invalid column name 'To'.'
What does the "search_name" parameter contains? The Message? The Column Name?
Your query is
Select * from MessagesTable where " + search_name + " = #From"
Then you specifies the "search_name" as a parameter for the #From...
So I believe your input was "Name" and your query is looked like this now:
Select * from MessagesTable where Name = 'Name';
You do not have any Name column in this specified table as you described.
this is Correct
private void Search_button_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select * from MessagesTable where [To]= #To";
cmd.Parameters.AddWithValue("#To", Search_textBox.Text);
DataSet dataSet = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dataSet);
dataGridView1.DataSource = dataSet.Tables[0];
}
You can change it as follows. Of course, if I understand correctly, that you want to search in the messages field by the input you get from the user.
private void Search_button_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select * from MessagesTable where MESSAGE = #From";
cmd.Parameters.AddWithValue("#From", search_name);
DataSet dataSet = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dataSet);
dataGridView1.DataSource = dataSet.Tables[0];
}
Try with To, because "To" - keyword SQL:
cmd.CommandText = cmd.CommandText = "Select * from MessagesTable where [To] =" + Search_textBox.Text;

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.

SQL Datareader failed to bind data to GridView

protected void Button1_Click(object sender, EventArgs e)
{
string query = "select * from aspnet_Users where userName like '%#UserName%'";
connection.Open();
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.Add("#UserName", SqlDbType.NVarChar).Value = TextBox1.Text;
SqlDataReader reader = command.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();
connection.Close();
}
I am trying to use connected model to search a user's data in a table but the GridView is always, never fills with data.
You parameter is acting as a string in your query because of single quotes you have include around the parameter. That is the reason it is not able to identify the parameter. Try this:-
string query = "select * from aspnet_Users where userName LIKE #UserName";
Then add it as parameter like this:-
command.Parameters.Add("#MyName",SqlDBType.NVarChar,40).Value ="%" + TextBox1.Text + "%";
You can populate gridview using SqlDataAdapter, your code look like this
string query = "select * from aspnet_Users where userName like '%#UserName%'";
SqlCommand cmd = new SqlCommand();
cmd.CommandText = query;
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#UserName", TextBox1.Text);
cmd.Connection = conn;
SqlDataAdapter dap = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
dap.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();

How to bind grid view data based on the dropdown list selected value

I have one drop down list to select student name.when i select a student name in the drop down list, grid view has to show details of selected name.
This is my coding for this but it didn't display anything.
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MGLCOMConnectionString"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("SELECT VALUE,VDESC FROM CSOPTFD WHERE OPTFIELD='WONO'AND VALUE LIKE '%" + customerddl.SelectedValue + "%'", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
this is my cs code to get the details of selected value.But it didn't any thing.
VALUE is a reserved keyword for T-SQL. Use it with square brackets like [VALUE]
And please use parameterized queries instead. This kind of string concatenations are open for SQL Injection attacks.
SqlCommand cmd = new SqlCommand("SELECT [VALUE], VDESC FROM CSOPTFD WHERE OPTFIELD = 'WONO' AND [VALUE] LIKE '%' + #value + '%'", con);
cmd.Parameters.AddWithValue("#value", customerddl.SelectedValue);
Have you bind Dropdown Correctly,like CustomerId , Text and after that are you calling this code from Selected_Index_Changed Event with PostBack True ?
Try providing the code in a try - catch block. Use the finally block to closed the connection by using con.Close();
Also try closing the connection and then accessing the dataset for values.
SqlConnection con =null;
DataSet ds=null;
try
{
con = new SqlConnection(ConfigurationManager.ConnectionStrings["MGLCOMConnectionString"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("SELECT VALUE,VDESC FROM CSOPTFD WHERE OPTFIELD='WONO'AND VALUE LIKE '%" + customerddl.SelectedValue + "%'", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
ds = new DataSet();
da.Fill(ds);
}
catch(SQLException ex)
{
}
finally
{
if(con!=null)
con.Close();
}
GridView1.DataSource = ds;
GridView1.DataBind();

c# Using Parameters.AddWithValue in SqlDataAdapter

How can I use Parameters.AddWithValue with an SqlDataAdapter. Below searching codes.
var da = new SqlDataAdapter("SELECT * FROM annotations WHERE annotation LIKE '%"+txtSearch.Text+"%'", _mssqlCon.connection);
var dt = new DataTable();
da.Fill(dt);
I rewrote the code like this:
SqlDataAdapter da;
da = new SqlDataAdapter("SELECT * FROM annotations WHERE annotation LIKE '%#search%'", _mssqlCon.connection);
da.SelectCommand.Parameters.AddWithValue("#search",txtSearch.Text);
var dt = new DataTable();
da.Fill(dt);
but it failed.
The string used to initialize the SqlDataAdapter becomes the CommandText of the SelectCommand property of the SqlDataAdapter.
You could add parameters to that command with this code
da = new SqlDataAdapter("SELECT * FROM annotations WHERE annotation LIKE #search",
_mssqlCon.connection);
da.SelectCommand.Parameters.AddWithValue("#search","%" + txtSearch.Text + "%");
First, remove the single quote around the parameter placeholder.
Second, add the wildcard character directly in the Value parameter of
AddWithValue
You have asked to use AddWithValue, but remember that, while it is a useful shortcut, there are also numerous drawbacks and all well documented.
First: Can we stop using AddWithValue() already? where the
author discuss how AddWithValue could give back wrong results in your
queries
Second: How Data Access Code Affects Database Performance where
the author presents evidences of strong performance problems for
AddWithValue
So, the same code without AddWithValue and using the Object and Collection Initializers syntax could be written as
da = new SqlDataAdapter("SELECT * FROM annotations WHERE annotation LIKE #search",
_mssqlCon.connection);
da.SelectCommand.Parameters.Add(new SqlParameter
{
ParameterName = "#search",
Value = "%" + txtSearch.Text + "%",
SqlDbType = SqlDbType.NVarChar,
Size = 2000 // Assuming a 2000 char size of the field annotation (-1 for MAX)
});
and, an even more simplified and one liner version of the above is:
da.SelectCommand.Parameters.Add("#search",SqlDbType.NVarChar,2000).Value = "%" + txtSearch.Text + "%";
Use da.SelectCommand.Parameters.Add() instead of cmd.Parameters.Add(), here's a sample for dealing with a stored procedure which takes two parameters and second one is a nullable int parameter:
public DataTable GetData(int par1, int? par2)
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlDataAdapter da = new SqlDataAdapter())
{
string sql = "StoredProcedure_name";
da.SelectCommand = new SqlCommand(sql, conn);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.Parameters.Add("#Par1", SqlDbType.Int).Value = par1;
da.SelectCommand.Parameters.Add("#Par2", SqlDbType.Int).Value = (object)par2?? DBNull.Value;
DataSet ds = new DataSet();
da.Fill(ds, "SourceTable_Name");
DataTable dt = ds.Tables["SourceTable_Name"];
//foreach (DataRow row in dt.Rows)
//{
//You can even manipulate your data here
//}
return dt;
}
}
}
Try this:
mySearchString = "Select * From test Where ([title] LIKE '%' + #title + '%')";
cmd.Parameters.Add("#title", SqlDbType.VarChar, 120);
cmd.Parameters("#title").Value = TextBox1.Text;
I use Repeater for show data
int queryString =int.Parse(Request.QueryString["Id"]);
SqlConnection conn =new SqlConnection("server=.; Database=Northwind;
Integrated Security=true;");
try{
conn.Open();
SqlDataAdapter dataAdapter = new SqlDataAdapter("SELECT ProductID, ProductName, UnitPrice, CategoryID FROM Products WHERE CategoryID =#CategoryID", conn);
dataAdapter.SelectCommand.Parameters.Add("#CategoryID", queryString);
DataSet dataSet = new DataSet();
dataAdapter.Fill(dataSet);
QueryStringProductListRepeater.DataSource = dataSet;
QueryStringProductListRepeater.DataBind();
}
catch{
Response.Write("QueryStringProductListRepeater");
}
finally{
conn.Close();
}

Categories

Resources