错误ExecuteNonQuery:连接属性尚未初始化

时间:2019-05-29 10:48:44

标签: c# vb.net

我对以下代码有疑问:

namespace Elite_Shop
{
        public partial class Bill : Form
        {
            int j;
            int total = 0;
            SqlConnection sqlcon = new SqlConnection(@"Data Source=HP\SQLEXPRESS;Initial Catalog=EliteShop;Integrated Security=True  ");



        public Bill()
        {
            InitializeComponent();
        }
        public void get_value(int i)
        {
            j = i;
        }
        private void Bill_Load(object sender, EventArgs e)
        {
            if (sqlcon.State == ConnectionState.Open)
            {
                sqlcon.Close();
            }
            sqlcon.Open();
            DataSet1 ds = new DataSet1();
            SqlCommand cmd = new SqlCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "Select * from Salesman_Table Where SMID="+j+"";
            cmd.ExecuteNonQuery();
            DataTable dt = new DataTable();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(ds.DataTable1);

            SqlCommand cmd2 = new SqlCommand();
            cmd2.CommandType = CommandType.Text;
            cmd2.CommandText = "Select * from Sale_Table Where OrderID=" + j + "";
            cmd2.ExecuteNonQuery();
            DataTable dt2 = new DataTable();
            SqlDataAdapter da2 = new SqlDataAdapter(cmd2);
            da2.Fill(ds.DataTable2);
            da2.Fill(dt2);

            foreach (DataRow dr2 in dt2.Rows)
            {

                total = total + Convert.ToInt32(dr2["Sub Total"].ToString());
            }
            SaleReport sr = new SaleReport();
            sr.SetDataSource(ds);
            sr.SetParameterValue("Grand Total", total.ToString());
            crystalReportViewer1.ReportSource = sr;
        }
    }
}

执行时,返回以下错误消息:

  

ExecuteNonQuery:连接属性尚未初始化。

我该如何解决?

1 个答案:

答案 0 :(得分:0)

您需要在SqlCommand上设置Connection property

cmd.Connection = sqlcon;