2014-03-29 121 views
1

當while循環重複迭代時,我已經有一個問題,已經綁定的是由新記錄替換,但我想通過while循環的迭代來綁定所有數據。Gridview數據綁定

我是一個新的我不知道它是如何可能的。

while (i >= 0) 
{ 
    if (i != 0) 
    { 
     group_idd = group_ids[--i]; 
    }     
    SqlConnection connection3 = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection_String"].ConnectionString); 
    using (connection3) 
    { 
     using (SqlCommand cmdd = new SqlCommand()) 
     { 
      cmdd.CommandText = "SELECT [news_category],[id] FROM [news_profile] WHERE [user_id]='" + user_id + "' AND [group_id]='" + group_idd + "' AND [profile_id] IS NOT NULL"; 
      cmdd.Connection = connection3; 
      connection3.Open(); 
      GridView1.DataSource = cmdd.ExecuteReader(); 
      GridView1.DataBind(); 
      connection3.Close();        
     } 
    } 
    if (i == 0) 
    { 
    --i; 
    } 
} 

回答

1

在你創建一個小班

public class NewsProfile 
{ 
    public string NewsID { get; set; } 
    public string NewsCategory { get; set; } 
} 

現在隱藏代碼,這樣做

List<NewsProfile> newsProfiles = new List<NewsProfile>(); 
// while loop here 
SqlConnection connection3 = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection_String"].ConnectionString); 
using (connection3) 
{ 
    using (SqlCommand cmdd = new SqlCommand()) 
    { 
     cmdd.CommandText = "SELECT [news_category],[id] FROM [news_profile] WHERE [user_id]='" + user_id + "' AND [group_id]='" + group_idd + "' AND [profile_id] IS NOT NULL"; 
     cmdd.Connection = connection3; 
     connection3.Open(); 
     while (reader.Read()) 
     { 
      NewsProfile np = new NewsProfile(); 
      np.NewsCategory = reader.IsDBNull(0) ? "" : reader.GetString(0); 
      np.NewsID = reader.IsDBNull(1) ? "" : reader.GetString(1); 
      newsProfiles.Add(np); 
     } 
    } 
} 
//end while loop here 
GridView1.DataSource = newsProfiles; 
GridView1.DataBind();