간단한 설명 텍스트 열과 ImageUrl에 대한 열이있는 테이블에 데이터 바인딩되는 DropDownList가 있습니다. 사용자가 DropDownList에서 선택을 클릭하면 이미지가 div에 추가됩니다. 나는 DropDownList의 AutoPostBack 속성을 true로 설정하여 사용자가 페이지와 더 잘 상호 작용할 수 있도록했습니다. 처음에 나는 괜찮 았다고 생각했다. 그런 다음 사용자가 드롭 다운에서 항목을 추가하면 div에 추가 된 항목 ("추가 할 사진 선택")의 기본 텍스트로 돌아갑니다. 사라질 것입니다. 그런 다음 사용자가 추가 할 다른 그림을 선택하면 새 그림이 사라진 이전 그림과 함께 추가됩니다. 누군가가 내가 왜 그런지 알아낼 수 있습니까?div에서 컨트롤을 제거하는 DropDownList의 기본값
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;
}
}
, 그것은 이동해야합니다 :이 (! DropDownList2.SelectedItem.Value = "-1")에 코드를이해야하는 경우의 내부 foreach 문이다 선택 이벤트가 발생했습니다. – fnostro
@ 카를 감사합니다. – wootscootinboogie