Must declare the scalar variable "#Name" - asp.net

I have these includes:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
My connection string is
public partial class Directory : System.Web.UI.Page
{
SqlConnection con = new SqlConnection("Data Source=10.4.33.61;Initial Catalog=Bank_Reconciliation;Persist Security Info=True;User ID=****;Password=****");
protected void Page_Load(object sender, EventArgs e)
{
}
My method to search by string and display in data grid view (naming search button as btnsearch) is
protected void btnsearch_Click(object sender, EventArgs e)
{
string str = "select * from Employee where (Name like '%' + #search + '%') ";
SqlCommand xp = new SqlCommand(str, con);
xp.Parameters.Add("#search", SqlDbType.VarChar).Value = txtsearch.Text;
con.Open();
xp.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = xp;
DataSet ds = new DataSet();
da.Fill(ds,"Name");
GridView1.DataSource = ds;
GridView1.DataBind();
con.Close();
}
}
I receive the following error:
Must declare the scalar variable "#Name".
Why is this, and how do I fix it?

It might be easier to have the TSQL just use LIKE #search, and handle it when adding the parameter:
protected void btnsearch_Click(object sender, EventArgs e)
{
string str = #"SELECT * FROM Employee WHERE Name LIKE #search";
SqlCommand xp = new SqlCommand(str, con);
xp.Parameters.AddWithValue("#search", "%" + txtSearch.Text + "%");
con.Open();
xp.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = xp;
DataSet ds = new DataSet();
da.Fill(ds,"Name");
GridView1.DataSource = ds;
GridView1.DataBind();
con.Close();
}

Change you button click code to this:
protected void btnsearch_Click(object sender, EventArgs e)
{
string str = "select * from Employee where (Name like '%" + #search + "%') ";
SqlCommand xp = new SqlCommand(str, con);
xp.Parameters.Add("#search", SqlDbType.VarChar).Value = txtsearch.Text;
con.Open();
xp.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = xp;
DataTable dt = new DataTable();
da.Fill(ds, dt);
GridView1.DataSource = dt;
GridView1.DataBind();
con.Close();
}
}
It puts proper quotes for like operator, and also used DataTable instead of DataSet. You can also use DataSet but here it seems no need for that.

Related

Database Storing Insert Query

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
public partial class Details : System.Web.UI.Page
{
string strcon = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
string objective = " ";
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(strcon);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
{
String SQL = "SELECT TOP 2 * FROM QuestionBank ORDER BY NEWID()";
SqlDataAdapter Adpt = new SqlDataAdapter(SQL, con);
DataSet login1 = new DataSet();
Adpt.Fill(login1);
foreach (DataRow dr in login1.Tables[0].Rows)
{
objective = login1.Tables[0].Rows[0]["s_id"].ToString() + "," + login1.Tables[0].Rows[1]["s_id"].ToString();
Label1.Text = login1.Tables[0].Rows[0]["question"].ToString();
Label2.Text = login1.Tables[0].Rows[0]["question"].ToString();
break;
}
}
}
protected void Button1_Click(object sender, EventArgs e))
{
SqlConnection con = new SqlConnection(strcon);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
SqlCommand cmd = new SqlCommand("Insert into PaperTbl values('" + objective + "','" + TextBox1.Text + "','" + TextBox2.Text + "')", con);
cmd.ExecuteNonQuery();
Response.Write("<script>alert('Answers Saved Successfully');location.href='Details.aspx'</script>");
}
}
When i Click on Save Button
then question in the Label1 and Label2 gets changes
So the answer from textbox1 and textbox2 becomes wrong.
So while Saving the Data gets refreshed and new question gets save instead of old question. Please Help Me.
Page_Load is running before your TextBox1_TextChanged postback event. So the new values are populated and then saved.
See here for an explanation of page life cycle https://www.c-sharpcorner.com/UploadFile/8911c4/page-life-cycle-with-examples-in-Asp-Net/
This should work:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadNew();
}
}
private void LoadNew()
{
string strcon = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
string objective = " ";
SqlConnection con = new SqlConnection(strcon);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
{
String SQL = "SELECT TOP 2 * FROM QuestionBank ORDER BY NEWID()";
SqlDataAdapter Adpt = new SqlDataAdapter(SQL, con);
DataSet login1 = new DataSet();
Adpt.Fill(login1);
foreach (DataRow dr in login1.Tables[0].Rows)
{
objective = login1.Tables[0].Rows[0]["s_id"].ToString() + "," + login1.Tables[0].Rows[1]["s_id"].ToString();
Label1.Text = login1.Tables[0].Rows[0]["question"].ToString();
Label2.Text = login1.Tables[0].Rows[0]["question"].ToString();
break;
}
}
}
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(strcon);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
SqlCommand cmd = new SqlCommand("Insert into PaperTbl values('" + objective + "','" + TextBox1.Text + "','" + TextBox2.Text + "')", con);
cmd.ExecuteNonQuery();
LoadNew();
Response.Write("<script>alert('Answers Saved Successfully');location.href='Details.aspx'</script>");
}

