我在c#的asp.net应用程序中有下拉列表。下拉列表的元素来自数据库(用户名)。我的下拉列表显示我选择的名称作为名字默认显示在我的数据库表中。即,当我打开页面时,我看到该名称已被选中。我想要的是,所选名称应该像" nworks User"。我通过使用代码尝试了它:
<asp:DropDownList ID="DropDownListSelectEmployee" runat="server" AutoPostBack="true"
OnSelectedIndexChanged="DropDownListSelectEmployee_SelectedIndexChanged"
OnTextChanged="DropDownListSelectEmployee_TextChanged" Height="30px" Width="250px">
<asp:ListItem Selected="True">nWorks Employee</asp:ListItem>
</asp:DropDownList>
但没用。我试过的下一个选项是:DropDownListSelectEmployee.Selecteditem.Text="nWorks User";
再次没有奏效。我使用代码从数据库中获取项目:
public void
DropDownListSelectEmployee_Fill()
{
if (!Page.IsPostBack)
{
DropDownListSelectEmployee.Items.Clear();
string q = "select username from nworksuser where _type='Employee';";
MySqlCommand cmd = new MySqlCommand(q, conn);
conn.Open();
string user = "";
MySqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
user = rdr.GetString("username");
DropDownListSelectEmployee.Items.Add(user);
}
conn.Close();
}
}
怎么可能?
答案 0 :(得分:0)
假设您不想选择名称,请使用:
使用DropDownListSelectEmployee.SelectedIndex = -1;
但是,如果您想在顶部添加一个命名框,只需将其添加为列表的第一项,并将其作为所选索引。
像这样:
DropDownListSelectEmployee.Items.Add("nWorks User");
while (rdr.Read())
{
user = rdr.GetString("username");
DropDownListSelectEmployee.Items.Add(user);
}
您需要在循环外添加第一个项目,然后默认情况下您将选择第一个项目。
答案 1 :(得分:0)
DropDownListSelectEmployee.DataSource = table;
DropDownListSelectEmployee.DataTextField = "Name";
DropDownListSelectEmployee.DataValueField = "Id";
DropDownListSelectEmployee.DataBind();
DropDownListSelectEmployee.Items.Insert(0, new ListItem("--nworks User--", "0"));
<asp:DropDownList runat="server" ID="DropDownListSelectEmployee"OnSelectedIndexChanged="DropDownListSelectEmployee_SelectedIndexChanged" AutoPostBack="true"
OnTextChanged="DropDownListSelectEmployee_TextChanged" Height="30px" Width="250px">
</asp:DropDownList>
背后的代码: protected void Page_Load(object sender,EventArgs e) { if(!Page.IsPostBack) { BindDropdwon(); } }
protected void DropDownListSelectEmployee_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void DropDownListSelectEmployee_TextChanged(object sender, EventArgs e)
{
}
private void BindDropdwon()
{
DataTable table = new DataTable();
table.Columns.Add("Id", typeof(int));
table.Columns.Add("Name", typeof(string));
// Here we add three DataRows.
table.Rows.Add(25, "Indocin");
table.Rows.Add(50, "Enebrel");
table.Rows.Add(10, "Hydralazine");
DropDownListSelectEmployee.DataSource = table;
DropDownListSelectEmployee.DataTextField = "Name";
DropDownListSelectEmployee.DataValueField = "Id";
DropDownListSelectEmployee.DataBind();
***DropDownListSelectEmployee.Items.Insert(0, new ListItem("--nworks User--", "0"));***
}
}