How use WHERE in SqlDataAdapter in C# - 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;

Related

Dataset filter method

Here is my code,
Conn.Open();
DataTable dt = new DataTable();
DataSet ds = new DataSet();
SqlCommand sqlCmd = new SqlCommand("SELECT * from CurrentDataCR ",Conn);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
sqlDa.Fill(ds);
ds.Tables[0].DefaultView.RowFilter = " mst_remote_station_id Like'*9001*'";
Here I am getting Complete row for id 9001. I need only one column value for this id.
DataRow[] rows = ds.Tables[0].Select("mst_remote_station_id Like '%9001%'");
You can do it this way also if you need only one row just select it in the initial query.
Also you should Dispose the SqlDataAdapter after using it ! You can do it with using block
Conn.Open();
DataSet ds = new DataSet();
SqlCommand sqlCmd = new SqlCommand("SELECT * from CurrentDataCR ",Conn);
using(SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd))
{
sqlDa.Fill(ds);
}
ds.Tables[0].Select("mst_remote_station_id Like '%9001%'");
I don't know if the connection is global but it is bad practice to use global connection, you have connection pool so use separate connection for every query.

DataAdapter.Fill(), Error arise as "Incorrect syntax near ')'"

When retrieving a datatable from database using the following code in ASP.Net & C#:
The database is located in my local machine.
string connectionString = #"Data Source=CCS90; Initial Catalog=Ribo; Trusted_Connection=True;";
SqlConnection myConn = new SqlConnection(connectionString);
myConn.Open();
SqlCommand sqlCommand = new SqlCommand("SELECT * FROM PUR_POHEADER WHERE POID = #POID", myConn);
sqlCommand.Parameters.Add("#POID", SqlDbType.Int);
sqlCommand.Parameters["#POID"].Value = Convert.ToInt32(request.ReferenceNo);
DataSet DS = new DataSet();
SqlDataAdapter AD = new SqlDataAdapter(sqlCommand, myConn);
//AD.Fill(DS);
AD.Fill(DS, "POTABLE"); //Error arise at this place
DataTable DT = DS.Tables[0];
myConn.Close();
When compiler comes to the line AD.Fill(DS, "POTABLE");, error occurs at Incorrect syntax near '). What may be the reason?
You create a SqlCommand with a SELECT statement and then you don't use it. What is insertStatement? Surely you should be using sqlCommand.
You may try with
AD.Fill(DS);
instead of
AD.Fill(DS,"PORTABLE");
Also try:
SqlDataAdapter AD = new SqlDataAdapter(sqlCommand);
instead of
SqlDataAdapter AD = new SqlDataAdapter(insertStatement, myConn);
Problem is here:
SqlDataAdapter AD = new SqlDataAdapter(insertStatement, myConn);
replace it with:
SqlDataAdapter AD = new SqlDataAdapter(sqlCommand);
and also you are using this overload i think:
AD.Fill(DS, "NameOfDataTable");
then you can access it like this:
DataTable DT = DS.Tables["NameOfDataTable"];
insetad of using 0 index.

Why I get Incorrect syntax near '=' error

