Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
634 views
in Technique[技术] by (71.8m points)

c# - Declaring SqlConnection throughout one form

I'm looking for some advise on C# - Please bare in mind that i'm only a beginner with C# & Sql.

I am looking to design a small program that will Add/Edit/Delete and run reports all linked to Sql database.

I wish to include multiple functions and Sql queries within different areas on the same form.

Example: 1. I wish to have a combo box that does a search (Select * from dbo.table) 2. I have a button that when clicked displays all information from another dbo.table.

My question is:

Would I have to declare my Sqlconnection multiple times or can this be declared within my:

public partial class MainMenu : Form
{
    SqlConnection mmConnection = new SqlConnection("#");
    SqlCommand mmCommand = new SqlCommand();
    SqlDataReader reader;
}

then i can use:

mmConnection.Open();
mmConnection.Close();

Any advise would be fantastic. If I can declare at the top of my form it would keep my code cleaner.

Kindest Regards, Zak Hargreaves.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Add your connection string in web.config file

<connectionStrings>
  <add name="CustomerDataConnectionString" connectionString="Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Northwind"
    providerName="System.Data.SqlClient" />
</connectionStrings>

and in aspx form

    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connection string"].ToString());

for more information use this link


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...