【问题标题】:Error :System.NullReferenceException: Object reference not set to an instance of an object错误:System.NullReferenceException:对象引用未设置为对象的实例
【发布时间】:2013-08-02 08:25:48
【问题描述】:

我正在尝试调试上述错误。下面是我的代码。

private SqlConnection SQLConn(string name) 
{
    SqlConnection conn = new SqlConnection();
    conn.ConnectionString = ConfigurationManager.ConnectionStrings[name].ConnectionString;
    return conn;
}

 protected void rb2_SelectedIndexChanged(object sender, EventArgs e)
{
    SqlConnection conn = new SqlConnection();

    conn = SQLConn("Plastics");
  try
    {
        string selectSQL = "SELECT [Description], [Code], [Change] FROM [plastics]";

        SqlCommand cmd = new SqlCommand(selectSQL, conn);

        conn.Open();

        GridView1.DataSource = cmd.ExecuteReader();
        GridView1.DataBind();

    }
    catch (SqlException Exception)
    {
        // catch exception
        Response.Write("An error occured");
    }
    finally
    {
        conn.Close();
    }

}

GridView1.DataSource = cmd.ExecuteReader(); 出现错误

我必须实例化什么?

【问题讨论】:

  • 检查if (GridView1 != null)
  • 非常感谢您的快速响应。我输入if语句后没有出现错误,但gridview不显示。
  • 您的 .aspx 文件中有一个名为 GridView1 的 GridView 吗?
  • 您的“SqlDataReader”是否为空?
  • 在调试器中运行代码会发生什么?

标签: c# asp.net


【解决方案1】:
using (DataSet ds = new DataSet())
{
    DataTable dt = new DataTable();
    ds.Tables.Add(dt);
    string str = "User ID=username;Password=password;Data Source=Test";
    SqlConnection conn = new SqlConnection(str);
    conn.Open();
    SqlCommand cmd = new SqlCommand();
    cmd.Connection = conn;
    cmd.CommandText = "select * from table_name";
    cmd.CommandType = CommandType.Text;
    SqlDataAdapter da = new SqlDataAdapter(cmd); 
    da.Fill(dt);
    if(dt!=null)
    {
       GridView2.DataSource = dt;
       GridView2.DataBind();
    }
}

【讨论】:

  • DataSet 上使用using 做得很好,但不是SqlConnectionSqlCommandSqlDataAdapter 等重要的东西。
  • 由于这是一个不连贯的架构,所以没有资源被占用的机会。我们可能只想考虑释放 DataSet ...
  • 感谢您的代码。我仍然在 GridView1.DataSource = dt; 上遇到同样的错误
  • 你能运行上面放在 SQL 中的查询,看看你是否先得到任何输出???或者您可以调试一下,看看您的 Datatable 中是否有任何数据。
  • 您也尝试将 AutoGenerateColumns 设置为 true
猜你喜欢
  • 1970-01-01
  • 2013-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-09
  • 1970-01-01
相关资源
最近更新 更多