Refer a good article on CP which demonstrate how to insert and read data from a SQL Server:
Beginners guide to accessing SQL Server through C#[
^]
A
class is a construct that
enables you to create your own custom types by grouping together variables of other types, methods and events.
It defines the data and behavior of a type.
Refer more details on following MSDN article:
Classes (C# Programming Guide)[
^]
This is how you can create a
class file
and define
connection string
which can be accessed in you solution all over by creating object of this class file.
public class DBConnection
{
public static string cnnStr;
public SqlConnection cnTransact;
public string GetConnectionString
{
get
{
return "ConnectionString";
}
}
public DBConnection()
{
cnTransact = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
}
}
Web.config file:
<connectionstrings>
<add name="ConnectionString" connectionstring="Server=SQLExpress;uid=abc;pwd=123;database=DBName" providername="System.Data.SqlClient" />
</connectionstrings>
Creating object of class file:
DBConnection DB = new DBConnection();
By this DB object you can access all the methods and properties in that class file in you solution.
(Note that, DBConnection is class file name)
To open connection:
DB.cnTransact.Open();
To close connection:
DB.cnTransact.Close();
Refer more about classes:
C# Class[
^]
Creating a Simple Class in C#[
^]
Creating a Class Factory with C# and .NET[
^]