簡體   English   中英

錯誤填充:SelectCommand.Connection屬性尚未初始化

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

這是我的代碼:

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

在方法BindEmpGrid您將創建一個帶有構造函數的命令,該構造函數將使用命令文本和連接。 這行不會失敗,但是您沒有任何名為con局部變量。 所以我想這行是行得通的,因為您有一個名為con的SqlConnection類型的全局變量,但是該全局變量未初始化。

因此,刪除在代碼中引起混亂的全局變量,並像在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);

我建議也開始使用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);
      ....
 }

您沒有在BindEmpGrid()函數中BindEmpGrid()連接對象con

BindEmpGrid()函數中添加以下語句:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM