简体   繁体   中英

Error :System.NullReferenceException: Object reference not set to an instance of an object

I am trying to debug the above error. Below is my code.

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

}

I get an error on GridView1.DataSource = cmd.ExecuteReader();

What must I instantiate?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM