在用户控件的下拉列表中设置选定的索引 [英] Set selected index in a Dropdownlist in usercontrol
问题描述
我对用户控件还很陌生.到目前为止,我发现它们对于处理大量重复的用户输入字段非常有用.但是,我在预填充控件中的下拉列表时遇到了问题.我将一个ddl添加到我的ascx页面,然后绑定该ddl并将其公开:
I'm fairly new to usercontrols. So far, I've found them quite useful for handling large amounts of repeating user input fields. However, I'm having a problem with prepopulating a dropdownlist in the control. I add a ddl to my ascx page then I bind the ddl and expose it:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<Travel_CarSize> tc = Travel_CarSizes.GetCarSizes();
ddlCarSize.DataSource = tc;
ddlCarSize.DataTextField = "CarSize";
ddlCarSize.DataValueField = "CarSizeID";
ddlCarSize.DataBind();
}
}
public string CarSize
{
get { return ddlCarSize.SelectedValue.ToString(); }
set { ddlCarSize.SelectedIndex = ddlCarSize.Items.IndexOf(ddlCarSize.Items.FindByValue(value)); }
}
但是,当我以编程方式尝试在控件中设置ddl的选择时,我总是最终将其设置为THEN并将其绑定.在我的aspx.cs文件中设置:
However, when I programatically try to set a selection for the ddl in the control I always end up setting it THEN binding it. In my aspx.cs file I set:
CarControl1.CarSize = "3";
该程序旨在显示一个空的用户控件(带有数据绑定的ddl)和一个gridview.用户选择一个gridview条目,并且该用户控件被数据填充.因此,ddl从一开始就受到约束,然后发生了导致预选" ddl的事件.
The program is designed to display an empty usercontrol (with a databound ddl) and a gridview. The user selects a gridview entry and that usercontrol gets filled with the data. So the ddl gets bound from the start then the events happen that lead to the "pre-selected" ddl.
当这没有给我结果时,我在if(!IsPostBack),ddlCarSize.DataBind();上设置了一个断点.和集合{}.我运行该程序,它将绑定我的ddl,然后在gridview中进行选择.当我单击选择时,我发现它在用户控件中击中了if(!IsPostBack)并说:哦,这是一个回发,请不要输入if."然后它命中了set {},但ddl现在为空.然后它再次击中了if(!IsPostBack),由于某种原因,现在它说它不是回发并重新绑定了ddl.
When this didn't give me the result I was looking for I put a breakpoint on the if(!IsPostBack), the ddlCarSize.DataBind(); and the set{}. I run the program, it binds my ddl and I make a selection in the gridview. When I click the select I found that it hits the if(!IsPostBack) in the usercontrol and says "Oh, this is a postback, don't go in the if." then it hits the set{} but the ddl is empty now. Then it hits the if(!IsPostBack) again and for some reason now says it's not a postback and rebinds the ddl.
我认为这是一个非常普遍的问题,但我尚未找到解决方案.任何帮助将不胜感激.
I figure this is a pretty common problem but I've yet to find a solution. Any help would be greatly appreciated.
推荐答案
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Bind()
}
}
public Bind()
{
if (ddlCarSize.Items.Count == 0)
{
List<Travel_CarSize> tc = Travel_CarSizes.GetCarSizes();
ddlCarSize.DataSource = tc;
ddlCarSize.DataTextField = "CarSize";
ddlCarSize.DataValueField = "CarSizeID";
ddlCarSize.DataBind();
}
}
public string CarSize
{
get { return ddlCarSize.SelectedValue.ToString(); }
set
{
Bind();
ddlCarSize.SelectedIndex = ddlCarSize.Items.IndexOf(ddlCarSize.Items.FindByValue(value)); }
}
这篇关于在用户控件的下拉列表中设置选定的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!