我有一个 DropDownList,它数据绑定到一个表,该表有一个简单的描述性文本列和一个 ImageUrls 列。当用户单击从 DropDownList 中选择时,会将图像添加到 div。我将 DropDownList 的 AutoPostBack 属性设置为 true,以便用户可以与页面进行更好的交互。起初我认为一切都很好,然后在测试时我发现如果用户从下拉列表中添加一些内容,然后返回到列表项中的默认文本(“选择要添加的图片”),无论添加到 div会消失。如果用户随后选择要添加的不同图片,则将新图片与已消失的前一张图片一起添加。有人可以帮我弄清楚这是为什么吗?
public partial class Webform1 : System.Web.UI.Page
{
string imageListKey = "imageListKey";
//List of images inside the div will be stored in Viewstate to they aren't lost
//during postback
List<string> ImagePaths
{
get
{
if (ViewState[imageListKey] == null)
ViewState[imageListKey] = new List<string>();
return (List<string>)ViewState[imageListKey];
}
}
protected void Page_Load(object sender, EventArgs e)
{
//don't hit the database every time there's a postback
string cs = ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString;
if(!IsPostBack)
{
using (SqlConnection con = new SqlConnection(cs))
{
using (SqlCommand cmd = new SqlCommand("select * from CardPictures", con))
{
con.Open();
cmd.CommandType = CommandType.Text;
DropDownList2.AutoPostBack = true;
DropDownList2.DataTextField = "SideAffectName";
DropDownList2.DataValueField = "ImagePath";
DropDownList2.DataSource = cmd.ExecuteReader();
DropDownList2.DataBind();
DropDownList2.Items.Insert(0, new ListItem("Select picture to add", "-1"));
}
}
}
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
//don't allow duplicate values in ImagePaths
if (!ImagePaths.Contains(DropDownList2.SelectedItem.Value))
{
if (DropDownList2.SelectedItem.Value != "-1")
{
ImagePaths.Add(DropDownList2.SelectedItem.Value);
//foreach Image selected, add to testDiv
foreach (string s in ImagePaths)
{
testDiv.Controls.Add(AddImage(s));
}
}
}
}
//to test that things are being added to the ViewState variable correctly
protected void Button1_Click(object sender, EventArgs e)
{
foreach (string s in ImagePaths)
{
Response.Write(s + "<br/>");
}
}
//adds an Image and setes the imageUrl to whatever is in the ViewState ImagePaths
private Image AddImage(string imageUrl)
{
Image i = new Image();
i.Height = 75;
i.Width = 75;
i.ImageUrl = imageUrl;
return i;
}
}