简体   繁体   English

错误填充:SelectCommand.Connection属性尚未初始化

[英]error Fill: SelectCommand.Connection property has not been initialized

This is my code: 这是我的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Windows.Forms;
using System.Web.Security;
using System.IO;

public partial class Search : System.Web.UI.Page
{
    SqlConnection con;
    SqlCommand cmd;
    SqlCommand cmd1;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            FillEmpDropdownList();
        }

    }
    protected void FillEmpDropdownList()
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["database1ConnectionString"].ConnectionString);
        SqlCommand cmd = new SqlCommand();
        SqlDataAdapter adp = new SqlDataAdapter();
        DataTable dt = new DataTable();
        try
        {
            cmd = new SqlCommand("Select * from Emp_Tb", con);
            adp.SelectCommand = cmd;
            adp.Fill(dt);
            ddlEmpRecord.DataSource = dt;
            ddlEmpRecord.DataTextField = "Emp_Id";
            ddlEmpRecord.DataValueField = "Emp_Id";
            ddlEmpRecord.DataBind();
            ddlEmpRecord.Items.Insert(0, "-- Select --");
              //ddlEmpRecord.Items.Insert(0, new ListItem("Select Emp Id", "-1"));
        }
        catch (Exception ex)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Error occured : " + ex.Message.ToString() + "');", true);
        }
        finally
        {
            cmd.Dispose();
            adp.Dispose();
            dt.Clear();
            dt.Dispose();
        }
    }

    protected void ddlEmpRecord_SelectedIndexChanged(object sender, EventArgs e)
    {
         try
        {
            int empId = Convert.ToInt32(ddlEmpRecord.SelectedValue);
            BindEmpGrid(empId);
        }
        catch (Exception ex)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Error occured : " + ex.Message.ToString() + "');", true);
        }       
    }

    private void BindEmpGrid(Int32 empId)
    {
        DataTable dt = new DataTable();
        SqlDataAdapter adp = new SqlDataAdapter();
        try
        {
            SqlCommand cmd1 = new SqlCommand("select *  from Emp_Tb where Emp_Id=" + empId + " ", con);
            adp.SelectCommand = cmd1;
            adp.Fill(dt);

            if (dt.Rows.Count > 0)
            {
               grdEmp.DataSource = dt;
               lblEmpId.Text = "Emp Id :" +  dt.Rows[0]["Emp_Id"].ToString();
               lblEmpName.Text ="Emp Name: " + dt.Rows[0]["EmpName"].ToString();
               lblCity.Text = "City: " +dt.Rows[0]["City"].ToString();
               lblSalary.Text = "Salary: " + dt.Rows[0]["Salary"].ToString();
               grdEmp.DataBind();
            }
        }
        catch (Exception ex)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Error occured : " + ex.Message.ToString() + "');", true);
        }
        finally
        {
            dt.Clear();
            dt.Dispose();
            adp.Dispose();
        }
    }
    }

In the method BindEmpGrid you create a command with the constructor that takes the commandtext and the connection. 在方法BindEmpGrid您将创建一个带有构造函数的命令,该构造函数将使用命令文本和连接。 This line doesn't fail, but you don't have any local variable named con . 这行不会失败,但是您没有任何名为con局部变量。 So I suppose that this line works because you have a global variable of SqlConnection type named con, but this global variable is not initialized. 所以我想这行是行得通的,因为您有一个名为con的SqlConnection类型的全局变量,但是该全局变量未初始化。

So, remove the global variable that is causing confusion in your code, and add a local variable named con as you already do in the FillEmpDropdownList method 因此,删除在代码中引起混乱的全局变量,并像在FillEmpDropdownList方法中一样添加一个名为con的局部变量。

private void BindEmpGrid(Int32 empId)
{
    DataTable dt = new DataTable();
    SqlDataAdapter adp = new SqlDataAdapter();
    try
    {

         SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["database1ConnectionString"].ConnectionString);
         SqlCommand cmd1 = new SqlCommand("select *  from Emp_Tb where Emp_Id=@id", con);
         cmd1.Parameters.AddWithValue("@id",empId );
         adp.SelectCommand = cmd1;
         adp.Fill(dt);

I suggest also to start using the Using Statement , because it seems that your code doesn't close and dispose correctly the connection after the usage and do not forget to always use a parameterized query 我建议也开始使用Using语句 ,因为似乎您的代码在使用后没有关闭并正确处理连接,并且不要忘记总是使用参数化查询

 using(SqlConnection con = new SqlConnection(....))
 using(SqlCommand cmd1 = new SqlCommand("select *  from Emp_Tb where Emp_Id=@id", con))
 {
      cmd1.Parameters.AddWithValue("@id",empId );
      cmd1.Parameters.AddWithValue("@id",empId );
      adp.SelectCommand = cmd1;
      adp.Fill(dt);
      ....
 }

You did not intialise your connection object con in BindEmpGrid() function. 您没有在BindEmpGrid()函数中BindEmpGrid()连接对象con

Add the below statement in BindEmpGrid() function: BindEmpGrid()函数中添加以下语句:

con = new SqlConnection(ConfigurationManager.
         ConnectionStrings["database1ConnectionString"].ConnectionString);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 填充:SelectCommand.Connection属性尚未初始化错误 - Fill: SelectCommand.Connection property has not been initialized error 如何解决Fill:SelectCommand.Connection属性尚未初始化 - how to solve Fill: SelectCommand.Connection property has not been initialized 填充:SelectCommand.Connection 属性尚未初始化 C# - Fill: SelectCommand.Connection property has not been initialized C# 填充:SelectCommand.Connection属性尚未初始化 - Fill: SelectCommand.Connection property has not been initialized 填充:SelectCommand.Connection 属性尚未初始化 - Fill: SelectCommand.Connection property has not been initialized SelectCommand.Connection属性尚未初始化 - SelectCommand.Connection property has not been initialized C#错误:“填充:SelectCommand.Connection属性尚未初始化。” - C# Error: “Fill: SelectCommand.Connection property has not been initialized.” C#错误:“填充:SelectCommand.Connection属性尚未初始化。” - C# Error: “Fill: SelectCommand.Connection property has not been initialized.” C#错误:“填充:SelectCommand.Connection属性尚未初始化。”仅在PC上 - C# Error: “Fill: SelectCommand.Connection property has not been initialized.” just in on pc SSIS 脚本任务错误。 填充:SelectCommand.Connection 属性尚未初始化 - SSIS Script Task Error. Fill: SelectCommand.Connection property has not been initialized
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM