connection属性尚未初始化的问题
在VS2005中有一个GridView1,有如下的代码:
using System.Web;
using System;
using System.Data;
using System.Configuration;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {            SqlConnection con = new SqlConnection("Data Source=MYCOMPUTE\\SQLEXPRESS;Initial Catalog=newswebsite;User ID=designer;Password=123");
            con.Open();
            if (con.State == ConnectionState.Closed)
            {
                Response.Write("连接还未打开!!!!");
                
            }
            //string sqlstr = "select * from category";
            //SqlCommand cmd = new SqlCommand(sqlstr);
            //SqlDataReader sdr = cmd.ExecuteReader();
            //this.GridView1.DataSource = sdr;
            //this.GridView1.DataBind();
           
        }
    }
}结果调试过程中什么都没有出现,如果把那些注释的恢复正常,那么就出现了说connection尚未初始化,是什么原因,请高手帮助,其中sqlconnection的字符串是从sqldatasource中复制过来的,如果单纯用sqldatasorce作为数据源的话那一切又是正常的,下面的SQL语句也是复制过来的,错误应该不会出现在这吧,如果我在sqlconnection上加一个try catch语句块的话,显示的错误是上下文中不存在变量con,不知道是什么原因求助!

解决方案 »

  1.   

    SqlCommand cmd = new SqlCommand(sqlstr,con);
      

  2.   

    你没有给sqlCommand设置connection属性,楼上的是直接通过构造函数传递connectino对象,是一种解决方法,
    你也可以给sqlcommand的connection属性赋值来达到目的。
      

  3.   

    在构造SqlCommand 对象的时候需要一个SqlConnection对象和一个代表SQl语句的字符串对象,而你在构造的时候缺少了SqlConnection 修改你的代码:string sqlstr = "select * from category";
                SqlCommand cmd = new SqlCommand(sqlstr);
     cmd.COnnection = con;
    cmd.connection.Open();
                SqlDataReader sdr = cmd.ExecuteReader();
                this.GridView1.DataSource = sdr;
                this.GridView1.DataBind(); 
      

  4.   

    string sqlstr = "select * from category";
    SqlCommand cmd = new SqlCommand(sqlstr,con);
    SqlDataReader sdr = cmd.ExecuteReader();
    this.GridView1.DataSource = sdr;
    this.GridView1.DataBind();
      

  5.   

    咱加上了con以后调试的页面上什么都没有呢?就是显示出来的IE上什么也不显示???不过没有什么错误,是什么原因?
      

  6.   


    所你注解的代码改为下面的:
                string sqlstr = "select * from category";
                SqlDataAdapter sda = new SqlDataAdapter(sqlstr,第二个参数加上连接);
                DataSet ds = new DataSet();
                sda.Fill(ds);
                this.GridView1.DataSource = ds.Tables[0];
                this.GridView1.DataBind();
      

  7.   

    cmd.COnnection = con;
    cmd.connection.Open(); 
      

  8.   

    我想说的是你加上了以后,建议你放弃使用SqlDataReader,用Sqldataadapter填充DATASET试试看。还有就是你可以单步调试看看哪个地方出现了错误
      

  9.   

    using(SqlConnection con = new SqlConnection(conString))
    {
    SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM category", con);
    DataSet ds = new DataSet();
    da.Fill(ds);
    GridView1.DataSource = ds;
    GridView1.DataBind();
    }