简体   繁体   中英

checkboxed selected rows from gridview1 to gridview2 ASP.NET C#

As title said it all anyway I have a table is sql-server products .

Which has product id, name,price and cetegory.

what i did is i get data into 1st GridView category wise, and what i want is when i checked that particular row or multiple row and click select button it shuld show product name and price in 2nd gridview.

But what its do is it override the next selected item to previously selected item in 2nd gridview and shows onlu one row not multiple selected items.

can anybody help me ??

here is a code

protected void Button1_Click(object sender, EventArgs e)
    {
        for (int i = 0; i < GridView1.Rows.Count; i++)
        {

            CheckBox chbox = GridView1.Rows[i].Cells[0].FindControl("CheckBox1") as CheckBox;

            if (chbox.Checked == true)
            {
                string conn = ConfigurationManager.ConnectionStrings["Test_T3ConnectionString2"].ConnectionString;
                SqlConnection con = new SqlConnection(conn);
                string query = "select prod_name,price from products where prod_id = '" + GridView1.Rows[i].Cells[1].Text + "'";
                SqlCommand cmd = new SqlCommand(query, con);
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataTable dt = new DataTable();
                da.Fill(dt);

                GridView2.DataSource = dt;
                GridView2.DataBind();
            }

        }
    }

You binded the grid too many times.

protected void Button1_Click(object sender, EventArgs e) {
List<string> checkedIDs = new List<string>();

 for (int i = 0; i < GridView1.Rows.Count; i++) {

    CheckBox chbox = GridView1.Rows[i].Cells[0].FindControl("CheckBox1") as CheckBox;

    if (chbox.Checked == true)
    {
        checkedIDs.Add("'" + GridView1.Rows[i].Cells[1].Text + "'");
    }

}


        string conn = ConfigurationManager.ConnectionStrings["Test_T3ConnectionString2"].ConnectionString;
        SqlConnection con = new SqlConnection(conn);
        string query = "select prod_name,price from products where prod_id in (" + string.Join(",", checkedIDs.ToArray()) + ")";
        SqlCommand cmd = new SqlCommand(query, con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        da.Fill(dt);

        GridView2.DataSource = dt;
        GridView2.DataBind();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM