Gridview SQL LIKE from Dropdownlist - asp.net

I have a textbox, dropdownlist and a SQL statement bound to a gridview.
How can I add the dropdownlist value to the SQL statement after the WHERE clause?
I've try the following but it's showing no data.
"SELECT FirstName, LastName FROM tblPerson WHERE '" & ddlSearch.SelectedValue & "' LIKE '%" & txtSearch.Text & "%' ORDER BY FirstName

You are missing your column name in your query so try this
string query = "SELECT FirstName, LastName FROM tblPerson
WHERE myDDLColumn like '% " + ddlSearch.SelectedValue + "'%'" + "and
myTextBoxColumn like '%" + txtSearch.Text + "'%'";
EDIT : If your dropdownlist contains the column names as value of item in dropdown then you can write it as :
string query = "SELECT FirstName, LastName FROM tblPerson WHERE "+
ddlSearch.SelectedValue+" like '%" + txtSearch.Text + "'%'";

Related

Is this SQLite Update query correct?

String query = "UPDATE CONTACT SET NAME ='" +
contact.getName()"',phoneNO='" +
contact.getContactNumber() +
"' WHERE ID = "+contact.getId();
"UPDATE CONTACT SET NAME ='" +
contact.getName() +
"',phoneNO='" +
contact.getContactNumber() +
"' WHERE ID = " +
contact.getId();
You are missing a "+" after the getName(). But this whole approach is risky because the name and other parameters could contain quotes or other characters that could cause the statement to be parsed incorrectly (SQL injection).
It is safer to embed the query string with named parameters instead.
Like
"UPDATE CONTACT SET NAME = #name, phoneNO - #phone WHERE ID = #ID"
Then you define the values for #name, #phone, and #ID when you execute. This is much safer. The exact details of how you do that depends on the database you are using and the API

Move most matched result up in asp.net

I am developing an application where user searches for another user. The most matched results should come higher up.
string name = txtSearch.Text;
string space = " ";
if(name.Contains(space))
{
string[] FullName = txtSearch.Text.Split(' ');
using (SqlConnection conn = new SqlConnection(strcon))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select UserProfile.City, UserProfile.FirstName, UserProfile.LastName,UserProfile.Age where UserProfile.FirstName like '%" + FullName[0] + "%' or UserProfile.FirstName like '%" + FullName[1] + "%' or UserProfile.LastName like '%" + FullName[1] + "%'";
cmd.Connection = conn;
conn.Open();
dlContacts.DataSource = cmd.ExecuteReader();
dlContacts.DataBind();
conn.Close();
}
}
}
This is where I am handling search work. txrSearch is id of text box where user types username to search and finally data is bound to datalist. Now I want to move the matches record up. Like if user types "Tom John" then Tom John name should come on the top and then remaining records with lower frequency of those keywords should come down. How can I do it?
Thanks in advance
To avoid SQL injection attacks, always use parameterized queries.
cmd.Parameters.AddWithValue("#myFirstParam", FullName[0])
cmd.Parameters.AddWithValue("#mySecondParam", FullName[1])
your CommentText
(maby it is not ideal, but it works for you.)
SELECT
UserProfile.City,UserProfile.FirstName,UserProfile.LastName,UserProfile.Age
FROM
UserProfile
WHERE
UserProfile.FirstName LIKE '%' + #myFirstParam + '%' OR
UserProfile.FirstName LIKE '%' + #mySecondParam + '%' OR
UserProfile.LastName LIKE '%" + #mySecondParam + "%'
ORDER BY
CASE WHEN UserProfile.FirstName LIKE '%' + #myFirstParam + '%' THEN 1 ELSE 0 END +
CASE WHEN UserProfile.FirstName LIKE '%' + #mySecondParam + '%' THEN 1 ELSE 0 END +
CASE WHEN UserProfile.LastName LIKE '%' + #mySecondParam + '%' THEN 1 ELSE 0 END
DESC
what about
i have three names
i have three names
i use upper/lower case
i enter space and not type a second word
....?

