我是一名初學者,編寫代碼使用Asp.Net和c#在Gridview中顯示數據。我想知道我遵循的方法是否正確。我希望提出有關標準和架構問題的建議,以及我的代碼的最佳實踐,以便我可以相應地修改我的代碼。我感謝你的偉大建議和代碼增補。最佳做法代碼和問題
連接代碼:
public class DemoProjConnectionClass
{
public SqlConnection DemoProjConnection()
{
SqlConnection con = new SqlConnection("Data Source=Localhost;Initial Catalog=master;Integrated Security=True");
return con;
}
}
域代碼(得到&套):
public class DemoProjDomainClass
{
public int EmpId { get; set; }
public string EmpName { get; set; }
public int Salary { get; set; }
}
類庫代碼:
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代碼
protected void Page_Load(object sender, EventArgs e)
{
DemoProjServiceClass ob=new DemoProjServiceClass();
GridView1.DataSource = ob.getDemoProjList();
GridView1.DataBind();
}
請告訴我爲什麼選擇投票? – Shyju 2012-03-27 03:43:47
優秀的評論。我注意到他們。萬分感謝。 – Kurkula 2012-03-27 04:48:00
在類庫代碼中,數據集是最佳選擇使用,然後將其循環列表? – Kurkula 2012-03-27 04:51:04