当你选定一项进行其他操作时会重新绑定dropdownlist,这样会重新回到第一项,在page_load里加上判断if(!IsPostBack){‘这里是你需要绑定dropdownlist的代码‘}。
private void Page_Load(object sender, System.EventArgs e)
{
if (!IsPostBack)
{
bindtodropdownlist1();//第一种方法
bindtodropdownlist2();//第二种方法
}
}
//第一种方法
private void bindtodropdownlist1()
{
string connstring=”data source=SINOSOFT-SERVER;initial catalog=kmsdb;user id=mbm;password=mbm”;
string querystring=”select distinct cDepartmentname from t_Department”;
SqlConnection myconn=new SqlConnection(connstring);
myconn.Open();
SqlDataAdapter myadapter=new SqlDataAdapter(querystring,myconn);
DataSet ds=new DataSet();
myadapter.Fill(ds,”t_Department”);
myconn.Close();
DropDownList1.DataSource=ds.Tables[0].DefaultView;
DropDownList1.DataValueField=ds.Tables[“t_Department”].Columns”cDepartmentName”].ToString();
DropDownList1.DataBind();
}
//第二种方法
private void bindtodropdownlist2()
{
string connstring=”data source=SINOSOFT-SERVER;initial catalog=kmsdb;user id=kms;password=kms”;
string querystring=”select distinct cDepartmentname from t_Department”;
SqlConnection myconn=new SqlConnection(connstring);
myconn.Open();
SqlCommand myCommand = new SqlCommand(querystring,myconn);
SqlDataReader myReader;
myReader = myCommand.ExecuteReader();// Always call Read before accessing data.
while (myReader.Read())
{
DropDownList2.Items.Add(new ListItem(myReader.GetString(0),myReader.GetString(0)));
}
myReader.Close();
myconn.Close();
}
版权声明:本文为博主原创文章,未经博主允许不得转载。