0

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

其中有产品 id、名称、价格和 cetegory。

我所做的是我将数据GridView明智地放入第一类,我想要的是当我检查特定行或多行并单击选择按钮时,它会在第二个网格视图中显示产品名称和价格。

但它的作用是将下一个选定项目覆盖到第二个网格视图中先前选定的项目,并仅显示一行而不是多个选定项目。

有谁能够帮我 ??

这是一个代码

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

        }
    }
4

1 回答 1

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();
}
于 2012-07-17T12:06:42.123 回答