将数据库值检索到没有重复值的数据绑定Dropdownlist的ASP.NET中
本文关键字:数据绑定 Dropdownlist NET ASP 检索 数据库 | 更新日期: 2023-09-27 18:26:05
每当用户单击"更新配置文件"按钮时,他将被引导到页面,在中,他在注册期间保存的所有信息都将显示在文本框中,并在页面加载后下拉列表。(下载列表是数据绑定的)
使用下面的代码,我可以做到这一点,但是,当我更改DDLDepartment(第一个下拉列表)中的值时,DDLGroup(第二个下拉列表
DDL部门和DDL组是相互关联的,因为DDL组根据在DDL部门中选择的值进行过滤
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack) // important
{
DataTable dt = new DataTable();
con.Open();
SqlDataReader myReader = null;
string cmdstr = "SELECT * from USERSONLINE where Username = '" + Session["Username"] + "'";
SqlCommand userExist = new SqlCommand(cmdstr, con);
myReader = userExist.ExecuteReader();
while (myReader.Read())
{
txtEmpID.Text = (myReader["EmpId"].ToString());
txtFirstName.Text = (myReader["FirstName"].ToString());
txtLastName.Text = (myReader["LastName"].ToString());
txtUsername.Text = (myReader["Username"].ToString());
ddlDepartment.SelectedItem.Text = (myReader["Department"].ToString());
ddlGroup.SelectedItem.Text = (myReader["GroupName"].ToString());
}
con.Close();
}
}
html标记
<asp:DropDownList ID="ddlDepartment" AutoPostBack="True" runat="server" AppendDataBoundItems="True" BackColor="#F3F3F3" ForeColor="#838383"
Height="25px" style="text-align: left" Width="135px" DataSourceID="SqlDataSourceDepartment" DataTextField="DepartmentName" DataValueField="DepartmentID" OnDataBound="ddlDepartment_DataBound" >
<asp:ListItem Value="0">Select Department</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="ddlGroup" runat="server" BackColor="#F3F3F3" ForeColor="#838383" Height="25px" style="text-align: left; margin-bottom: 0px;" Width="145px" DataSourceID="SqlDataSourceGroup" DataTextField="GroupName" DataValueField="GroupID" AutoPostBack="true" OnDataBound="ddlGroup_DataBound" AppendDataBoundItems="true" >
<asp:ListItem>Select Group</asp:ListItem>
选择部门和集团时,使用以下
ddlDepartment.Items.FindByValue((myReader["Department"].ToString())).Selected = true;
ddlGroup.Items.FindByValue((myReader["GroupName"].ToString())).Selected = true;