How to get a table on a new web page when a button is Clicked

This is my one tag:
<asp:Button ID="button" runat="server" Text="ShowOrder" onclick="newTab" />
This is my 'aspx.cs' which will be called when button is clicked
protected void newTab(object sender, EventArgs e)
{
Response.Redirect("Default2.aspx?id="+txtSearchCustomerByID.Value);
}
What I want is to print my sql table on loaded web tab (new page) when it gets loaded.
My stored procedure is displaying the data of my table where id is equal to "id entered by user in textbox".
Now,
protected void Page_Load(object sender, EventArgs e)
{
int id_no = int.Parse(Request.QueryString["id"]);
if (Page.IsPostBack)
{
showOrders(id_no);
}
}
Now what should I have in 'Default2.aspx' so that I will get my table by using,
public void showOrders(int id)
{
using (SqlConnection con = new SqlConnection(strConnString))
{
SqlCommand cmd = new SqlCommand("showOrdersSP", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#id", id);
con.Open();
.......
}
}
I need to use DataTable
So simply when I clicked, I will get data table on new page
You can refer below code:
public void showOrders(int id)
{
using (SqlConnection con = new SqlConnection(strConnString))
{
DataTable dt = new DataTable();
SqlParameter[] p1 = new SqlParameter[1];
p1[0] = new SqlParameter("#id", id);
dt= getRecords_table("showOrdersSP", p1); // you will get your DataTable here
}
}
// Common Method for FillYour Tables
private DataTable getRecords_table(string spname, SqlParameter[] para)
{
string connectionstring = System.Configuration.ConfigurationManager.ConnectionStrings["connName"].ConnectionString.ToString();
SqlConnection con = new SqlConnection(connectionstring);
SqlDataAdapter ad = new SqlDataAdapter(spname, con);
ad.SelectCommand.CommandType = CommandType.StoredProcedure;
DataTable dt = new DataTable();
ad.SelectCommand.Parameters.AddRange(para);
con.Open();
ad.Fill(dt);
con.Close();
return dt;
}
Hope it will helps you
Thanks

Retrieve data from asp.net webform

What is wrong in this program??
it shows error in da.Fill(dt);. This program is for searching record from DataBase by Name.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
using System.Threading.Tasks;
public partial class NameSearch : System.Web.UI.Page
{
public SqlConnection con = new
SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].
ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
con.Open();
}
protected void btnSearch_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("select * from case1 where
Name="+txtSearchName.Text,con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet dt = new DataSet();
da.SelectCommand = cmd;
da.Fill(dt);
GridView1.DataSource = dt;
cmd.ExecuteNonQuery();
con.Close();
}
}
SqlCommand cmd = new SqlCommand("select * from case1 where
Name='"+txtSearchName.Text + "'",con);
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds= new DataSet();
da.SelectCommand = cmd;
da.Fill(ds, "FooTable");
GridView1.DataSource = ds.Tables["FooTable"];;
cmd.ExecuteNonQuery();
con.Close();
You have to use Text in commandtype instead of StoredProcedure..Use parameterized query to avoid sql injection
string name=txtSearchName.Text;
SqlCommand cmd = new SqlCommand("select * from case1 where Name=#name",con);
cmd .Parameters.AddWithValue("#name", name);
cmd.CommandType = CommandType.Text;
da.SelectCommand = cmd;
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
con.Close();

update a database from dataset

as you see in this code i was update the dataset ds at Button1_Click and i want to update the changes made on that dataset to the database.
if i wrote it at the Button1_Click it is work but when i put exactly the same code at Unnamed1_Click it is not working and i dont know why!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Configuration;
using System.Data;
using System.Data.SqlClient;
public partial class Discount : System.Web.UI.Page
{
DataSet ds = new DataSet();
public void Page_Load(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection("Data Source=Media.ruppin.ac.il;Initial Catalog=igroup9_test1; User ID=igroup9;Password=igroup9"))
{
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Items", con); // יצירת dataAdapter
da.Fill(ds);
GridView2.DataSource = ds;
GridView2.DataBind();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
int price;
for (int i = 0; i < GridView2.Rows.Count; i++)
{
if (Convert.ToInt32(ds.Tables[0].Rows[i].ItemArray[4]) > Convert.ToInt32(minamount.Text))
{
price = Convert.ToInt32(ds.Tables[0].Rows[i][2]);
price -= price * int.Parse(discountrate.Text) / 100;
ds.Tables[0].Rows[i][2] = Convert.ToString(price);
}
}
GridView2.DataSource = ds.Tables[0];
GridView2.DataBind();
//SqlConnection con = new SqlConnection("Data Source=Media.ruppin.ac.il;Initial Catalog=igroup9_test1; User ID=igroup9;Password=igroup9_");
//con.Open();
//SqlDataAdapter tmpda = new SqlDataAdapter("SELECT * FROM Items", con);
//SqlCommandBuilder builder = new SqlCommandBuilder(tmpda);
//tmpda.Update(ds);
}
protected void Unnamed1_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection("Data Source=Media.ruppin.ac.il;Initial Catalog=igroup9_test1; User ID=igroup9;Password=igroup9_86098"))
{
con.Open();
SqlDataAdapter tmpda = new SqlDataAdapter("SELECT * FROM Items", con);
SqlCommandBuilder builder = new SqlCommandBuilder(tmpda);
tmpda.Update(ds);
}
}
}
You need to specify the update command for your SqlDataAdapter. Just insert the following code after your commandBuilder instace:
tmpda.UpdateCommand = builder.GetUpdateCommand();

