Just wanted to add something to what they've suggested. Here are a few points that you want to consider:
(1) When binding a
Data Control
manually at Page_Load event, make sure that you wrap your code for binding within
!IsPostback
block to avoid unexpected results.
(2) Make it a habit to put
objects
that eat resources such as
SqlConnection
,
SqlCommand
and
SqlDataAdapter
within a
using statement
to ensure that objects will be properly disposed and closed after they are used.
protected void Page_Load(object sender, EventArgs e){
if(!IsPostback){
BindList();
}
}
private void BindList(){
String strConnString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
using(SqlConnection con = new SqlConnection(strConnString)){
using(SqlCommand cmd = new SqlCommand("select * from Expense_Type", con)){
con.Open();
DropDownListexpensetype.DataSource = cmd.ExecuteReader();
DropDownListexpensetype.DataTextField = "Expense_Type";
DropDownListexpensetype.DataValueField = "Expense_Type";
DropDownListexpensetype.DataBind();
}
}
}
Note: I've noticed that you've assigned the field
Expense_Type
for both
Text
and
Value
. Just make sure that the
DataValueField
contain unique values to avoid unexpected behavior when selecting/pre-selecting values from the list.