2013-07-04 4 views
3

저는 C# 형식으로 콤보 박스를 가지고 있습니다. 나는 그것을 내가 Combobox.SelectedText를 사용 Combobox.SelectedValue 및 항목의 텍스트 (데이터베이스에서 온 NAME)를 사용하여 항목의 값 (데이터베이스에서 온 ID)를 얻을 수인덱스에서 콤보 박스의 가치를 얻는 방법은 무엇입니까?

string selectSql = "SELECT ID, NAME FROM MUSTERI"; 

SqlCommand comm = new SqlCommand(selectSql, conn); 
SqlDataReader dr = comm.ExecuteReader(); 
DataTable dt = new DataTable(); 

dt.Columns.Add("ID", typeof(string)); 
dt.Columns.Add("NAME", typeof(string)); 
dt.Load(dr); 

combobox.ValueMember = "ID"; 
combobox.DisplayMember = "AD"; 
combobox.DataSource = dt; 

같은 데이터 소스를 제공,하지만 난 K의 값을 얻을 필요가있다. 항목 (exapmle : 4 번째 항목의 값). 어떻게해야합니까?

답변

4

Items 속성을 사용할 수 있습니다.

DataRowView itemAtFourthIndex = combobox.Items[4] as DataRowView; 

int id = -1; 
if(itemAtFourthIndex != null) 
    id = Convert.ToInt32(itemAtFourthIndex.Row["ID"]); 
+0

약 2 시간을 찾고 있습니다 ... 고맙습니다 –

+0

당신은 오신 것을 환영합니다. :) – keyboardP

1

내부적으로 ComboBox는 리플렉션을 사용하여 항목의 텍스트를 가져옵니다. 다음과 같은

Private Function GetText(cb As ComboBox, i As Integer) As String 
    Dim src = cb.Items(i) 
    Dim txt As String 
    Try 
     txt = src.GetType.GetProperty(cb.DisplayMember).GetValue(src) 
    Catch ex As Exception 
     txt = ex.Message 
    End Try 
    Return txt 
End Function 
0

당신이 시도 할 수 있습니다 : 당신이 데이터 소스로의 DataTable을 사용하지 않는 경우에도 작동합니다 얻기 위해 사용하거나 현재를 지정하는 인덱스를 설정할 수 있습니다

combobox.SelectedIndex = k; 

선택한 항목. 게다가 현재 선택된 항목의 선택을 취소하려면 SelectedIndex를 -1로 설정하십시오.

때로는 방법은 FINDSTRING을 사용하여 지정하는 항목을 검색에 사용할 수 있으며, MSDN에서 예제가있다 :

private void findButton_Click(object sender, System.EventArgs e) { 
    int index = comboBox1.FindString(textBox2.Text); 
    comboBox1.SelectedIndex = index; 
} 

희망이 도움이.

관련 문제