0

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

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(); 上收到错误消息

我必须实例化什么?

4

1 回答 1

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();
    }
}
于 2013-08-02T08:31:22.440 回答