我是一名初学者,正在使用 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;
}
}
界面代码
protected void Page_Load(object sender, EventArgs e)
{
DemoProjServiceClass ob=new DemoProjServiceClass();
GridView1.DataSource = ob.getDemoProjList();
GridView1.DataBind();
}
最佳答案
我建议你:
- 使用 MVC 代替 asp.net classic
- 改用 linq 或 EntityFramework(cmd、conn、适配器、数据集)
- 使用中继器代替网格以获得更好的性能
看看这个tutorial在 asp.net 网站上
关于c# - 最佳实践代码和问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9883035/