如何填充列表<>来自SQL并在gridview中显示列表值

时间:2014-04-02 18:54:13

标签: c# list gridview

我需要使用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();
   }
 }

4 个答案:

答案 0 :(得分:2)

以下是一些建议:

  • gridview的数据源应该是整个集合。您的循环会一遍又一遍地覆盖数据源。试试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";