How to RETURN #Identity of instert data in spl in asp.net

I'm inserting data in a table with this code below.
SqlCommand cmd = new SqlCommand("INSERT INTO Users (Username,Password,FirstName,lastName,PhoneNumber,Address,City,State,Country,ZipCode,UserType,PayOut,TimeDate)"
+ ("VALUES ('" + TextBox1.Text + "','" + TextBox3.Text + "','" + TextBox4.Text + "','" + TextBox5.Text + "','" + TextBox6.Text + "','" + TextBox7.Text + "','" + TextBox8.Text + "','" + TextBox9.Text + "','" + TextBox10.Text + "','" + TextBox11.Text + "','User','0','" + Date + "')"), con);
cmd.ExecuteNonQuery();
I want to get Id of inserting Value in database which I save new data in table anyone have any idea what can i have to add in a code so i can RETURN #Identity of insert value in table and use that id some other code.
Thank you
First use parametrized queries (to avoid SQL Injection attack)
var sql = "INSERT INTO Users (Username,Password,FirstName,lastName,PhoneNumber,Address,City,State,Country,ZipCode,UserType,PayOut,TimeDate)" +
"values (#username, #password, #firstname, #lastname, #phone, #address, #city, #state, #country, #zipcode, #usertype, #payout, #timedate);" +
"select SCOPE_IDENTITY()";
var cmd = new SqlCommand(sql);
cmd.Parameters.AddWithValue("#username", TextBox1.Text);
cmd.Parameters.AddWithValue("#password", TextBox3.Text);
cmd.Parameters.AddWithValue("#firstname", TextBox4.Text);
cmd.Parameters.AddWithValue("#lastname", TextBox5.Text);
cmd.Parameters.AddWithValue("#phone" TextBox6.Text);
//and so on
var id = Convert.ToInt32(cmd.ExecuteScalar());
SCOPE_IDENTITY returns last id created for inserted row in given scope. This way you get back id. Use ExecuteScalar() method that returns one value from first row, first column.
Also do not store clear text as password, use some hashing method.
change your sql and code like as below
for sql 2005+
INSERT INTO Users (UserId,otherdata...)
OUTPUT INSERTED.ID
VALUES(#UserId, #othervalues...)
for sql 2000
INSERT INTO aspnet_GameProfiles(UserId,otherdata...)
VALUES(#UserId, #othervalues...);
SELECT SCOPE_IDENTITY()
And then
Int32 newId = (Int32) myCommand.ExecuteScalar();
Suggestion:
Make use of parameterize query to avoid sql injection attack....
The simplest way would be to append "SELECT SCOPE_IDENTITY()" to your SQL statement. You should parametrize your query to avoid SQL Injection, and it would look something like:
string sql = #"
INSERT INTO Users
(Username,Password,FirstName,lastName,PhoneNumber,
Address,City,State,Country,ZipCode,UserType,PayOut,TimeDate)
VALUES(#Username, #Password, ...)
SELECT SCOPE_IDENTITY()
";
SqlCommand cmd = new SqlCommand(sql, ...);
... append parameters ...
var identity = (decimal) cmd.ExecuteScalar();
If your identity column is an integer, you can either cast from decimal to integer, or do the cast in SQL Server, e.g.
string sql = #"
INSERT INTO Users
...
SELECT CAST(SCOPE_IDENTITY() AS INT)
";
SqlCommand cmd = new SqlCommand(sql, ...);
... append parameters ...
var identity = (int) cmd.ExecuteScalar();
Note that SCOPE_IDENTITY is generally a better choice than ##IDENTITY. In most cases, they will return the same value. But, for example, if your INSERT statement causes a trigger to fire, which inserts an identity value in a second table, then it's the identity value inserted into this second table that will be returned by ##IDENTITY. Using SCOPE_IDENTITY avoids this problem.

If/Else Statements in VB.NET (SQL) Query?

I just wanted to know what's the best way to add If/Else statements in a SQL query within VB.Net code?
This is my current query (doesn't work):
SELECT
FIRSTNAME, LASTNAME
FROM
TBL_USERS
ORDER BY
If(SortSelect() Is ""lastname"", LASTNAME, FIRSTNAME)
Thanks in advance.
My opinion about this is to NEVER put the IF in the SQL statement. It makes it too hard to read. Probably because it's all on the same line.
In your case, there's only one, but when you got many conditions, it gets almost impossible to read.
You should declare a string for your condition like this
Dim strQuery as string
Dim strOrderBy as string
If(SortSelect() = "lastname") then
strOrderBy = "Order By lastname"
Else
strOrderBy = "Order By firstname"
endif
strQuery = "SELECT FIRSTNAME, LASTNAME FROM TBL_USERS " & strOrderBy
you could try something like this:
SELECT FIRSTNAME, LASTNAME
FROM TBL_USERS
ORDER BY Case when <SortSelect>= 'lastname' then LASTNAME else FIRSTNAME end
Dim sql as string = "SELECT FIRSTNAME, LASTNAME FROM TBL_USERS ORDER BY "
if (SortSelect() = "lastname")
sql = sql & "lastname"
else
sql = sql & "firstname"
end if

AutoCompleteExtender strange problem

I've faced with a strange problem in ASP.net/SQL Server and really can not find out what is the problem. I have a AutoCompleteExtender that finds out the predicted results from a web service. All the times it was working great with both english and non-english characters until I became forced to change the collation of the SQL Server 2008 database that was feeding the webservice.
Nothing changed but the collation of this database and column type which was changed from Nvarchar to Varchar. SQL server shows results correct while executing the query but:
The problem is that when typing in english in autocompleteextender textbox it responds immediately but when I enter a non-english word there, i should PRESS the BACKSPACE key to delete the last character so that it respond. My database collation is SQL_Latin1_General_CP1256_CI_AS.
I can't realize why this strange behaviour is exposed while entering non-english characters.
Here is the Web service code attached to my ajax autocompleteextender:
[WebMethod(EnableSession = true)]
[System.Web.Script.Services.ScriptMethod]
public string[] GetCompletionListByVT(string prefixText, int count)
{
List<string> returnData = new List<string>();
try
{
string connStr = ConfigurationManager.ConnectionStrings["CS"].ConnectionString;
SqlConnection objconnection = new SqlConnection(#connStr);
string strsql = "SELECT TOP 10 CompanyName FROM ViewAutoCompleteWSFeed WHERE (CompanyName LIKE '%" + prefixText+"" + "%');";
objconnection.Open();
// strsql = "SELECT TOP 10 CompanyName FROM ViewAutoCompleteWSFeed WHERE (CompanyName LIKE '%" + prefixText + "%' OR Business_Landline_Phone_1 LIKE '%" + prefixText + "%' OR Business_Landline_Phone_2 LIKE '%" + prefixText + "%' OR MobileNumb1 LIKE '%" + prefixText + "%' OR MobileNumb2 LIKE '%" + prefixText + "%' OR EmailAddress LIKE '%" + prefixText + "%' OR Business_Address LIKE '%" + prefixText + "%' OR htCompanySN LIKE '%" + prefixText + "%' OR htCompanyNo LIKE '%" + prefixText + "%' OR Notes LIKE '%" + prefixText + "%');";
SqlCommand objcommand = new SqlCommand(strsql, objconnection);
SqlDataReader dr = objcommand.ExecuteReader();
while (dr.Read())
{
returnData.Add(dr["CompanyName"].ToString());
}
objconnection.Close();
return returnData.ToArray();
}
catch (Exception ex)
{
returnData.Add(prefixText);
}
return returnData.ToArray();
}
The solution is that you delete the temporary folder for your website under the .net framework folder on your windows folder.
The next time you compile and build your website the problem disappears.

Resources