![](/img/trans.png)
[英]How to populate a textbox based on the selected value of a dropdown list in an asp.net c# web forms application?
[英]How to bind the 'SelectedValue' in dropdown in ASP.NET Web Forms C# application from code behind?
我试图在FormView的EditItemTemplate中使用下拉列表。 我正在从数据表填充下拉列表。 下拉列表按预期方式填充,但是当我尝试保存更改时,下拉字段为null。 在FormView中进行更改时,如何保存所选值?
通常,我只是将SelectedValue ='<%#Bind(“ Surname”)%>'放在下拉标记中,但是显然不能,因为我将其填充在后面的代码中。
这是下拉标记:
<asp:DropDownList runat="server" ID="SurnameDdl" AppendDataBoundItems="True" ></asp:DropDownList>
这是我用来填充下拉列表的数据表代码:
private DataTable GetAdUsers()
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[6]
{
new DataColumn("givenName", typeof (string)),
new DataColumn("sn", typeof (string)),
new DataColumn("mail", typeof (string)),
new DataColumn("department", typeof (string)),
new DataColumn("manager", typeof (string)),
new DataColumn("DisplayField", System.Type.GetType("System.String"), "sn + ' ,' + givenName + ' ' + mail")
});
using (var context = new PrincipalContext(ContextType.Domain, null))
{
using (var group = (GroupPrincipal.FindByIdentity(context, "TWIA Underwriting"))) //Options include Users, Everybody, Agent Services, UnderwritingAdmin
{
var users = group.GetMembers(true);
foreach (UserPrincipal user in users)
{
DirectoryEntry de = user.GetUnderlyingObject() as DirectoryEntry;
dt.Rows.Add
(
Convert.ToString(de.Properties["givenName"].Value),
Convert.ToString(de.Properties["sn"].Value),
Convert.ToString(de.Properties["mail"].Value),
Convert.ToString(de.Properties["department"].Value),
Regex.Replace((Convert.ToString(de.Properties["manager"].Value)), @"CN=([^,]*),.*$", "$1"),
de.Properties["DisplayField"].Value
);
}
}
}
return dt;
}
这是FormView的OnDataBound事件:
protected void fvPhaudDets_OnDataBound(object sender, EventArgs e)
{
if (fvPhaudDets.CurrentMode == FormViewMode.Edit)
{
DropDownList ddl = null;
ddl = (DropDownList)fvPhaudDets.FindControl("SurnameDdl");
ddl.DataSource = GetAdUsers();
ddl.DataTextField = "DisplayField";
ddl.DataValueField = "sn";
ddl.DataBind();
ddl.SelectedValue = "Surname";
}
}
我还需要在下拉菜单中添加事件和代码吗? 如果是这样,需要什么?
您可以在FormView上使用FindControl
来找到DropDownList。 它也可以在编辑模式下使用。 如果您有这样的FormView
<asp:FormView ID="FormView1" runat="server">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem>Aa</asp:ListItem>
<asp:ListItem>Bb</asp:ListItem>
<asp:ListItem>Cc</asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
</asp:FormView>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
然后将数据绑定到它并设置测试的编辑模式
if (IsPostBack == false)
{
FormView1.DataSource = new string[1];
FormView1.ChangeMode(FormViewMode.Edit);
FormView1.DataBind();
}
您现在可以在按钮单击上获取值
protected void Button1_Click(object sender, EventArgs e)
{
DropDownList ddl = FormView1.FindControl("DropDownList1") as DropDownList;
Label1.Text = ddl.SelectedValue;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.