2015-02-02 3 views
0

나는 이라는 테이블을 가지고 있는데,이 필드는 4 필드 : DepId, DepName, DoctorId, PatientId으로 구성되어 있습니다. 콤보 박스를 채우는 동안 혼란

나는 다음과 같은 코드를 사용하여, 부서 이름과 콤보 컨트롤을 채우는 시도하고있다 :

public void ListDeps(ComboBox comboBox1) 
{ 
    DepartmantClass d; //I have created this class with the same fields in the Departmants table 
    try 
    { 
     con = Baglanti.Baglan(); 
     cmdStr = "Select * from Departmants"; 
     cmd = new SqlCommand(cmdStr, con); 
     if (con.State == ConnectionState.Closed) { con.Open();} 
     SqlDataReader reader = cmd.ExecuteReader(); 
     if (reader.HasRows) 
     { 
      d = new Bolumler(); 
      while (reader.Read()) 
      { 
       d.DepName = reader["DepName"].ToString(); 
       d.DoctorId = Convert.ToInt32(reader["DoctorId"].ToString()); 
       d.DepId= Convert.ToInt32(reader["DepId"].ToString()); 
       comboBox1.Items.Add(d); 
      } 
     } 
     reader.Close(); 
    } 
} 

private void frmMain_Load(object sender, EventArgs e) 
{ 
    DepartmantClass d= new DepartmantClass();    
    d.ListDeps(cmbDepNames); 
} 

모든 것이 괜찮습니다. 문제는 (나는) combobox 값을 제대로 전달할 수 없다는 것입니다. comboBox_SelectedIndexChanged 이벤트 처리기에서 다음 줄을 실행할 때 - 모든 값이 같습니다.

MessageBox.Show(comboBox1.SelectedItem.ToString()); 
+0

질문과 관련이 없지만 https://stackoverflow.com/questions/3639861/why-is-select-considered-harmful에서 주어진 이유로 인해 '선택 *'을 변경하는 것을 고려해야합니다. – mcy

답변

2

스왑이

d = new Bolumler(); 
    while (reader.Read()) 
    { 
... 

while (reader.Read()) 
     { 
    d = new Bolumler(); 
... 

에 그래서 당신은 각 반복에 Bolumler의 새 인스턴스를 만듭니다.

+0

정말 고마워요. ... – user3733078

관련 문제