我需要使用SQL填充List,然后在gridview中显示值。我认为我非常接近,但由于某种原因,它下面的代码不起作用。我将不胜感激任何帮助。谢谢!
您好,我合并了您的解决方案,我将所有值都放在一个长列中,而且没有标题。有任何想法吗?谢谢!
List<String> valuesList = new List<string>();
String queryString = "Select NRCode__c,Amazon_Listing_Level__c, Amazon_Rule_ID__c,ESTShipPrice__c from vendors";
SqlDataReader dr = classdb.LoadReader(queryString) as SqlDataReader;
if (dr.HasRows)
{
while (dr.Read())
{
valuesList.Add(dr.GetString(0));
valuesList.Add(dr.GetString(1));
valuesList.Add(dr.GetString(2));
valuesList.Add(dr.GetString(3));
}
dr.Close();
Label1.Text = "works";
}
else
{
dr.Close();
Label1.Text = "No working";
}
GridView1.AutoGenerateColumns = true;
GridView1.DataSource = valuesList;
GridView1.DataBind();
}
}
答案 0 :(得分:2)
以下是一些建议:
GridView1.DataSource = valuesList
。SqlDataAdapter
并写入DataTable
来大大简化:< / LI>
示例:
String queryString = "Select NRCode__c,Amazon_Listing_Level__c, Amazon_Rule_ID__c,ESTShipPrice__c from vendors";
SqlDataAdapter sda = new SqlDataAdapter(queryString, connectionString);
DataTable results = new DataTable();
sda.Fill(results);
GridView1.AutoGenerateColumns = true;
GridView1.DataSource = results;
GridView1.DataBind();
答案 1 :(得分:1)
看起来问题就在这里:
for (int i = 0; i < valuesList.Count; i++)
{
GridView1.AutoGenerateColumns = true;
GridView1.DataSource = valuesList[i];
GridView1.DataBind();
}
你需要摆脱for循环。数据源应该只是valuesList。
GridView1.AutoGenerateColumns = true;
GridView1.DataSource = valuesList;
GridView1.DataBind();
答案 2 :(得分:1)
您还在遍历您的值并继续将它们添加为数据源。 改变这个:
for (int i = 0; i < valuesList.Count; i++)
{
GridView1.AutoGenerateColumns = true;
GridView1.DataSource = valuesList[i];
GridView1.DataBind();
}
是:
GridView1.DataSource = valuesList;
GridView1.DataBind();
答案 3 :(得分:0)
替换它:
dr.Read();
valuesList.Add(dr.GetString(0));
valuesList.Add(dr.GetString(1));
valuesList.Add(dr.GetString(2));
valuesList.Add(dr.GetString(3));
dr.Close();
Label1.Text = "works";
有了这个:
while(dr.Read())
{
valuesList.Add(dr.GetString(0));
valuesList.Add(dr.GetString(1));
valuesList.Add(dr.GetString(2));
valuesList.Add(dr.GetString(3));
}
dr.Close();
Label1.Text = "works";