I can't see any data displayed in a gridview.
Can't see any search results.
I'm trying to use sqlparameter.
As you can see, my sqlQuery is a very long one.
If I enter 'card', it should find item_description with 'big card' or 'small card' values.
Here is my code:
searchWord = Request.Cookies["Search"].Value;
searchType = Request.Cookies["Display"].Value;
string sqlQuery;
string custSearch = searchWord;
DataTable dt = new DataTable();
SqlConnection sc = new SqlConnection(GetConnectionString());
sqlQuery = "SELECT Player.player_id AS 'ID', Player.fname AS 'First name', "
+"Player.lname AS 'Last name', Player.sport AS 'Sports',"
+"Player.position AS 'Position', Player.debut_year AS 'Debut year',"
+"Player.prof_year AS 'Major year', Player.birth_date AS 'Date of birth',"
+"Player.birth_place AS 'Place of birth', Player.team_f AS 'Current team',"
+"Player.team_s AS 'Past team1', Player.team_t AS 'Past team2',"
+"Player.living AS 'Death status' "
+"FROM Player WHERE (Player.fname LIKE '#SearchPam') "
+"OR (Player.lname LIKE '#SearchPam') OR (Player.sport LIKE '#SearchPam') "
+"OR (Player.position LIKE '#SearchPam') OR (Player.team_f LIKE '#SearchPam') "
+"OR (Player.team_s LIKE '#SearchPam') OR (Player.team_t LIKE '#SearchPam');";
try
{
sc.Open();
string result = sqlQuery;
SqlCommand cmd = new SqlCommand(result, sc);
cmd.Parameters.AddWithValue("#SearchPam", custSearch);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapter.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
catch{...}
finally{sc.Close();}
public string GetConnectionString()
{
return ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
}
You can use either of the following queries, i think you will get expected output using this:
string sql = "SELECT * FROM TableA WHERE Col1 LIKE #SearchPam";
.
.
cmd.Parameters.AddWithValue("#SearchPam", "%" + txtSearch.Text + "%");
OR
string sql = "SELECT * FROM TableA WHERE Col1 LIKE '%' + #SearchPam+ '%'";
.
.
cmd.Parameters.AddWithValue("#SearchPam", txtSearch.Text);
Related
Code below is working properly and view all matches by search in column.
string sql = "SELECT car, model, year FROM store WHERE" + column + "LIKE " + search + "'";
Now adding parameters in query. Not working. It doesn't display search in column. Only display all rows in column, if search column of column ( 1 = 1)
public int SearchCar(MainStore searchCars)
{
string connection = #"Data Source=(LocalDB)";
SqlConnection con = new SqlConnection(connection);
string sql = "SELECT car, model, year FROM store WHERE #column like #search '";
SqlDataAdapter sda = new SqlDataAdapter(sql, con);
sdt.SelectCommand.Parameters.AddWithValue("#column", "%" + searchCars.GetCombo());
sdt.SelectCommand.Parameters.AddWithValue("#search", "%" + searchCars.GetSearch());
DataTable dt = new DataTable();
sda.Fill(dt);
dataGridView1.DataSource = data;
}
What could possible be the answer to get it search within specific column?
Change it as follows so as to not parameterize the column name:
public int SearchCar(MainStore searchCars)
{
string connection = #"Data Source=(LocalDB)";
SqlConnection con = new SqlConnection(connection);
string sql = string.Format("SELECT car, model, year FROM store WHERE {0} like #search", search.GetCombo());
SqlDataAdapter sda = new SqlDataAdapter(sql, con);
// sdt.SelectCommand.Parameters.AddWithValue("#column", "%" + search.GetCombo());
sdt.SelectCommand.Parameters.AddWithValue("#search", "%" + search.GetSearch());
DataTable dt = new DataTable();
sda.Fill(dt);
dataGridView1.DataSource = data;
}
Also, you've got an extra quote at the end of your query:
like #search '";
Please take a look at this
private static void Select() {
string cmdStr = "SELECT FirstName, LastName, Telephone FROM Person WHERE FirstName = #FirstName";
using (SqlConnection connection = new SqlConnection(ConnectionString))
using (SqlCommand command = new SqlCommand(cmdStr, connection)) {
command.Parameters.AddWithValue("#FirstName", "John");
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read()) {
string output = "First Name: {0} \t Last Name: {1} \t Phone: {2}";
Console.WriteLine(output, reader["FirstName"], reader["LastName"], reader["Telephone"]);
}
}
}
I have this peace of code where I need to retrieve data from Mysql. If I use parameterized query it does not take actual parameter value instead it takes parameter name as value.
Error: #choise must be defined
MySqlConnection connection = new MySqlConnection("");
MySqlDataAdapter mySqlDataAdapter;
DataSet DS;
private string columnValue = xxx;
private string Choise = yyy;
MySqlCommand command = connection.CreateCommand();
command.CommandText = "SELECT * FROM table2 WHERE " + columnValue + " = #choise";
command.Parameters.Add(new MySqlParameter("#choise", Choise));
DS = new DataSet();
connection.Open();
mySqlDataAdapter = new MySqlDataAdapter(command.CommandText, connection);
mySqlDataAdapter.Fill(DS);
connection.Close();
when I run this i get query like:
SELECT * FROM table2 WHERE xxx = #choise
instead of
SELECT * FROM table2 WHERE xxx = yyy.
Where is the problem?
I have tried:
command.Parameters.Add(new MySqlParameter("#choise", Choise));
command.Parameters.AddWithValue("#choise", Choise);
It works fine when I'm using actual variables instead of parameters.
I think you need to run Prepare() on the command before adding parameters:
command.CommandText = "select * from table2 where " + columnValue + " = #choise";
command.Prepare();
command.Parameters.AddWithValue("#choise", Choise);
Try this instead:
command.CommandText = "SELECT * FROM `table2` WHERE `" + columnValue + "` = #choise";
command.Parameters.AddWithValue("#choise", Choise);
I need to get 6 values from database and bind them to link button texts her is the code
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//string post = Request.QueryString["post"];
////string title = "nokia";
string date = DateTime.Now.ToShortDateString();
SqlConnection conn = new SqlConnection();
conn.ConnectionString = #"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\nokiaoaq\Desktop\WebSite1\App_Data\Database.mdf;Integrated Security=True;User Instance=True";
try
{
conn.Open();
//string str = "insert into Table1 (title , date_ ,www, cat) values (' " + TextBox1.Text + "','" + DateTime.Now.ToShortDateString() + "','" + TextBox2.Text + "','" + DropDownList1.SelectedItem.Text + "')";
////string str = "INSERT INTO Table1 (title,date_,www ) values ('ddddddd','aaaaaaa','qqqqqq')";
string str =
//"SELECT from table1 WHERE cat = 1 and datee='" + date + "'ORDER BY datee";
"SELECT table1.title FROM table1 WHERE cat = 1 and datee='" + date + "'ORDER BY datee DESC";
SqlCommand objcmd = new SqlCommand(str, conn);
SqlDataAdapter da1 = new SqlDataAdapter(objcmd);
DataTable dt = new DataTable();
da1.Fill(dt);
//DataRow dr = new DataRow();
//DataRow dr = ds.Tables[0].Rows[0];
foreach (DataRow dr in dt.Rows)
{
ml1.Text = dr[0].ToString();
ml2.Text = dr[1].ToString();
ml3.Text = dr[2].ToString();
ml4.Text = dr[3].ToString();
ml5.Text = dr[4].ToString();
ml6.Text = dr[5].ToString();
}
}
catch (Exception ex)
{
Label4.Text = "Failed to connect to data source";
}
finally
{
conn.Close();
}
}
}
ml is link button id
You are trying to assign 6 fields from the row returned to 6 different textboxes, but your select query asks for just one field. If you want more than one field returned then add their names to the select query (change fieldX to the appropriate field name).
string str = "SELECT title, field1, field2, field3, field4, field5 " +
"FROM table1 WHERE cat = 1 and datee=#dt ORDER BY datee DESC";
also do not use string concatenation to build the sql statement. Use always a parametrized query
SqlCommand objcmd = new SqlCommand(str, conn);
objcmd.Parameters.AddWithValue("#dt", datee);
.....
this will avoid problem with formatting strings, date, numbers etc, but also the sql injection problem.
By the way, I hope that your code returns just one row because, as it stands now, if you have more than one row returned then only the one with the earliest date will be shown in the textboxes. (And if this is the case then the order by is useless). If you have more than one row returned then you should consider to bind the datatable to a GridView to show all records returned.
In my SQL statement I use wildcards. But when I try to select something, it never select something. While when I execute the query in Microsoft SQL Server Management Studio, it works fine.
What am I doing wrong?
Click handler
protected void btnTitelAuteur_Click(object sender, EventArgs e)
{
cvalTitelAuteur.Enabled = true;
cvalTitelAuteur.Validate();
if (Page.IsValid)
{
objdsSelectedBooks.SelectMethod = "getBooksByTitleAuthor";
objdsSelectedBooks.SelectParameters.Clear();
objdsSelectedBooks.SelectParameters.Add(new Parameter("title", DbType.String));
objdsSelectedBooks.SelectParameters.Add(new Parameter("author", DbType.String));
objdsSelectedBooks.Select();
gvSelectedBooks.DataBind();
pnlZoeken.Visible = false;
pnlKiezen.Visible = true;
}
}
In my Data Access Layer
public static DataTable getBooksByTitleAuthor(string title, string author)
{
string sql = "SELECT 'AUTHOR' = tblAuthors.FIRSTNAME + ' ' + tblAuthors.LASTNAME, tblBooks.*, tblGenres.GENRE "
+ "FROM tblAuthors INNER JOIN tblBooks ON tblAuthors.AUTHOR_ID = tblBooks.AUTHOR_ID INNER JOIN tblGenres ON tblBooks.GENRE_ID = tblGenres.GENRE_ID "
+"WHERE (tblBooks.TITLE LIKE '%#title%');";
SqlDataAdapter da = new SqlDataAdapter(sql, GetConnectionString());
da.SelectCommand.Parameters.Add("#title", SqlDbType.Text);
da.SelectCommand.Parameters["#title"].Value = title;
DataSet ds = new DataSet();
da.Fill(ds, "Books");
return ds.Tables["Books"];
}
Try this:
string sql = "SELECT 'AUTHOR' = tblAuthors.FIRSTNAME + ' ' + tblAuthors.LASTNAME, tblBooks.*, tblGenres.GENRE "
+ "FROM tblAuthors INNER JOIN tblBooks ON tblAuthors.AUTHOR_ID = tblBooks.AUTHOR_ID INNER JOIN tblGenres ON tblBooks.GENRE_ID = tblGenres.GENRE_ID "
+"WHERE (tblBooks.TITLE LIKE #title);";
SqlDataAdapter da = new SqlDataAdapter(sql, GetConnectionString());
da.SelectCommand.Parameters.Add("#title", SqlDbType.Text);
da.SelectCommand.Parameters["#title"].Value = "%" + title + "%";
You can't include your query parameter inside a string literal. Do it like this instead:
WHERE (tblBooks.TITLE LIKE '%' + #title + '%');
Also, whenever you have a leading wildcard you should look into a full text index instead. Your query as written is doomed to be much slower than it could be, because you can't use index when you have a leading wild card.
The answer from John Allers is correct. As an aside, you should wrap the SqlDataAdapter in a using block:
using (SqlDataAdapter da = new SqlDataAdapter(sql, GetConnectionString()))
{
da.SelectCommand.Parameters.Add("#title", SqlDbType.Text);
da.SelectCommand.Parameters["#title"].Value = title;
DataSet ds = new DataSet();
da.Fill(ds, "Books");
return ds.Tables["Books"];
}
How to filter data in datagrid for example if you select the combo box in student number then input 1001 in the text field. All records in 1001 will appear in datagrid. I am using sql server
private void button2_Click(object sender, EventArgs e)
{
if (cbofilter.SelectedIndex == 0)
{
string sql;
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Server= " + Environment.MachineName.ToString() + #"\; Initial Catalog=TEST;Integrated Security = true";
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds1 = new DataSet();
ds1 = DBConn.getStudentDetails("sp_RetrieveSTUDNO");
sql = "Select * from Test where STUDNO like '" + txtvalue.Text + "'";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.CommandType = CommandType.Text;
da.SelectCommand = cmd;
da.Fill(ds1);
dbgStudentDetails.DataSource = ds1;
dbgStudentDetails.DataMember = ds1.Tables[0].TableName;
dbgStudentDetails.Refresh();
}
else if (cbofilter.SelectedIndex == 1)
{
//string sql;
//SqlConnection conn = new SqlConnection();
//conn.ConnectionString = "Server= " + Environment.MachineName.ToString() + #"\; Initial Catalog=TEST;Integrated Security = true";
//SqlDataAdapter da = new SqlDataAdapter();
//DataSet ds1 = new DataSet();
//ds1 = DBConn.getStudentDetails("sp_RetrieveSTUDNO");
//sql = "Select * from Test where Name like '" + txtvalue.Text + "'";
//SqlCommand cmd = new SqlCommand(sql,conn);
//cmd.CommandType = CommandType.Text;
//da.SelectCommand = cmd;
//da.Fill(ds1);
// dbgStudentDetails.DataSource = ds1;
//dbgStudentDetails.DataMember = ds1.Tables[0].TableName;
//ds.Tables[0].DefaultView.RowFilter = "Studno = + txtvalue.text + ";
dbgStudentDetails.DataSource = ds.Tables[0];
dbgStudentDetails.Refresh();
}
}
It's difficult to answer pricisely to a vague question. I guess that you'll have to adapt your SQL query with a WHERE statement containing the user input.
If 'student number' is selected in the combo box, query like this (numbers starting with):
SELECT id, name, number FROM students WHERE number LIKE #search + '%'
If 'student name' is selected, use another query (names containing):
SELECT id, name, number FROM students WHERE name LIKE '%' + #search + '%'
Please explain in what sense C# is concerned.
You don't say what is wrong with the code you commented out. You also don't say what type the Studno column is.
Have you tried something like:
ds1.Tables[0].DefaultView.RowFilter = "Studno = '" + txtvalue.text + "'";