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/Dele
Consider to declare your SqlConnection
as field of your main form (if you don't want to use it on any other form).
Note: Add reference to System.Configuration
assembly in order to use ConfigurationManager
class.
Example:
public partial class MainMenu : Form
{
SqlConnection _myConnection;
public Form1()
{
InitializeComponent();
this._myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[0].ConnectionString);
}
public void ExecuteAQueryExample()
{
if (this._myConnection.State != ConnectionState.Open) this._myConnection.Open();
using (var command = this._myConnection.CreateCommand())
{
// ...
}
this._myConnection.Close();
}
}
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
Of course, you dont need to have multiple SqlConnection instances. for most application, one connection is sufficient. sqlCommand on the other hand is another thing: You might step into trouble if reusing it, but this is more a design issue than a technical thing.
I would suggest you move all your database access code to another class ("DataProvider"/"DatabaseController" or whatever name you think is sufficient) to properly encapsulate the code parts. There is no need for a form to directly handle SqlConnection or sqlCommand objects, let it indirectly happen via public methods of that controller type:
public class DataController
{
private SQLConnection Connection {get; set;
public void DataTable LoadDataFromDatabase()
{
...
}
...
}
Its better to use single connection string,declare your connection in web.config file and call it in aspx.cs