2014-10-03 2 views
0

이 질문에 대한 답변이 다른 곳에서 이미 제기 된 경우 사과드립니다 (몇 시간 동안 검색을하지 않으면 답변을 찾을 수 없습니다).C# DataGridview에서 행을 선택할 때 데이터 표시

어쨌든 내 코드는 작동하지만 단추를 사용하여 테스트했습니다. 행을 선택하고 버튼을 클릭하면 올바른 데이터가 표시됩니다.

하지만 행을 선택한 다음 버튼을 누르는 대신 데이터를 표시하고 싶습니다.

내 코드 :

private void dgvRecipes_CellContentClick(object sender, 
             DataGridViewCellEventArgs e) 
{ 

    if (dgvRecipes.SelectedRows.Count > 0) 
    { 
    int selectedRecipe = 
     int.Parse(dgvRecipes.SelectedRows[0].Cells[0].Value.ToString()); 

    lblRecipe.Text = dgvRecipes.SelectedRows[0].Cells[1].Value.ToString(); 

    string selectStr = "SELECT IngredDesc, IngredAmt, IngredComment " + 
      "FROM Ingredient, RecipeIngredients 
      WHERE RecipeIngredients.RecipeNo = " + selectedRecipe + 
      " AND Ingredient.IngredID = RecipeIngredients.IngredID "; 


    dbCmd = new SqlCommand(selectStr, dbConn); 
    dbAdapter = new SqlDataAdapter(dbCmd); 
    dbAdapter.Fill(ds, "RecipeIngredients"); 
    dgvIngredients.DataSource = ds.Tables["RecipeIngredients"]; 

    selectStr = "SELECT InstructionNo, Instructions FROM RecipeInstructions " 
       + "WHERE RecipeInstructions.RecipeNo = " + selectedRecipe; 


    dbCmd = new SqlCommand(selectStr, dbConn); 
    dbAdapter = new SqlDataAdapter(dbCmd); 
    dbAdapter.Fill(ds, "RecipeInstructions"); 
    dgvInstructions.DataSource = ds.Tables["RecipeInstructions"]; 

    } 

} 

다시 말하지만, 내가 제대로 내 질문을 표현한 심하게 코드를 설정하지 않은 경우 사과.

답변

1

당신은 단지 DataGridView에의 Selection Change event을 추가해야합니다

private void DataGridView1_SelectionChanged(object sender, EventArgs e) 
{ 
    ...... 
} 

당신이 DataGridView에의 properties에 가야 할 것입니다 언급 유용한 TaW을 설명하기 위해 (VS의의 desgin에서)을 SelectionChange 이벤트에 Events 탭을 더블 클릭을 선택

+0

나는 이것을 시도했지만 도움이되지 않았다. 그래도 답장을 보내 주셔서 감사합니다. –

+1

이렇게하면됩니다. 실제로 이벤트를 __hooked했거나 코드를 추가 했습니까 ?? – TaW

+0

감사합니다!, 이벤트 탭을 사용하여 변경했습니다. 방금 ​​코드를 변경하려고했습니다. –

0

일반적으로 바인딩을 사용하여이 작업을 수행하므로 입력란 뒤에 여분의 코드가 없어도 텍스트 상자에 동일한 값이 표시됩니다. 하지만 DataGrid의 "selectionmode"라는 속성을 변경할 수도 있습니다. selectRow로 설정해야합니다. 그런 다음 적절한 이벤트를 찾고 단추 아래에있는 코드를 해당 이벤트로 이동하십시오.

0

DataGridView 이벤트를 사용하십시오. 세포 가 선택 될 때마다

인 selectionchanged 이벤트가 발생하거나 선택은 을 취소 프로그래밍 여부 사용자 액션에 의한.

+0

SelectionChanged에 대한 두 번째 언급, 뭔가를 놓친 것일 수 있습니다. 다음과 같이되어야합니다. 개인 무효 dgvRecipes_SelectionChanged (개체 발신자, EventArgs e) {code here} –

관련 문제