填充:SelectCommand.Connection属性尚未初始化C#

时间:2016-04-22 17:09:21

标签: c# database-connection connection-string

public partial class WebForm1 : System.Web.UI.Page
{
    SqlConnection con=new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True");
    SqlDataAdapter da = new SqlDataAdapter();
    SqlCommand cmd = new SqlCommand();
    DataTable dt = new DataTable();


    protected void Page_Load(object sender, EventArgs e)
    {
    cmd.CommandText="select id from regtb where id="+Session["id"];
    da.SelectCommand = cmd;
    da.Fill(dt);
    if(dt.Rows.Count>0)
    {
        Response.Redirect("userlogin.aspx");

    }

    }

这段代码有什么问题? 任何人都可以帮我这个 我收到此错误,我不知道如何纠正这个。

1 个答案:

答案 0 :(得分:1)

您需要打开SqlConnection,然后将其分配给SqlCommand:

                con.Open();
                cmd.Connection = con;