SelectCommand.Connection属性尚未初始化。 [英] SelectCommand.Connection property has not been initialized.

查看:944
本文介绍了SelectCommand.Connection属性尚未初始化。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此类连接代码



this code for class connection

public class myConnection
   {
       public SqlConnection con;
       public void GetConnection()
       {

           string str = "Data Source=HEND-PC;Initial Catalog=f_library;Integrated Security=True";
           SqlConnection con = new SqlConnection(str);
           con.Open();

       }
   }





这是表格





this is for form

public partial class Form1 : Form
    {
        myConnection cnn = new myConnection();
        
        public Form1()
        {
           
            InitializeComponent();
         


        }

        private void button1_Click(object sender, EventArgs e)
        {
          
            cnn.GetConnection();
            
            SqlDataAdapter dad = new SqlDataAdapter("Select * from emp where emp_fname='" + txt_name.Text + "'and emp_lname='" + txt_lname.Text + "' ", cnn.con);
             DataSet ds = new DataSet();
            dad.Fill(ds);
            if (ds.Tables[0].Rows.Count > 0)
            {
                
                dataGridView1.DataSource = ds.Tables[0];
            }
            else
            {
                  MessageBox.Show("conn is failed");                
            }

推荐答案

将方法 GetConnection 更改为此。

在方法中删除SqlConnection的变量声明。

Change the method GetConnection to this.
Remove the variable declaration of SqlConnection inside the method.
public class myConnection
{
    // This construct auto creates a property.
    // You can use this in your code as a regular property
    // private set means that you can only give a value to the property inside this class
    public SqlConnection con { get; private set; }

    public void GetConnection()
    {
        string str = "Data Source=HEND-PC;Initial Catalog=f_library;Integrated Security=True";
        SqlConnection con = new SqlConnection(str);
        con = new SqlConnection(str);
        con.Open();   
    }
}


thnx

但我尝试你编码相同的错误
thnx
but i try u code the same error


public class myConnection
{
    public SqlConnection con { get; private set; } // Don't use public variables
    public void GetConnection()
    {
 
        string str = "Data Source=HEND-PC;Initial Catalog=f_library;Integrated Security=True";
        SqlConnection con = new SqlConnection(str);
        con = new SqlConnection(str);
        con.Open();
    
    }
}





怎么做{get;私人套装;}!?



how to make {get; private set;}!?


这篇关于SelectCommand.Connection属性尚未初始化。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