Dynamic parameter and query - asp.net

I'm creating a search engine for my asp page.There are 15 pieces filtering options like Price,Date,Name etc.
Also,The use of Filtering Options is optional.If the filtering options are left blank,search will be made.
I found a solution by using if and string.
string sorgu = "";
dbcommand cmd = CommandClassım.YeniCommand();
sorgu += "Select * From Urunler Where ";
if(UrunAdi.Text != string.Empty)
{
sorgu += "UrunAdi = #UrunAdi";
dbparameters prm = cmd.createparameter();
prm.Parametername = "#UrunAdi";
prm.Value = UrunAdi.Text;
prm.DbType = DbType.String;
cmd.Parameters.Add(prm);
}
cmd.CommandText = sorgu;
it's running upper code without problem.However,I want to using a parameter to filter dynamic.
So,the user choose those categories through checkbox inside search engine.
When I try to run below code,I got the following error.
Must declare the scalar variable "#cat0".
Code:
string sorgu = "";
DbCommand cmd = CommandClassım.YeniCommand();
sorgu += "Select * From Urunler Where ";
DbParameter prm = cmd.CreateParameter;
for(int i = 0; i < Category.Length; i++)
{
sorgu += "Kategori = #cat" + i.ToString();
prm.ParameterName = "#cat" + i.ToString();
prm.Value = Category.Value;
prm.DbType = DbType.String;
cmd.Parameters.Add(prm);
}
cmd.CommandText = sorgu;

Just a hunch, but could it be that you're not providing the indexer for Category?
prm.Value = Category.Value;
I would think it should be:
prm.Value = Category[i].Value;

Related

Error cannot find Column 2 dr = ds.Tables[0].Rows[0]

