Set selected index in a Dropdownlist in usercontro

2019-09-11 18:08发布

问题:

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)); }
}

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";

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.

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.

回答1:

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)); }
}