0
\$\begingroup\$

Can I create a method to do work with these five sections? I'm doing binding operations so many times. Do you have an idea on how to make this code prettier?

  • ddlModelValue -> ASP.NET DropDownList

var dtModel = Session[SystemConstant.ModelSessionKey] as DataTable;
ddlModelValue.DataSource = dtModel;
ddlModelValue.DataTextField = "Name";
ddlModelValue.DataValueField = "Name";
ddlModelValue.DataBind();

var dtGroup = Session[SystemConstant.GroupSessionKey] as DataTable;
ddlGroupValue.DataSource = dtGroup;
ddlGroupValue.DataTextField = "Name";
ddlGroupValue.DataValueField = "Name";
ddlGroupValue.DataBind();

var dtFit = Session[SystemConstant.FitSessionKey] as DataTable;
ddlFitValue.DataSource = dtFit;
ddlFitValue.DataTextField = "Name";
ddlFitValue.DataValueField = "Name";
ddlFitValue.DataBind();

var dtShellType = Session[SystemConstant.ShellTypeSessionKey] as DataTable;
ddlShellTypeValue.DataSource = dtShellType;
ddlShellTypeValue.DataTextField = "Name";
ddlShellTypeValue.DataValueField = "Name";
ddlShellTypeValue.DataBind();

var dtDataTypeCode = Session[SystemConstant.DataTypeCodeSessionKey] as DataTable;
ddlDataTypeCodeValue.DataSource = dtDataTypeCode;
ddlDataTypeCodeValue.DataTextField = "Name";
ddlDataTypeCodeValue.DataValueField = "Name";
ddlDataTypeCodeValue.DataBind();
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

This would be a start:

Sub bindTableToControl(table as DataTable, _
                       control, _
                       Optional textField As String = "Name", _
                       Optional valueField As String = "Name")

 control.DataSource = table;
 control.DataTextField = textField;
 control.DataValueField = valueField;
 control.DataBind();

End Sub

bindTableToControl( ddlModelValue , Session[SystemConstant.ModelSessionKey] );
bindTableToControl( ddlGroupValue, Session[SystemConstant.GroupSessionKey] );
bindTableToControl( ddlFitValue, Session[SystemConstant.FitSessionKey] );
bindTableToControl( ddlShellTypeValue, Session[SystemConstant.ShellTypeSessionKey] );
bindTableToControl( ddlDataTypeCodeValue, Session[SystemConstant.DataTypeCodeSessionKey] );

Basically I removed most of the repetition. I also removed all the Hungarian prefixes in the Sub.

As a side note, I wonder why SystemConstant is part of the Session, that does not seem memory efficient?

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.