Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
635 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 Reply

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...