SQL Connection variable not in the current context

I am a beginner in.NEt and having difficulty using the sql connection in a radio button index changed eventhandler that i defined on the page_load.
Below is my code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
namespace Controls
{
public partial class Report_Selection : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
GridView1.HeaderStyle.Font.Bold = true;
RadioButtonList1.SelectedIndexChanged += new EventHandler(RadioButtonList1_SelectedIndexChanged);
using (SqlConnection cnn = new SqlConnection("Data Source=DBSW9079;Initial Catalog=Underwriting;Integrated Security=SSPI;"))
{
SqlCommand cmd;
SqlDataReader sdr;
if (!IsPostBack)
{
cmd = new SqlCommand("select Categoryid,CategoryTitle from Report_Category", cnn);
cnn.Open();
sdr = cmd.ExecuteReader();
SelectCategorydlist1.DataSource = sdr;
SelectCategorydlist1.DataTextField = "CategoryTitle";
SelectCategorydlist1.DataValueField = "categoryid";
SelectCategorydlist1.DataBind();
cnn.Close();
}
else
{
//It's a Post back
//make the grid visible and fill it
GridView1.Visible = true;
RadioButtonList1.SelectedValue = "1";
cmd = new SqlCommand("Select rptdesc,rptdesctext,categoryid from report_description " + "where categoryid != 99999"
+ "and categoryid = " + Convert.ToInt32(SelectCategorydlist1.SelectedValue).ToString(), cnn);
cnn.Open();
sdr = cmd.ExecuteReader();
GridView1.DataSource = sdr;
GridView1.DataBind();
sdr.Close();
{
}
}
}
}
void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlCommand cmd1;
SqlDataReader sdr1;
if (RadioButtonList1.SelectedIndex.Equals(1))
{
RadioButtonList1.ClearSelection();
cmd1 = new SqlCommand("Select rptdesc,rptdesctext,categoryid from report_description "
+ "and categoryid = " + Convert.ToInt32(SelectCategorydlist1.SelectedValue).ToString(), cnn);
cnn.Open();
sdr1= cmd1.ExecuteReader();
GridView1.DataSource = sdr1;
GridView1.DataBind();
sdr1.Close();
}
}
}
}
In the above code when i use the cnn sequel connection in the event handler i get an small r
Your query in RadioButtonList1_SelectedIndexChanged appears to be incorrect. There's an and without a where:
Select rptdesc,rptdesctext,categoryid from report_description
and categoryid = ...
^^^ should be WHERE

Resources