I don’t know how to write the persistence layer yet, so I just use this method and add stored procedures. I feel more comfortable. I hope you can give me some advice.
public class clsdb
{
public clsdb()
{
//
// TODO: add constructor logic here
//
}
//Database connection
public static SqlConnection getcn()
{
return (new SqlConnection("server=.;database=web;uid=sa;pwd=123"));
}
//GridView binding method
public static void DataBindGridViewAsTable(GridView Grid,String strsql)
{
SqlConnection cn = clsdb.getcn();
cn.Open();
SqlDataAdapter da = new SqlDataAdapter(strsql,cn);
DataTable td = new DataTable();
da.Fill(td);
Grid.DataSource = td;
Grid.DataBind();
cn.Close();
cn.Dispose();
}
//Methods to add, delete, and update records
public static void AddDelUpDataBase(String strsql)
{
SqlConnection cn = clsdb.getcn();
cn.Open();
SqlCommand cmd = new SqlCommand(strsql,cn);
cmd.ExecuteNonQuery();
cn.Close();
cn.Dispose();
}
//Method to return a record
public static int select(String strsql)
{
int i = -1;
SqlConnection cn = clsdb.getcn();
cn.Open();
SqlCommand cmd = new SqlCommand(strsql, cn);
i=(int)cmd.ExecuteScalar();
cn.Close();
cn.Dispose();
return i;
}
//Return the recordset of SqlDataReader
public static SqlDataReader SelectDataBase(String strsql)
{
SqlConnection cn = clsdb.getcn();
cn.Open();
SqlCommand cmd = new SqlCommand(strsql,cn);
cmd.CommandType = CommandType.Text;
SqlDataReader rd = cmd.ExecuteReader(CommandBehavior.CloseConnection);
return rd;
}
//Method to bind DropDownList
public static void DataBindDropDownList(DropDownList drp,string strsql)
{
SqlConnection cn = getcn();
cn.Open();
SqlDataAdapter da = new SqlDataAdapter(strsql,cn);
DataTable td = new DataTable();
da.Fill(td);
drp.DataSource = td;
drp.DataBind();
cn.Close();
cn.Dispose();
}
//Method to bind DataList
public static void DataBindDataList(DataList list, string strsql)
{
SqlConnection cn = getcn();
cn.Open();
SqlDataAdapter da = new SqlDataAdapter(strsql, cn);
DataTable td = new DataTable();
da.Fill(td);
list.DataSource = td;
list.DataBind();
cn.Close();
cn.Dispose();
}
}