-1

This code wants add selected items into the shopping cart for that I have got the itemname from requested.stringquery then I want to extract details of that item and put it into the table dt in gridview which will be displayed as my cart but it showing error where da=fill(ds).

if (!IsPostBack)
{
    DataTable dt = new DataTable();
    DataRow dr;

    dt.Columns.Add("sno");
    dt.Columns.Add("itemname");
    dt.Columns.Add("price");
    dt.Columns.Add("image");
    dt.Columns.Add("cost");
    dt.Columns.Add("totalcost");

    if (Request.QueryString["item_name"] != null)
    {
        if (Session["Buyitems"] == null)
        {
            dr = dt.NewRow();
            SqlConnection scon = new SqlConnection(ConfigurationManager.ConnectionStrings["online food orderingConnectionString"].ConnectionString);

            scon.Open();

            String myquery = "select * from food_items where item_name=" + Request.QueryString["item_name"]  ;
            SqlCommand cmd = new SqlCommand(myquery,scon);

            SqlDataAdapter da = new SqlDataAdapter(cmd);

            DataSet ds = new DataSet();
            da.Fill(ds);
            dr["sno"] = 1;

            dr["itemname"] = ds.Tables[0].Rows[0]["item_name"].ToString();
            dr["productimage"] = ds.Tables[0].Rows[0]["image"].ToString();
            dr["price"] = ds.Tables[0].Rows[0]["price"].ToString();
            dt.Rows.Add(dr);
            GridView1.DataSource = dt;
            GridView1.DataBind();
            Session["buyitems"] = dt;
        }
Roman
  • 11,966
  • 10
  • 38
  • 47
  • strings get surrounded by single quotes in SQL so your syntax is wrong, but you should use parameters anyway. – Crowcoder May 16 '18 at 13:17
  • Please don't keep for yourself the error message (if you want to be helped) – Steve May 16 '18 at 13:17
  • Possible duplicate of [What are good ways to prevent SQL injection?](https://stackoverflow.com/questions/14376473/what-are-good-ways-to-prevent-sql-injection) – mjwills May 16 '18 at 13:28
  • Is `item_name` a `varchar` in the database? Or `nvarchar`? – mjwills May 16 '18 at 13:29

1 Answers1

1

Change

String myquery = "select * from food_items where item_name=" + Request.QueryString["item_name"]  ;
SqlCommand cmd = new SqlCommand(myquery,scon);

to be:

 String myquery = "select * from food_items where item_name=@item_name";
 SqlCommand cmd = new SqlCommand(myquery, scon);

 cmd.Parameters.AddWithValue("item_name", Request.QueryString["item_name"]);

Part of the problem is that appending strings to SQL statements is a very bad idea and leads to Sql Injection issues. Then you will have to consider what to do with strings that contain single and double quotes.

Using parameters like above will help avert the majority of problems you will encounter.

JayV
  • 3,238
  • 2
  • 9
  • 14