【发布时间】: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 代码,但在此之前检查您的
Datasetds,如果它不是null或rowcount在GetData方法中大于 0,然后检查您的 gridview 代码否则检查你的ConnectionString。
标签: c# asp.net visual-studio-2010 gridview