我正在使用RESTful Web服务,我有一个列表,列出了我想要添加到gridview的所有对象。当我将它们添加到DataTable中的每一行时,每行的结果都是相同的。我不确定我做错了什么?
protected void ButtonSearch_Click(object sender, EventArgs e)
{
Results trackResults = (Results)Session["Result"];
foreach (Tracks t in trackResults.results)
{
//create datatable and columns,
DataTable table = new DataTable();
table.Columns.Add("Artist Name");
table.Columns.Add("Collection Name");
table.Columns.Add("Track Name");
table.Columns.Add("Artwork");
table.Columns.Add("Track Price");
table.Columns.Add("Release Date");
table.Columns.Add("Genre");
for (int i = 0; i < trackResults.results.Count; i++)
{
DataRow dr1 = table.NewRow();
dr1["Artist Name"] = t.artistName;
dr1["Collection Name"] = t.collectionName;
dr1["Track Name"] = t.trackName;
dr1["Artwork"] = t.artworkUrl30;
dr1["Track Price"] = t.trackPrice;
dr1["Release Date"] = t.releaseDate;
dr1["Genre"] = t.primaryGenreName;
table.Rows.Add(dr1);
}
GridView1.DataSource = table;
GridView1.DataBind();
答案 0 :(得分:1)
1-无需在foreach循环中创建数据表,也无需编写for循环。
2-您应该在循环外部创建数据表和列,然后创建行并向表中添加行
3-将表分配给foreach循环结束的datagridview。
我已经编辑了下面的代码,但没有编译。试试吧
protected void ButtonSearch_Click(object sender, EventArgs e)
{
Results trackResults = (Results)Session["Result"];
//create datatable and columns,
DataTable table = new DataTable();
table.Columns.Add("Artist Name");
table.Columns.Add("Collection Name");
table.Columns.Add("Track Name");
table.Columns.Add("Artwork");
table.Columns.Add("Track Price");
table.Columns.Add("Release Date");
table.Columns.Add("Genre");
foreach (Tracks t in trackResults.results)
{
DataRow dr1 = table.NewRow();
dr1["Artist Name"] = t.artistName;
dr1["Collection Name"] = t.collectionName;
dr1["Track Name"] = t.trackName;
dr1["Artwork"] = t.artworkUrl30;
dr1["Track Price"] = t.trackPrice;
dr1["Release Date"] = t.releaseDate;
dr1["Genre"] = t.primaryGenreName;
table.Rows.Add(dr1);
}
GridView1.DataSource = table;
GridView1.DataBind();
}
答案 1 :(得分:0)
看起来您需要更改初始化内容的方式。现在,您正在为trackResults.results
中的每个记录创建新的表对象,然后在每次迭代时在绑定网格上创建。您可能希望将其更改为:
protected void ButtonSearch_Click(object sender, EventArgs e)
{
Results trackResults = (Results)Session["Result"];
//create datatable and columns,
DataTable table = new DataTable();
table.Columns.Add("Artist Name");
table.Columns.Add("Collection Name");
table.Columns.Add("Track Name");
table.Columns.Add("Artwork");
table.Columns.Add("Track Price");
table.Columns.Add("Release Date");
table.Columns.Add("Genre");
foreach (Tracks t in trackResults.results)
{
DataRow dr1 = table.NewRow();
dr1["Artist Name"] = t.artistName;
dr1["Collection Name"] = t.collectionName;
dr1["Track Name"] = t.trackName;
dr1["Artwork"] = t.artworkUrl30;
dr1["Track Price"] = t.trackPrice;
dr1["Release Date"] = t.releaseDate;
dr1["Genre"] = t.primaryGenreName;
table.Rows.Add(dr1);
}
GridView1.DataSource = table;
GridView1.DataBind();