I am a beginner and writing code to display data in a Gridview using Asp.Net and c#. I want to know if the approach I followed is correct or not. I want suggestions on standards and architectural issues, best practices with my code so that I can modify my code accordingly. I appreciate your great suggestions and code additions.
Connection Code:
public class DemoProjConnectionClass
{
public SqlConnection DemoProjConnection()
{
SqlConnection con = new SqlConnection("Data Source=Localhost;Initial Catalog=master;Integrated Security=True");
return con;
}
}
Domain Code(gets & sets):
public class DemoProjDomainClass
{
public int EmpId { get; set; }
public string EmpName { get; set; }
public int Salary { get; set; }
}
Class Library Code:
public class DemoProjServiceClass
{
public IList<DemoProjDomainClass> getDemoProjList()
{
string sqlDemoProjList;
sqlDemoProjList = "SELECT EmpId,EmpName,Salary from Employee";
DemoProjConnectionClass x = new DemoProjConnectionClass();
SqlConnection con = x.DemoProjConnection();
con.Open();
SqlCommand cmd = new SqlCommand(sqlDemoProjList, con);
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "tempTable1");
IList<DemoProjDomainClass> DemoProjList = new List<DemoProjDomainClass>();
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
DemoProjDomainClass _obj = new DemoProjDomainClass();
_obj.EmpId = Convert.ToInt16(ds.Tables[0].Rows[i][0]);_obj.EmpName = ds.Tables[0].Rows[i][1].ToString();_obj.Salary = Convert.ToInt16(ds.Tables[0].Rows[i][2]);DemoProjList.Add(_obj);
}
return DemoProjList;
}
}
UI Code
protected void Page_Load(object sender, EventArgs e)
{
DemoProjServiceClass ob=new DemoProjServiceClass();
GridView1.DataSource = ob.getDemoProjList();
GridView1.DataBind();
}
Connection Code:
I will not hardcode the connectionstring like that. I will keep that in a config file (web.config or so..) and read from there so that i can change my connection string any time if needed with a recompilation.
Class Library Code
Your getDemoProjList method dont have any exception handling. I will wrap that code with using statement so that i dont need to worry abour closing my connection
UI
I dont think you should load data in the PageLoad without checking whether it is a postback or not. So will use a isPostBAck property checkk. I would also do a null check before binding it as the data source of the grid.