I tried bind a label from datatable
I get this error
Incorrect syntax near '='.
at this line
da.Fill(dt);
My code : Page_Load
LbLID.Text =this.Page.Request.QueryString["DI"].ToString();
SqlConnection con = new SqlConnection("Data Source=local;Initial Catalog=DB;User
ID=sa;Password="pass);
SqlDataAdapter da = new SqlDataAdapter("select * from Table1 where ID= " +
LbLID.Text.Trim(), con);
System.Data.DataTable dt = new System.Data.DataTable();
da.Fill(dt);
lblS1.Text = dt.Rows[0][4].ToString();
lblS1.DataBind();
You can't break normal string literals across multiple lines, also your closing quote is misplaced:
SqlConnection con = new SqlConnection("Data Source=local;Initial Catalog=DB;User ID=sa;Password=pass");
Or use a verbatim literal, which you can break across multiple lines:
SqlConnection con = new SqlConnection(
#"Data Source=local;
Initial Catalog=DB;
User ID=sa;
Password=pass");
That said, your code is vulnerable to SQL injection attacks. For your own sake, and the sake of your users, you really should use parameterized queries instead of concatenating your SQL queries like that.
Here's a quick example:
using(var con = new SqlConnection(...))
{
var cmd = new SqlCommand("select * from Table1 where ID = #ID", con);
con.Open();
cmd.Parameters.AddWithValue("#ID", LbLID.Text.Trim());
var da = new SqlDataAdapter(cmd);
var dt = new DataTable();
da.Fill(dt);
lblS1.Text = dt.Rows[0][4].ToString();
lblS1.DataBind();
}
Some other tips: You should avoid using select * queries, since your database schema might change, and that would break any existing code. It would be better to select only the column you're interested in and make a simple call to ExecuteScalar.
Try this:
SqlDataAdapter da = new SqlDataAdapter("select * from Table1 where ID ='" +
LbLID.Text.Trim() + "'", con);
However note that it a very bad code which is vulnerable to sql injection.
So you should try this:
var com = new SqlCommand("SELECT * FROM Table1 WHERE ID=#id", con);
com.Parameters.AddWithValue("id",LBLID.Text.Trim());
var da = new SqlDataAdapter(com);
Or shorter:
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Table1 WHERE ID=#id", con);
da.SelectCommand.AddWithValue("id",LBLID.Text.Trim());
Its a SQL error. You aren't passing in a valid ID.
It's one of two things.
Option A: Your ID is a string. In which case.. you need to use single quotes:
SqlDataAdapter da = new SqlDataAdapter("select * from Table1 where ID= '" + LbLID.Text.Trim() + "'", con);
Option B: Your LbLId is wrong.. you're checking for ["DI"] .. when I think it should be ["ID"]:
LbLID.Text =this.Page.Request.QueryString["ID"].ToString();
I do not see any problem in the code at da.Fill(). But I see another issue at the following statement:
SqlConnection con = new SqlConnection("Data Source=local;Initial Catalog=DB;User
ID=sa;Password="pass);
...Password="pass); - rather is should be
...Password=" + pass);
OR
...Password=pass");
I am wondering you are not getting an undefined variable error for pass*.

Fill DataTable from SQL Server database

This one is a mystery for me, I know the code I took it from others, in my case the datatable it returns is empty
conSTR is the connection string, set as a global string
public DataTable fillDataTable(string table)
{
string query = "SELECT * FROM dstut.dbo." +table;
SqlConnection sqlConn = new SqlConnection(conSTR);
sqlConn.Open();
SqlCommand cmd = new SqlCommand(query, sqlConn);
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
sqlConn.Close();
return dt;
}
EDIT 1
The whole point is to later show this table in a datagrid view on a tabcontrol, here is the question on that
displaying multiple datatable in tabcontrol C#
Here it just show's me a blank datagridview
EDIT 2
Tried them all, when I try to display the table, the datagridview is empty, have the right amount of rows but now value
If the variable table contains invalid characters (like a space) you should add square brackets around the variable.
public DataTable fillDataTable(string table)
{
string query = "SELECT * FROM dstut.dbo.[" + table + "]";
using(SqlConnection sqlConn = new SqlConnection(conSTR))
using(SqlCommand cmd = new SqlCommand(query, sqlConn))
{
sqlConn.Open();
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
return dt;
}
}
By the way, be very careful with this kind of code because is open to Sql Injection. I hope for you that the table name doesn't come from user input
Try with following:
public DataTable fillDataTable(string table)
{
string query = "SELECT * FROM dstut.dbo." +table;
SqlConnection sqlConn = new SqlConnection(conSTR);
sqlConn.Open();
SqlCommand cmd = new SqlCommand(query, sqlConn);
SqlDataAdapter da=new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
sqlConn.Close();
return dt;
}
Hope it is helpful.

an SQL Search query using more than one condition

my problem is that , i made a child form for searching , but i have problem in sql query and parameters , my code is
SqlConnection sc = new SqlConnection(
"Data Source=MOHAMMED-PC;Initial Catalog=salessystem;Integrated Security=True");
SqlCommand command = new SqlCommand(
"Select * from customers WHERE (docno = #doc) OR (NAME LIKE #name ) OR (salepoint = #salepoint)", sc);
DataTable dt = new DataTable();
command.Parameters.AddWithValue("#doc", doctxt.Text);
command.Parameters.Addwithvalue("#name", nametxt.Text);
command.Parameters.AddWithValue("#salepoint", salepointtxt.Text);
SqlDataAdapter sda = new SqlDataAdapter(command, sc);
sda.Fill(dt);
dataGridView1.DataSource = dt;
i have error in sql adapter command and in where clause command , any help ??
Three things:
You have a typo on this line
command.Parameters.Addwithvalue("#name", nametxt.Text);
The method is AddWithValue (note the case difference)
The constructor of SqlDataAdapter takes the command but no connection then since the command already contains the connection, so this is correct:
SqlDataAdapter sda = new SqlDataAdapter(command);
Probably the most important last:
If you use LIKE you need to use the wild-cards %:
command.Parameters.AddWithValue("#name", string.Format("%{0}%",nametxt.Text);

Categories

Resources