-1

In my C# Application, I want to pass a connection string manually from a Form(formCon) to connection.cs. I've tried a lot and googled it, but nothing works fine.

This is the code written in connection.cs:

class connection
{
    public SqlConnection con;               
    public SqlCommand cmd = new SqlCommand();

    public connection()
    {        
        string conn = "Data Source=ds;Initial Catalog=initcat;uid=sa;pwd=pass";
        con = new SqlConnection(conn);
    }
}

I want to replace conn with the value from frmCon which contains the connection string.

Tobbe
  • 1,825
  • 3
  • 21
  • 37
Athira Anu
  • 11
  • 3

3 Answers3

0

Where is the instance of connection created? If it is created in formCon you can pass it to connection via its constructor, like this:

string connectionString = connectionStringFromForm();
connection conn = new connection(connectionString);

And edit your constructor:

public connection(string connectionString)
{
    con = new SqlConnection(connectionString);
}
Tobbe
  • 1,825
  • 3
  • 21
  • 37
0

Use parameterized constructor like this

class connection
    {

        public SqlConnection con;               
        public SqlCommand cmd = new SqlCommand();

        public connection(string connectionString)
        {

            con = new SqlConnection(connectionString);

        }

When you will create object of this class, you will pass this string like this

connection conn =new connection("Data Source=ds;Initial Catalog=initcat;uid=sa;pwd=pass")
Lali
  • 2,816
  • 4
  • 30
  • 47
0
string paramOneUse = "";
string paramTwoUse = "";

public connection (string param1, string param2){
  paramoneUse = param1;
  paramTwoUse = param2
}

then call the method you want to execute and use the paramaters you want to use

public void doSomething(){ 
 string conn = paramOneUse; // or paramTwoUse
 con = new SqlConnection(conn);
}

// keep in mind that im using void here only to simplyfy, if you are returning something then you can not use void

EDIT:

After reading the comments, this might be what you want: look here

Community
  • 1
  • 1
ThunD3eR
  • 3,216
  • 5
  • 50
  • 94
  • Thanks, but in that link it is already saying that "you to don't modify web.config from your, because every time when change, it will restart your application" . So i want to modify anywhere other than config file like class etc. Is it a good idea? – Athira Anu Sep 09 '15 at 06:52
  • read it more carefully. You should not modify the web.config on the fly. Which means do not make changes to you web.config while you application is running. You can however add a new key to it and get it via the System.Configuration.ConfigurationManager.AppSettings – ThunD3eR Sep 10 '15 at 11:51