2013-06-06 10 views
1

UserControl을 :동적 UserControl을 클릭 이벤트

private string lastName; 
public string LastName 
{ 
get { return lastName; } 
set 
{ 
    lastName = value; 
    lastNameTextBox.Text = value; 
} 
} 

양식 :

using (SqlConnection myDatabaseConnection = new SqlConnection(myConnectionString.ConnectionString)) 
     { 
      myDatabaseConnection.Open(); 
      using (SqlCommand SqlCommand = new SqlCommand("Select LasatName from Employee", myDatabaseConnection)) 
      { 
       int i = 0; 
       SqlDataReader DR1 = SqlCommand.ExecuteReader(); 
       while (DR1.Read()) 
       { 
        i++; 
        UserControl2 usercontrol = new UserControl2(); 
        usercontrol.Tag = i; 
        usercontrol.LastName = (string)DR1["LastName"]; 
        usercontrol.Click += new EventHandler(usercontrol_Click); 
        flowLayoutPanel1.Controls.Add(usercontrol); 
       } 
      } 
     } 

양식은 데이터베이스에서 레코드를로드하고 동적으로 생성 된 각각의 UserControls '텍스트 상자에 각각의 성을 표시합니다. 동적 UserControl을 클릭 때 어떻게 폼의 텍스트 상자에 같은 주소로위한 추가적인 정보를 표시합니다?

시도 : 사용자 정의 컨트롤 UserControl2를 내부

private void usercontrol_Click(object sender, EventArgs e) 
    { 
     using (SqlConnection myDatabaseConnection = new SqlConnection(myConnectionString.ConnectionString)) 
     { 
      myDatabaseConnection.Open(); 
      using (SqlCommand mySqlCommand = new SqlCommand("Select Address from Employee where LastName = @LastName ", myDatabaseConnection)) 

      { 
       UserControl2 usercontrol = new UserControl2(); 
       mySqlCommand.Parameters.AddWithValue("@LastName", usercontrol.LastName; 
       SqlDataReader sqlreader = mySqlCommand.ExecuteReader(); 

       if (sqlreader.Read()) 
       { 
        textBox1.Text = (string)sqlreader["Address"]; 
       } 

      } 
     } 
    } 
+0

그리고 시도가 왜 작동하지 않았다? 근처 충분한 정보조차 당신이 뭘하려는 건지의 생각이 여기에 우리가 아니다 -. ** 더 많은 코드가 해답이 될 것되지 않습니다 ** 당신이 무슨 일을하는지, 당신이 원하는 것을 설명 , 그리고 작동하지 않는 것. –

+0

@Michael - http://stackoverflow.com/questions/16894918/display-a-number-of-usercontrol-based-on-the-number-of-records-in-the-database?noredirect=1#comment24378920_16894918 –

답변

1

첫째. 첫 번째 코드 조각에서 "Select ID from ..."를 실행하지만 리더에서 "성"필드를 찾으십시오. 작동하지 않을 것입니다.

두 번째. 당신은 당신이 Employee 테이블에서 더 많은 정보가 필요합니다 것을 알고 있다면, 난 당신이 LastName을 어디다 같은 UserControl에 저장하는 것이 좋습니다. 실행, "...에서 * 선택"UserControl2에 다른 필드와 속성을 추가하고 Read 루프에 할당 :

usercontrol.Address = (string)DR1["Address"]; 

셋째. 두 번째 코드 조각에서 사용

UserControl2 usercontrol = (UserControl2)sender; 

대신

UserControl2 usercontrol = new UserControl2(); 

새로 만든 사용자 컨트롤이 할당 된 LastName이 없기 때문에

.

다음 :

private void usercontrol_Click(object sender, EventArgs e) 
{ 
    UserControl2 usercontrol = (UserControl2)sender; 
    textBox1.Text = usercontrol.Address; 
} 
+0

...고맙습니다 :) –

0

(생성자 또는 의 InitializeComponent 방법) 당신이 잠재적 인 청취자에게 클릭 이벤트를 전달합니다. 그런

뭔가 :

public UserControl2() 
{ 
    ... 
    this.lastNameTextBox.Click += (s, a) => OnClick(a); 
    ... 
} 
관련 문제