0

I will try to explain this clearly, so now I got

sqlConnection conn = new SqlConnection();
InitializeComponent();

conn.ConnectionString = "Data Source=servername;" +
                        "Initial Catalog=database;" +
                        "Integrated Security=True;";

in the MainWindow and I want to fire the command

SqlCommand scom = new SqlCommand(query, conn);

when a button is clicked, it's a stupid question now the button can't see conn because it's in the MainWindow how can I access it?

The thing is I don't want to reconfigure the connection every time the button is clicked.

2
  • You haven't shown the context of conn so we can't tell if it is in scope or not, but your description implies conn is decleared at the class (window) level so why can't the button event "see" it? Is the button on a different window? Commented Jul 10, 2016 at 13:45
  • 1
    you create one class for db connection and invoke the class file when ever you want that is best practice. Commented Jul 10, 2016 at 14:40

1 Answer 1

1

This gets the root level window:

Window parentWindow = Application.Current.MainWindow

or the immediate parent window

Window parentWindow = Window.GetWindow(this);

So access the conn property like this

if(parentwindow.conn != null)
{
    SqlCommand scom = new SqlCommand(query, parentwindow.conn);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.