从数据源检索数据并在GridView中显示

时间:2013-12-02 14:44:04

标签: c# asp.net visual-studio-2010 gridview

我在VS 2010中将数据显示在gridview中时遇到问题。 我有SQLdataSource连接到我的数据库,但gridview根本没有显示,我的错误信息就是显示的全部内容。谁会知道为什么会这样?

这是我的代码:

`using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.Web.Services.Description;

namespace DBprototype2
{
    public partial class _Default : System.Web.UI.Page
    {
             void Page_Load(Object sender, EventArgs e)
  {

    // This example uses Microsoft SQL Server and connects
    // to the Northwind sample database. The data source needs
    // to be bound to the GridView control only when the 
    // page is first loaded. Thereafter, the values are
    // stored in view state.                      
    if(!IsPostBack)
    {

      // Declare the query string.
      String queryString = 
        "SELECT * FROM ";

      // Run the query and bind the resulting DataSet
      // to the GridView control.
      DataSet ds = GetData(queryString);
      if (ds.Tables.Count > 0)
      {
        GridView1.DataSource = ds;
        GridView1.DataBind();
        Label1.Text = "Connected.";
      }
      else
      {
        Label1.Text = "Unable to connect to the database.";
      }

    }     

  }

  DataSet GetData(String queryString)
  {

    // Retrieve the connection string stored in the Web.config file.
      String connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

      DataSet ds = new DataSet();

    try
    {
      // Connect to the database and run the query.
      SqlConnection connection = new SqlConnection(connectionString);        
      SqlDataAdapter adapter = new SqlDataAdapter(queryString, connection);

      // Fill the DataSet.
      adapter.Fill(ds);
      Label1.Text = "Connected.";

    }
    catch(Exception ex)
    {

      // The connection failed. Display an error message.
      Label1.Text = "Unable to connect.";


    }

    return ds;

  }
             }
        }




`

如果有人能告诉我我的代码存在问题会非常有帮助。

1 个答案:

答案 0 :(得分:2)

问题在于您的查询:

String queryString = 
        "SELECT * FROM ";

缺少表格可供选择,稍后在您的方法GetData中,您未在查询中添加任何表名称,这就是失败的原因。

  • 另请考虑将connection括在using声明中
  • 使用Exception对象ex.Message而不是标签中的硬编码错误,这将帮助您调试并查看到底出了什么问题。
  • 不是针对此特定情况,但始终考虑使用参数化查询。