How can I avoid this type of code, or is it common in Winforms?
When creating Winforms application using .NET 4, I constantly find myself writing this type of code:
public partial class StudentListerForm : UserControl
{
public StudentListerForm()
{
InitializeComponent();
LoadBranding();
}
private void StudentListerForm_Load(object sender, EventArgs e)
{
cmbGrade.DisplayMember = "Name";
cmbGrade.ValueMember = "GradeId";
cmbGradeInstance.DisplayMember = "Name";
cmbGradeInstance.ValueMember = "GradeParaleloId";
LoadExistingGrades();
}
private void LoadExistingGrades()
{
GradeRepos开发者_如何转开发itory repo = new GradeRepository();
cmbGrade.DataSource = repo.FindAllGrades();
}
That's just an excerpt. The point is, how can I more cleanly display data retrieved from a database? I find myself changing something in the schema and having to go one by one column checking if the name is correct.
Or am I being just paranoid.
It's a question of mapping really. If you have the database column name mapped through to each control then yes, if you change that coloumn name you will need to update the code to reflect that change. This isn't the best approach as it means your front end code is mapped directly onto your database unless you're using MVC. I'd recommend you look at two things.
Firstly, why are you changing names of database columns in the first place? Has the column changed in purpose? Should it be a new column entirely?
Secondly, can you use stored procedures, views or some sort of dataset mapping in between the database and the front end? That way, if the database column does change name, you only need to change it in the stored procedure/view/dataset and your front end wouldn't be coupled to the old name.
精彩评论