用户控件数据绑定 - ASP.NET

时间:2011-04-13 05:49:51

标签: asp.net user-controls webforms

我开发“地址”用户控件。它包含2个dropDowns(国家和城市)和2个textBoxes(街道和建筑物)。第二个dropDown(Cities)取决于第一个dropDown选择的Country。

<div>Country</div>
   <div> <asp:DropDownList runat="server" ID="ddlCountry" DataTextField="Name" 
           DataValueField="Id" DataSource="<%#Facade.Addresses.GetCountries() %>" 
           AutoPostBack="true"   onselectedindexchanged="ddlCountry_SelectedIndexChanged" /></div>
</div>


<div>
<div>City</div>
<div>
  <asp:DropDownList runat="server" ID="ddlCity" DataTextField="Name" 
        DataValueField="Name"  />
</div>
</div>


<div>
<div>Street</div>
    <div><uc:TextBox ID="txtStreet" Text="<%#Address.Street %>" runat="server"/></div>
</div>


<div>
<div>House</div>
    <div> <uc:TextBox ID="txtHouse" Text="<%#Address.House%>" runat="server"/></div>
</div>



 public partial class AddressControl : UserControl
    {


        protected void Page_Init(object sender, EventArgs e)
        {
           ddlCountry.DataBind();
           BindCity(int.Parse(ddlCountry.SelectedValue));

        }


 public BEAddress Address
        {
            get
            {
                return new BEAddress
                {
                    Country = ddlCountry.SelectedItem.Text,
                    City = ddlCity.SelectedItem.Text,
                    Street = txtStreet.Text,
                    House= txtHouse.Text
                };


            }
            set
            {


                BindCity(int.Parse(ddlCountry.Items.FindByText(value.Country).Value));

                var a = ddlCity.Items.FindByText(value.Country);
                if (a !=null)
                     a.Selected = true;



                txtStreet.Text = value.Street;
                txtHouse.Text = value.House;
            }

        }

        protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e) {
            BindCity(int.Parse(ddlCountry.SelectedValue));
        }



        private void BindCity(int countryId) {

            ddlCity.DataSource = Facade.Addresses.GetCities(countryId);
            ddlCity.DataBind();
        }
}

使用

ucAddress.Address = StoreDataSource.Address;

当我使用 setter ucAddress.Address = StoreDataSource.Address)时,dropDown“Cities”不包含正确的值。

如何更改代码以强制该控件正常工作?

0 个答案:

没有答案