I've been searching for an answer since this code was working fine like an hour ago and I did not make any editting so it turns a little confuse to recognize the error if any of you could help I would appreciate it much. Thanks in advance.
I've checked and there are no errors on the SQL query, as I said it was working fine dr is defined globally as:
DataRow dr = new DataRow();
and MyTable is defined globally also as
DataTable MyTable = new DataTable();
here's the related code:
sentencia = "select * from Facturas" + Session["sociotabla"].ToString() + " where IdFactura = " + Session["idFactura"].ToString();
ds = bd.Consulta(sentencia);
if (ds != null)
{
dr = MyTable.NewRow();
dr = ds.Tables[0].Rows[0];
LimpiarControles();
tbFactura.Text = dr[0].ToString();
ListItem li;
for (int i = 0; i < ddlCliente.Items.Count; i++)
{
li = ddlCliente.Items[i];
if (li.Value == dr[2].ToString()) //Error here Cannot find Column 2
{
ddlCliente.SelectedIndex = i;
Session["idCliente"] = dr[2].ToString();
break;
}
}

Why insert statement generates 2 rows?

I dont know why, but when I do an insert statement in my project, its generate 2 indentical rows instead of makeing just one.
why is that ?
this is my code :
if (ListBox.Items.Count != 0)
{
string username = Session["Session"].ToString();
con = new SqlConnection("Data Source=MICROSOF-58B8A5\\SQL_SERVER_R2;Initial Catalog=Daniel;Integrated Security=True");
con.Open();
string knowWhichOne = "SELECT ID FROM Users WHERE Username='" + UserOrGuest.Text + "'";
SqlCommand comm = new SqlCommand(knowWhichOne, con);
int userID = (Int32)comm.ExecuteScalar();
knowWhichOne = "SELECT ClassID FROM Users WHERE Username='" + UserOrGuest.Text + "'";
comm = new SqlCommand(knowWhichOne, con);
int classID = (Int32)comm.ExecuteScalar();
knowWhichOne = "SELECT SchoolID FROM Users WHERE Username='"+UserOrGuest.Text + "'";
comm = new SqlCommand(knowWhichOne, con);
int schoolID = (Int32)comm.ExecuteScalar();
if (RadioWords.Checked == true)
{
game = 1;
}
else
{
game = 2;
}
string arr = "";
for (int i = 0; i < ListBox.Items.Count; i++)
{
arr += ListBox.Items[i] +",";
}
string sqlqueryString = "INSERT INTO HistoryOfGames (GameID, UserID, LengthOfArray, NumberOfErrors, ClassID, SchoolID,Arrayarray) VALUES (#GameID, #UserID, #LengthOfArray, #NumberOfErrors, #ClassID, #SchoolID, #Arrayarray);" + "SELECT SCOPE_IDENTITY()";
SqlCommand commandquery = new SqlCommand(sqlqueryString, con);
commandquery.Parameters.AddWithValue("GameID", game);
commandquery.Parameters.AddWithValue("UserID", userID);
commandquery.Parameters.AddWithValue("LengthOfArray", HowMany.Text);
commandquery.Parameters.AddWithValue("NumberOfErrors", 0);
commandquery.Parameters.AddWithValue("ClassID", classID);
commandquery.Parameters.AddWithValue("SchoolID", schoolID);
commandquery.Parameters.AddWithValue("Arrayarray", arr);
commandquery.ExecuteNonQuery();
int IdOfRecentHistoryGame = (int)(decimal)commandquery.ExecuteScalar();
con.Close();
Response.Redirect("NowPlay.aspx?ID="+ IdOfRecentHistoryGame);
}
You're running it twice, ExecuteNonQuery() and ExecuteScalar(). Get rid of the ExecuteNonQuery().
you do
commandquery.ExecuteNonQuery();
then right after
int IdOfRecentHistoryGame = (int)(decimal)commandquery.ExecuteScalar();
you do execute it twice
and don't forget to check for sql injection in your code...
I'd check two things:
see how many times this statement is executed (try setting a breakpoint to verify that the code is only run once)
see if there are any triggers in the database that might cause an extra record to be inserted
I had the same problem,I handled it this way.not professional but it works:
Dim x As Boolean = True
If x = True Then
here goes your code to insert to database.
End If
x = False

insert a database value to a string array - not working

Cheers,
Im trying to insert a database value to my string array.
for some reason, it says :
"Object reference not set to an instance of an object."
This is my code :
if (IsPostBack)
{
if (RadioWords.Checked == true)
{
con = new SqlConnection("Data Source=MICROSOF-58B8A5\\SQL_SERVER_R2;Initial Catalog=Daniel;Integrated Security=True");
con.Open();
string SqlCount = "SELECT COUNT(*) FROM WordGame";
SqlCommand command = new SqlCommand(SqlCount, con);
//Sets an array of the size of the database.
int count = (Int32)command.ExecuteScalar();
arrOfWords = new string[count];
//Initialize the words in the array.
for (int i = 0; i < arrOfWords.Length; i++)
{
int GetRandomNumber = rnd.Next(1, arrOfWords.Length);
string Sqlinsert = "SELECT Word FROM WordGame WHERE ID='"+GetRandomNumber+"'";
SqlCommand commandToRandom = new SqlCommand(Sqlinsert, con);
arrOfWords[i] = commandToRandom.ExecuteScalar().ToString();
}
}
and its refering to this line :
int GetRandomNumber = rnd.Next(1, arrOfWords.Length);
Thanks for the helpers!
rnd is null , add a line
rnd = new Random();
at the start of your event
rnd = new Random();
Instantiate rnd as above. You're using a null object that causes the exception in your question to be thrown.

Incorrect syntax near ','. error

I am getting an SQL error when I try to do this:
public static int GetOrderId(decimal totalprice, int userid)
{
string s = "SELECT * from orders where OrderUserId = " + userid + " and OrderTotalPrice = " + totalprice;
cmd = new SqlCommand(s, con);
int temporderid = Convert.ToInt32(cmd.ExecuteScalar());
return temporderid;
}
As far I can see its because it gets OrderTotalPrice back, the format is incompatible. But I cant figure out how to get it in the compatible format.
It's probably formatting totalprice with a comma, like 3,14, where SQL Server expects a dot, like 3.14.
One way to fix that would be to specify InvariantCulture, which uses a dot:
var s = string.Format(
CultureInfo.InvariantCulture,
"SELECT * from orders where OrderUserId = {0} and OrderTotalPrice = {0:0.0}",
42, 3.1415);
This formats the price as 3.1 on any machine.
By the way, it's much nicer to pass the variables as parameters:
var com = new SqlCommand();
com.CommandType = CommandType.Text;
com.CommandText = "SELECT * from orders where OrderUserId = #userid " +
"and OrderTotalPrice = #totalprice";
com.Parameters.AddWithValue("#userid", 42);
com.Parameters.AddWithValue("#totalprice", 3.1415);
var temporderid = com.ExecuteScalar();
Then you don't have to worry about formats because you send the database a double, not a double formatted as a string.
I guess this is because totalprice gets converted to something like 12,35 when you concatenate the query.
Therefore, I'd suggest you use a parametrized query. E.g. like this:
var s = "SELECT * from orders " +
" where OrderUserId = #userid and OrderTotalPrice = #totalprice";
var cmd = new SqlCommand(s, con);
cmd.Parameters.AddWithValue("userid", userid);
cmd.Parameters.AddWithValue("totalprice", totalprice);
int temporderid = Convert.ToInt32(cmd.ExecuteScalar());

Regarding binding array to gridview

Hi
I have created session array :
int[] a = (int[])Session["values"];
Now i have to bind this value to my gridview. I have one column (boundfield in my gridview) in gridview.
I used code to bind array to gridview as follows, but its giving last value only as i want all the values to bind :
for (int i = 0; i < a.Length; i++)
{
str = "select * from Quest_Info where Quest_id='" + a[i] + "' order by Quest_id";
SqlDataAdapter da2 = new SqlDataAdapter(str, sqlconn);
ds2 = new DataSet();
da2.Fill(ds2, "Result");
reviewgrid.DataSource = ds2;
reviewgrid.DataBind();
}
Which code will work for this?
Asp.net, c#
Thank You.
Your code may not work because you are trying to bind gridview in the for loop which keep repeating and will result to bind only one last array id in the end.
You may try to prepare query out front before binding the gridview as example below.
string questIds = string.Empty;
for (int i = 0; i < a.Length; i++)
{
if (questIds.Length > 0)
questIds += ", ";
questIds += a[i];
}
string strSQL = "select * from Quest_Info where Quest_id IN ("+ questIds + ") order by Quest_id";
SqlDataAdapter da2 = new SqlDataAdapter(str, sqlconn);
ds2 = new DataSet();
da2.Fill(ds2, "Result");
reviewgrid.DataSource = ds2;
reviewgrid.DataBind();

Resources