2012-02-04 46 views
0

我有一個IDS列表1,2,4,6在我的列表(C#)我需要做的是從我的表提取對應於這些IDS的數據連接通過比較來自列表的數據從sql表中提取數據

enter image description here

我的代碼列表如下:

string str = "SELECT id1 FROM [Example] WHERE id2 = '1' UNION SELECT id2 FROM Example WHERE id1 = '1'"; 
      ds = new DataSet(str); 
      da = new SqlDataAdapter(str, con); 
      da.Fill(ds); 
      //GridView1.DataSource = ds; 
      //GridView1.DataBind(); 
      DataTable dtDetails = ds.Tables[0]; 
      List<int> lst = 
           (from dr in dtDetails.AsEnumerable() 
           select Convert.ToInt32(dr["id1"])).ToList<int>(); 

什麼上面的代碼確實是列表檢索沒有的2 3 4 6

我想要做的是檢索id2對應於這些沒有的是這樣嗎?

編輯:

string str = "SELECT id1 FROM [Example] WHERE id2 = '1' UNION SELECT id2 FROM Example WHERE id1 = '1'"; 
     ds = new DataSet(str); 
     da = new SqlDataAdapter(str, con); 
     da.Fill(ds); 
     DataTable dtDetails = ds.Tables[0]; 
     List<int> lst = 
          (from dr in dtDetails.AsEnumerable() 
          select Convert.ToInt32(dr["id1"])).ToList<int>(); 

     foreach (int prime in lst) // Loop through List with foreach 
     { 

      str1 = " SELECT id2 FROM [Connections] where id2= '"+prime+"'"; 
      SqlCommand cmd1 = new SqlCommand(str1, con); 
      cmd1.ExecuteNonQuery(); 
      DataSet ds1 = new DataSet(); 
      SqlDataAdapter da1 = new SqlDataAdapter(str1, con); 
      da1.Fill(ds1); 
      GridView1.DataSource = ds1; 
      GridView1.DataBind(); 

     } 

我的GridView不顯示任何

+0

對不起,我感到困惑;你想要達到什麼目的? – CarneyCode 2012-02-04 10:10:18

+0

檢查編輯=) – vini 2012-02-04 10:28:21

回答

-1

試試這個列表建構列表!

SELECT ID2 FROM例WHERE ID2 IN(SELECT ID1 FROM [實施例] WHERE ID2 = '1' UNION SELECT ID2 FROM示例,其中ID1 = '1')

-1

你可以做的是使用作爲你的選擇的一部分。因此,發送到SQL Server的select語句可能是:

SELECT * FROM [連接],其中ID1 IN(1,2,4,6)

在psudo代碼,這將是:

字符串列表=「1,2,4,6」; string str1 =「SELECT * FROM [Connections] where id1 IN(」+ list +「)」;

在你的代碼

當然,你想從你的ID

+0

它仍然給我同樣的結果,因爲它只顯示數據對應'6' – vini 2012-02-05 03:35:31

+0

無論如何,我得到了我的答案我想要的結果 – vini 2012-02-05 17:36:58