错误:System.NullReferenceException:未将对象引用设置为对象的实例

时间:2013-08-02 08:25:49

标签: c# asp.net

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

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();

上收到错误

我必须实例化什么?

1 个答案:

答案 0 :(得分:0)

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();
    }
}