c# Using Parameters.AddWithValue in SqlDataAdapter - c#

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();
}

Related

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.

A field or property with the name <variable> was not found on the selected data source

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.

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();

How use WHERE in SqlDataAdapter in C#

How use WHERE in SqlDataAdapter in C#?
I want get name in a textbox and use that at query but it wont work .
SqlConnection sqlconnection = new SqlConnection("Server=Behnam\\Accounting;Initial Catalog=Accounting;Integrated Security=TRUE");
DataTable dt = new DataTable();
string _search_name = txt_search.Text;
SqlDataAdapter SDA = new SqlDataAdapter("SELECT dbo.tbl_user.field1,dbo.tbl_user.field2 FROM tbl_user WHERE dbo.tbl_user.name=_search_name ", sqlconnection);
SDA.Fill(dt);
dataGridView1.DataSource = dt;
Prepare the command text and use a parameter for the value of your search.
Then use that command text to initialize a new SqlCommand. Fill the parameter value with AddWithValue and pass the SqlCommand to the constructor of the SqlDataAdapter.
string cmdText = "SELECT dbo.tbl_user.field1,dbo.tbl_user.field2 " +
"FROM tbl_user WHERE dbo.tbl_user.name=#search_name"
SqlCommand cmd = new SqlCommand(cmdText, sqlconnection);
cmd.Parameters.AddWithValue("#search_name", _search_name);
SqlDataAdapter SDA = new SqlDataAdapter(cmd);
The SqlDataAdapter will store your command as the SelectCommand property and will use the passed in SqlCommand to execute the query to retrieve the records from the database.
Keep in mind that AddWithValue is a shortcut with some drawbacks. For example it pass Always a string as a nvarchar parameter with size equal to the actual lenght of the variable. This effectively reduces the performance of the Sql Server Optimizer.
This is a very enlightening article on the issue
So, you were pretty close, you just needed to define a parameter inside the query and then add that parameter. However, in the following code block I've also conveniently recommended a more appropriate approach to using the classes needed to get the data (pun intended). The using statement here ensures that the objects get disposed of properly after you are done using them (man I just can't stop with the puns!)
using (SqlConnection c = new SqlConnection(connString))
{
c.Open();
using (SqlDataAdapter sda = new SqlDataAdapter(
"SELECT dbo.tbl_user.field1, dbo.tbl_user.field2 FROM tbl_user " +
"WHERE dbo.tbl_user.name= #name", c))
{
sda.SelectCommand.Parameters.AddWithValue("#name", txt_search.Text);
DataTable dt = new DataTable();
sda.Fill(dt);
}
}
Try this.
you were using the string directly in the query which will go undetected.
SqlConnection sqlconnection = new SqlConnection("Server=Behnam\\Accounting;
Initial Catalog=Accounting;Integrated Security=TRUE");
DataTable dt = new DataTable();
SqlDataAdapter SDA = new SqlDataAdapter("SELECT dbo.tbl_user.field1,dbo.tbl_user.field2 FROM tbl_user WHERE dbo.tbl_user.name=#searchName" , sqlconnection);
SDA.SelectCommand.Parameters.AddWithValue("#searchName", txt_search.Text);
SDA.Fill(dt);
dataGridView1.DataSource = dt;

datagrid not getting displayed

I am trying to display the data from sql into a datagrid as follows:
try
{
SqlConnection xconn = new SqlConnection();
xconn.ConnectionString = #"Data Source=servername; Trusted_Connection=yes; Database=master";
xconn.Open();
string s = "select * from tablename where name=#name";
SqlCommand ycmd = new SqlCommand(s, xconn);
ycmd.Parameters.Add("#name", dropdownlistname.SelectedValue);
SqlDataAdapter da = new SqlDataAdapter(ycmd);
DataTable dt = new DataTable();
da.Fill(dt);
gridview.DataSource = dt;
gridview.DataBind();
}
catch (Exception e2)
{
lblresult.Text = e2.Message + "<br />" + e2.StackTrace ;
}
I do not get any exception . However , the grid is not displayed.
try like this....
you can change this depends on your requirement ....
SqlCommand command = new SqlCommand();
command.CommandText = "SELECT * FROM Product WHERE Product.ID=#PROD_ID";
command.Parameters.Add(new SqlParameter("#PROD_ID", 100));
// Execute the SQL Server command...
SqlDataReader reader = command.ExecuteReader();
DataTable tblProducts = new DataTable();
tblProducts.Load(reader);
foreach (DataRow rowProduct in tblProducts.Rows)
{
// Use the data...
}
It doesn't work because you are defining a parameter #name to your sql statement but you are never feeding any value since the version of SqlCommand.Parameters.Add that takes 2 parameters is the one that receives parameterName and SqlDbType
I am surprised you are not getting exceptions. Perhaps your dropdownlistname.SelectedValue matches one of the enumeration values for SqlDbType and that's why?
You should be doing:
ycmd.Parameters.AddWithValue("#name", dropdownlistname.SelectedValue);

Categories

Resources