2017-08-31 14 views
1

次のソースコードは、削除された行の直前の行にフォーカスを設定するためのものです。DataGridView行へのフォーカスの設定

enter image description here

私は、データベースから不要な単語ddddddddを削除するとします。 Deleteボタンを押すと、cynosureという単語がフォーカスされ、DataGridViewの上部に配置されます。これは現在のケースではありません。今

enter image description here

、それが一番下に表示されます。

enter image description here

ソースコード

void SetFocusToWord(Word concernedWord) 
    { 
     if (concernedWord != null) 
     { 
      int index = 0; 
      foreach (DataGridViewRow r in dataGridView1.Rows) 
      { 
       Word item = r.Tag as Word; 

       if (concernedWord.Name == item.Name) 
       { 
        dataGridView1.Focus(); 
        dataGridView1.CurrentCell = dataGridView1.Rows[index].Cells[0]; 

        break; 
       } 

       index++; 
      } 
     } 
    } 

private void btnDelete_Click(object sender, EventArgs e) 
     { 
      try 
      { 
       if (dataGridView1.SelectedRows.Count > 0) 
       { 
        int selectionIndex = dataGridView1.SelectedRows[0].Index; 

        foreach (DataGridViewRow r in dataGridView1.SelectedRows) 
        { 
         Word c = r.Tag as Word; 

         if (c != null) 
         { 
          _wordDatabase.Delete(c); 
         } 
        } 

        LoadToDataGridView(); 

        if(selectionIndex > 0) 
        { 
         selectionIndex = selectionIndex - 1; 
        } 

        Word item = dataGridView1.Rows[selectionIndex].Tag as Word; 

        SetFocusToWord(item); 
       } 
       else 
       { 
        throw new Exception(SelectionErrorMessages.GetErrorMessageFor(typeof(Word))); 
       } 
      } 
      catch (Exception ex) 
      { 
       MessageBox.Show(ex.Message); 
      } 
     } 

    void LoadToDataGridView() 
    { 
     dataGridView1.Rows.Clear(); 

     List<Word> items = (List<Word>)_wordDatabase.Get(); 

     if (items != null) 
     { 
      if (items.Count > 0) 
      { 
       int i = 0; 
       foreach (Word c in items) 
       { 
        dataGridView1.Rows.Add(c.Name, c.Hint); 
        dataGridView1.Rows[i].Tag = c; 
        ++i; 
       } 
      } 
     } 
    } 

答えて

1

データベースを再ロードすることは、不要な手順のようです。あなたはグリッドが動作するようにする方法に基づいて

、このようなコードを使用してみてください:

if (dataGridView1.SelectedRows.Count > 0) { 
    int selectIndex = dataGridView1.SelectedRows[0].Index; 
    dataGridView1.Rows.RemoveAt(selectIndex); 
    if (selectIndex > 0) { 
    dataGridView1.ClearSelection(); 
    dataGridView1.Rows[selectIndex - 1].Selected = true; 
    dataGridView1.FirstDisplayedScrollingRowIndex = selectIndex - 1; 
    } 
} 
0

パフォーマンスが低下し、不要なコードの存在量が、プロジェクトにあなたが適切に結合リサイズを使用していないの結果です。コントロールのBindingContextとBindingSourceの利用を開始することをお勧めします。これはあなたの問題のほとんどを解決するはずです。

winformsバインドの詳細については、docsをお勧めします。

関連する問題