2014-09-23 5 views
0

선택한 콤보 상자 항목을 기반으로 datagridview의 데이터베이스에서 테이블을로드하려고합니다. 엔티티 프레임 워크를 사용하고 있습니다. 내 코드는 다음과 같습니다 :콤보 상자 항목 선택에 따라 DataGridview의 테이블보기

private void btnCRUDLoadTable_Click(object sender, EventArgs e) 
    { 

     //prompt user when "Load Table" button is clicked without selecting any database or table or user 
     if (cboSelectDB.SelectedIndex <= -1 || cboSelectUser.SelectedIndex <= -1 || cboSelectTable.SelectedIndex <= -1) 
     { 
      MessageBox.Show("Please Select Database, User and Table First"); 
     } 
     else 
     { 
      //load data according to combobox selection in datagridview 
      if (cboSelectUser.Text.ToString() == "User_name") 
      { 
       var context = new NameEntities(); 
       BindingSource bi = new BindingSource(); 
       //here, instead of putting tablename is there a way to put 
       //combox item name? I have tried combobox.Text.ToString(), 
       //but it doesn't work, shows error 
       bi.DataSource = context.TableName; 
       dgvLoadTable.DataSource = bi; 
       dgvLoadTable.Refresh(); 
      } 
     } 

    } 

감사합니다.

+0

오류가 표시되는 경우 해당 오류를 표시하십시오. – Reniuz

+0

오류는 다음과 같습니다 : Identifier Expected – feather

+0

1.'bi.DataSource = combobox.Text.ToString();'줄에이 오류가 있습니까? 2. 텍스트가 비어 있거나 null이 아닌 것은 확실합니까? 추신. 텍스트는 이미 문자열이므로 ToString로 변환 할 필요가 없습니다. – Reniuz

답변

0

reflation을 사용하여 동적으로 테이블 이름을 설정할 수 있습니다. 아래.

var context = new NameEntities(); 
    BindingSource bi = new BindingSource(); 
    //here, instead of putting tablename is there a way to put 
    //combox item name? I have tried combobox.Text.ToString(), 
    //but it doesn't work, shows error 
    var TableName = combobox.Text.ToString(); 
    bi.DataSource = context.GetType().GetProperty(TableName).GetValue(obj, null); 
    dgvLoadTable.DataSource = bi; 
    dgvLoadTable.Refresh(); 

TableName은 데이터베이스 테이블에 해당하는 NameEntities에서 작성된 속성 이름이어야합니다.

+0

obj가 현재 컨텍스트에 존재하지 않는다고 말합니다. – feather

+0

@feather obj 대신 context를 사용합니다. 나는 답을 바로 잡았다. – Priyank

+0

nullReferenceExeption이 처리되지 않았다는 메시지가 나타납니다. – feather

관련 문제