0

I want to copy particular row in items table and copy it into a new table (name- cart). And display the all records in cart table in a dataGridView. Help !

con = new System.Data.SqlClient.SqlConnection();

        con.ConnectionString = " Data Source=(LocalDB)\\v11.0;AttachDbFilename=|DataDirectory|\\posdb.mdf;Integrated Security=True";



        string query = "INSERT INTO cart (item_id,Description,Unit_Price,Qty) SELECT item_id,Description,price,'" + txtqty.Text + "' FROM items WHERE item_id = '" + textBox1.Text + "'";
        string qry = "SELECT * FROM cart";

        System.Data.SqlClient.SqlDataAdapter da;
        System.Data.SqlClient.SqlDataAdapter da1;
        da = new System.Data.SqlClient.SqlDataAdapter(query, con);
        da1 = new System.Data.SqlClient.SqlDataAdapter(qry, con);

        ds1 = new DataSet();
        con.Open();
        da1.Fill(ds1,"cart");
        con.Close();
        dataGridView1.DataSource = ds1;
        dataGridView1.DataMember = "cart";

Help ! ......

  • 3
    call that code when you click the button? – rmjoia Oct 20 '17 at 08:05
  • Might be good to know what sort of parameters we are talking about too. How would you be filtering on the *items* table? – geostocker Oct 20 '17 at 08:06
  • @geostocker i have a textbox1 to filter the data."WHERE item_id='"+textbox1.text+"' " – Uditha Kanishka Oct 20 '17 at 08:11
  • 1
    Your code is vulnerable to SQL injections, try using parameters – saidfagan Oct 20 '17 at 08:13
  • I'd suggest setting up a stored procedure that does all of that for you. 1. get the row from item based on query and simply insert the result into your cart table. Then display the cart based on a view or something. Should be fairly simple. Set up the stp and then when that call has been finished you do a seperate call to the view (or all in the same stp). :( – geostocker Oct 20 '17 at 08:20
  • @geostocker Thank. But how do i copy the record and past it in a another table.? – Uditha Kanishka Oct 20 '17 at 08:24
  • If it's an entire row (or multiple rows) your best bet would be to use a cursor. It might seem a bit scary, but it's really simple to use when you have set up your first! :) – geostocker Oct 20 '17 at 08:31

1 Answers1

2
protected void btn_Click(object sender, EventArgs e)
    {
     insert();
     View();
     }
    private void insert()
    {
      // write insert query 
    }
   private void View()
    {
     // write select query and bind to grid
    }
Boney Jose
  • 315
  • 1
  • 18