2012-07-29 10 views
0

저는 C# Windows 양식 응용 프로그램에서 작업하고 있습니다. 콤보 상자에서 선택한 항목의 ID를 가져 오려고했습니다. 아래 코드는 내 코드입니다.Combobox 창에서 선택한 항목의 ID 가져 오기

private void ProductForm_Shown(object sender, EventArgs e) 
    { 
     SqlCeConnection Connection = new SqlCeConnection(ConString); 
     Connection.Open(); 
     SqlCeDataAdapter da = new SqlCeDataAdapter("Select * from CastingMaterial", Connection); 
     DataTable dt = new DataTable(); 
     da.Fill(dt); 
     for (int i = 0; i < dt.Rows.Count; i++) 
     { 
      ProductsComboBox.Items.Add(dt.Rows[i]["PartName"]); 

     } 
     ProductsComboBox.DisplayMember = "PartName"; 
     ProductsComboBox.ValueMember = "PartId"; 
     Connection.Close(); 
    } 

    private void ProductsComboBox_SelectedIndexChanged(object sender, EventArgs e) 
    { 
     int ProductIndex = ProductsComboBox.SelectedIndex; 
     string productName = ProductsComboBox.Text.ToString(); 
     int ProductId =Convert.ToInt32(ProductsComboBox.SelectedValue); 
     SqlCeConnection Connection = new SqlCeConnection(ConString); 
     Connection.Open(); 
     String Query = "SELECT * From CastingMaterial where [email protected]"; 
     SqlCeDataAdapter da = new SqlCeDataAdapter(Query, Connection); 
     da.SelectCommand.Parameters.AddWithValue("PartId", ProductId); 
     DataSet ds = new DataSet(); 
     SqlCeCommandBuilder commandBuilder = new SqlCeCommandBuilder(da); 

     BindingSource bsource = new BindingSource(); 

     da.Fill(ds, "CastingMaterial"); 
     bsource.DataSource = ds.Tables["CastingMaterial"]; 
     Productgv.DataSource = bsource; 
     Connection.Close(); 
    } 

모든 도움을 주시면 감사하겠습니다.

답변

0

DataRow로 항목을 추가해야합니다. 대신, 열 중 하나에서 값을 추출됩니다

ProductCombo.Items.Add(dt.Rows[i]); 

그런 다음 당신은 당신이 잘못 항목을 추가하기 때문에 그러나,이 효과가 없습니다 올바르게 DisplayMember 및 ValueMember을 설정합니다.

0

솔직히 질문을 더 명확하게 게시해야합니다.

콤보 상자의 선택한 ID를 어떻게 가져 오시겠습니까?
그리고이 ID를 어떤 용도로 사용하셨습니까?

여기 실제 문제를 더 자세히 설명해야한다고 생각합니다. 원인 코드가 제대로 작동하는 것 같습니다.

그리고 btw에서는 실제로 콤보 상자의 데이터 항목을 설정하는 루프가 필요하지 않습니다. 콤보의 DataSource 속성을 방금 데이터를 추출한 DataTable에 할당하면됩니다.

ProductsComboBox.DataSource = dt ... 잘 작동합니다.
그런 다음 DisplayMemberValueMember을 각각의 열로 설정할 수 있습니다.

관련 문제