我有一个dropdownlist
邮政编码。
这是一个非常大的列表,从数据库加载需要很长时间。因此,首先我正在寻找最佳解决方案,以便在首次加载网站时尝试缓存或保存这些数据,以便我可以在需要时使用它。我尝试了一个列表和字典,然后datasource
在后面设置了代码,但它不允许我设置选定的值。
它一直告诉我它不能绑定到没有 no 的控件datasource
。让事情变得更加困难的dropdownlist
是里面的一个formview
。
我只是不确定解决这个问题的最佳方法。我datasource
在 created 方法中设置 and 值,formview
但我选择的值来自formview
datasource
.
private Dictionary<int, string> CreateZipcodeList()
{
string connStr = ConfigurationManager.ConnectionStrings["KlamathAlgaeEntityDevConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(connStr);
Dictionary<int,string> ziplist = new Dictionary<int,string>();
//Create CoreEntity Record
SqlCommand cmd1 = new SqlCommand(@"select zipcode.ZipCodeId, zipcode.zip + ', ' + city.name + ', ' + ISNULL(GeographicState.name,'') + ', ' + Country.name as zipstring
from zipcode left outer join City on ZipCode.CityId = city.CityId
left outer join GeographicState on ZipCode.GeographicStateId = GeographicState.GeographicStateId
left outer join Country on ZipCode.CountryId = Country.CountryId
order by country.name, GeographicState.name, city.name",
conn);
try
{
conn.Open();
SqlDataReader reader = cmd1.ExecuteReader(CommandBehavior.CloseConnection);
while (reader.Read())
{
if (!reader.IsDBNull(0))
{
ziplist.Add(reader.GetInt32(0), reader["zipstring"].ToString());
}
}
}
finally
{
if (conn != null)
{
conn.Close();
}
}
return ziplist;
}
protected void AddressForm_ItemCreated(Object sender, EventArgs e)
{
((DropDownList)AddressForm.FindControl("Zipcodeddl")).DataSource = CreateZipcodeList();
((DropDownList)AddressForm.FindControl("Zipcodeddl")).DataTextField = "Value";
((DropDownList)AddressForm.FindControl("Zipcodeddl")).DataValueField = "Key";
((DropDownList)AddressForm.FindControl("Zipcodeddl")).DataBind();
//((DropDownList)AddressForm.FindControl("Zipcodeddl")).SelectedValue = Eval("zipcodeid").ToString();
}
这可以很好地填充下拉列表,但是当我尝试设置所选值时,它说控件不是数据绑定的。这也不会将字典存储在任何地方,因此我需要在需要时调用该函数来加载字典。