将DataSet绑定到GridView时出现Null引用异常

时间:2013-03-28 21:10:02

标签: c# asp.net nullreferenceexception

我有以下代码在SQL数据库中运行一个非常简单的存储过程,然后尝试将结果数据绑定到ASP.NET GridView。

string cs = ConfigurationManager.ConnectionStrings["dbDuckDatabase"].ConnectionString;
string cmd = "spGetProductCategories";
using (SqlConnection con = new SqlConnection(cs))
{
    SqlDataAdapter da = new SqlDataAdapter(cmd, con);

    DataSet ds = new DataSet();
    da.Fill(ds);

    GridView1.DataSource = ds.Tables[0];
    GridView1.DataBind();
}

运行此代码时,Visual Studio 2010会在行上抛出Null Reference Exception错误:

GridView1.DataSource = ds.Tables[0];

这有什么奇怪的是我在另一个项目中运行了这个代码的版本。为了测试,我创建了一个新的空网站项目,只实现了上面的代码,它工作正常。有谁知道为什么它会在我正在进行的项目中抛出Null Reference Exception?

编辑:感谢大家的意见。我把它缩小到这样一个事实:当代码抛出Null Reference Exception错误时,这是​​因为它是从主页面执行的。我不认为从母版页执行代码与从普通的aspx页面执行代码有任何不同。有任何想法吗?

0 个答案:

没有答案
相关问题