Gridview数据绑定

时间:2014-03-29 19:32:52

标签: asp.net gridview

我有一个问题,当while循环重复迭代时,已经绑定的替换为新记录,但我想通过while循环的迭代绑定所有数据。

我是新手,我不知道它是怎么回事。

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 个答案:

答案 0 :(得分: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();