Click here to Skip to main content
15,893,161 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
this code for class connection

C#
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

C#
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");                
            }
Posted
Updated 15-Sep-14 21:59pm
v2

Change the method GetConnection to this.
Remove the variable declaration of SqlConnection inside the method.
C#
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();   
    }
}
 
Share this answer
 
v4
Comments
Sinisa Hajnal 16-Sep-14 4:09am    
Good catch!
thnx
but i try u code the same error
 
Share this answer
 
Comments
George Jonsson 16-Sep-14 4:15am    
Don't post comments as an answer.
C#
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();
    
    }
}


how to make {get; private set;}!?
 
Share this answer
 
Comments
George Jonsson 16-Sep-14 4:37am    
Don't post comments as an answer.
Use the 'Have a Question or Comment?' button under my solution.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900