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

时间:2014-03-15 14:31:13

标签: c#

这是我的代码:

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

2 个答案:

答案 0 :(得分: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);
      ....
 }

答案 1 :(得分:0)

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

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

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