复选从gridview1到gridview2的所选行ASP.NET C#

时间:2012-07-17 11:46:52

标签: c# asp.net gridview checkbox

正如标题所说,无论如何我有一张表sql-server 产品

其中包含产品ID,名称,价格和产品。

我所做的是将数据提升到第一GridView类别,我想要的是当我检查该特定行或多行并单击选择按钮时,它显示第二个gridview中的产品名称和价格。< / p>

但它的作用是它将下一个选定的项目覆盖到第二个gridview中先前选择的项目,并显示onlu一行而不是多个所选项目。

是谁能帮助我?

这是一个代码

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();
            }

        }
    }

1 个答案:

答案 0 :(得分:0)

您将网格绑定了太多次。

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();
}