【问题标题】:error Fill: SelectCommand.Connection property has not been initialized错误填充:SelectCommand.Connection 属性尚未初始化
【发布时间】:2014-04-20 22:18:51
【问题描述】:

这是我的代码:

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

【问题讨论】:

  • 究竟在哪一行?

标签: c#


【解决方案1】:

BindEmpGrid 方法中,您使用构造函数创建一个命令,该构造函数接受命令文本和连接。此行没有失败,但您没有任何名为 con 的局部变量。所以我认为这行有效是因为你有一个名为 con 的 SqlConnection 类型的全局变量,但是这个全局变量没有初始化。

因此,删除导致代码混乱的全局变量,并添加一个名为 con 的局部变量,就像您在 FillEmpDropdownList 方法中所做的那样

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

我建议也开始使用Using Statement,因为您的代码似乎在使用后没有关闭并正确处理连接,并且不要忘记始终使用参数化查询

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

【讨论】:

    【解决方案2】:

    您没有在BindEmpGrid() 函数中初始化您的连接对象con

    BindEmpGrid()函数中添加如下语句:

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

    【讨论】:

      猜你喜欢
      • 2011-08-10
      • 1970-01-01
      • 2015-07-01
      • 1970-01-01
      • 2013-02-25
      • 1970-01-01
      • 2014-03-06
      • 1970-01-01
      • 2014-03-18
      相关资源
      最近更新 更多