2014-12-01 3 views
0

버튼 클릭만으로 실행되는 메소드가 있습니다.C# ClickEvent - 이전 처리기 덮어 쓰기

  • 이 메서드는 데이터베이스로 이동하여 과 일치하는 모든 제품 ID (목록)를 반환합니다.
  • 그런 다음 해당 ID를 사용하여 데이터베이스에서 해당 이미지를 가져 와서이를 picturebox에 추가합니다.

문제는 각 그림 상자에 클릭 evethandler를 추가하는 것입니다. 검색 버튼을 두 번째로 클릭하면 해당 picturebox에 등록 된 두 개의 이벤트 핸들러가 있습니다. 그래서 picurebox를 클릭 할 때 search 버튼을 두 번 누르면 두 개의 메시지 상자가 나옵니다.

이전의 이벤트 처리기를 삭제하고 유지하는 방법이 있습니까?

private void btnSearch_Click(object sender, EventArgs e) 
    { 
     ClearPicBoxs(); 

     if((!txtBoxSearch.Text.Equals("Search...") || !txtBoxSearch.Text.Equals("")) && isLoggedIn) 
     { 
      //Get Product ids from database which have supplied keyword 
      DAOKeyword.SelectKeywords(txtBoxSearch.Text, productIdsList); 

      int cnt = 0; 

      foreach (int productId in productIdsList) 
      { 
       ImageDAOImpl DAOIamge = new ImageDAOImpl(); 

       picPrd = pictureBoxList[cnt]; 
       picPrd.Text = productId.ToString(); 
       picPrd.Click += new System.EventHandler((sender1, e1) => picPrd_Click(sender, e, productId)); 

       picPrd.Image = ByteArrayToImagebyMemoryStream(DAOIamge.SelectImage(productId)); 
       picPrd.SizeMode = PictureBoxSizeMode.StretchImage; 
       picPrd.Refresh(); 
       cnt++; 
      } 
      lblLatest_Search.Text = "''" + txtBoxSearch.Text + "''"; 
      productIdsList.Clear(); 
     } 
     else 
     { 
      //Select Latest Posted Products 
     } 
    } 



private void picPrd_Click(object sender, EventArgs e, int productId) 
     { 
      //Use productId to get info about product 
      MessageBox.Show(productId.ToString()); 
     } 
+0

왜 이벤트 핸들러를 다시 추가 하시겠습니까? 한 번 해봐. – Maarten

+0

EventHandler를 한 번만 추가하십시오 (예 : ctor) – nozzleman

답변

0

나는 목록 pictureBoxList이 채워집니다 위치를 잘 모르겠습니다, 왜 당신은 당신이 수동으로 제어 속성을 설정대로 컨트롤에 해당 항목을 할당해야합니다. 당신이 컨트롤을 이벤트 처리기를 할당하기 전에 때마다 다시 인스턴스화 경우

, 그것은 한 번만 나의 제안은 아래 라인과 아래 라인을

picPrd = pictureBoxList[cnt]; 

를 대체하는 것입니다 해고해야

picPrd = new PictureBox();