【问题标题】:Retrieving Data From a data source and displaying in a GridView从数据源检索数据并在 GridView 中显示
【发布时间】:2013-12-02 14:44:04
【问题描述】:

在 VS 2010 中获取要在网格视图中显示的数据时遇到问题。 我有一个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;

  }
             }
        }




`

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

【问题讨论】:

  • 您应该检查并确认您的连接字符串是正确的。
  • BTW 也向我们展示您的 gridview 代码,但在此之前检查您的 Dataset ds,如果它不是 nullrowcountGetData 方法中大于 0,然后检查您的 gridview 代码否则检查你的ConnectionString

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


【解决方案1】:

问题在于您的查询:

String queryString = 
        "SELECT * FROM ";

缺少要选择的表,稍后在您的方法GetData 中您没有在查询中添加任何表名,这就是它失败的原因。

  • 还可以考虑将您的connection 包含在using 声明中
  • 在标签中使用异常对象ex.Message 而不是硬编码错误,这将帮助您调试并查看到底出了什么问题。
  • 不适用于这种特殊情况,但始终考虑使用参数化查询。

【讨论】:

  • @user2674605,只需将您的查询设置为SELECT * FROM someTable,其中someTable 是您的表名,不要修改GetData
  • 感谢您的帮助,但我更新了它,它仍然给我同样的错误信息?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-31
  • 1970-01-01
  • 2015-09-13
相关资源
最近更新 更多