次のソースコードは、削除された行の直前の行にフォーカスを設定するためのものです。DataGridView行へのフォーカスの設定
私は、データベースから不要な単語dddddddd
を削除するとします。 Delete
ボタンを押すと、cynosure
という単語がフォーカスされ、DataGridView
の上部に配置されます。これは現在のケースではありません。今
、それが一番下に表示されます。
ソースコード
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;
}
}
}
}