2012-07-17 19 views
0

正如標題所說,無論如何我有一個表是sql-server產品複選框從gridview1到gridview2的選定行ASP.NET C#

它有產品ID,名稱,價格和cetegory。

我所做的是我得到數據到第一GridView類別明智,我想要的是當我檢查特定行或多行並單擊選擇按鈕shuld顯示產品名稱和價格在第二個gridview。

但是它做的是覆蓋第二個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(); 
      } 

     } 
    } 
+0

你似乎是樹立了一個新的'DataSource' /'的DataBind()'在同'GridView2'例如在循環中,每次...這會按照你說了,留給你的只有列表中的最後一項 – freefaller 2012-07-17 12:05:10

回答

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

感謝Amiram它的作品!所以這意味着我必須先將它們存儲在數組中,對嗎? – 2012-07-17 14:24:15

+0

是的,你需要先保存它們 – 2012-07-17 14:31:22

+0

但實際上這個代碼做了什麼? string.Join(「,」,checkedIDs.ToArray()); – 2012-07-17 14:31:31