/ / DatagridView最後の行を選択-c#、datagridview

DatagridView最後の行を選択する - c#、datagridview

選択したデータグリッドビューの最後の行の設定に問題があります。この方法で最後の行を選択します。

if (grid.Rows.Count > 0)
{
try
{
grid.Rows[grid.Rows.Count - 1].Selected = true;
grid.CurrentCell = grid.Rows[grid.Rows.Count - 1].Cells[1]
}
catch (IndexOutOfRangeException)
{ }
catch (ArgumentOutOfRangeException)
{ }
}

このコードを実行すると、例外が発生します。 IndexOutOfRangeException occurred:Index-1には値がありません。

デバッグするとき Rowsコレクションと対応する Cells コレクション両方のコレクションがいっぱいになっています。 Rows and Cellsコレクションのインデックスも存在します。

ここで何が間違っているのか、私には見当もつかない。ここで私を助けることができる誰か? Thnx

編集:

完全な例外は次のとおりです。

System.IndexOutOfRangeException: Index -1 does not have a value.
at System.Windows.Forms.CurrencyManager.get_Item(Int32 index)
at System.Windows.Forms.CurrencyManager.get_Current()
at System.Windows.Forms.DataGridView.DataGridViewDataConnection.OnRowEnter(DataGridViewCellEventArgs e)
at System.Windows.Forms.DataGridView.OnRowEnter(DataGridViewCell& dataGridViewCell, Int32 columnIndex, Int32 rowIndex, Boolean canCreateNewRow, Boolean validationFailureOccurred)
at System.Windows.Forms.DataGridView.SetCurrentCellAddressCore(Int32 columnIndex, Int32 rowIndex, Boolean setAnchorCellAddress, Boolean validateCurrentCell, Boolean throughMouseClick)
at System.Windows.Forms.DataGridView.set_CurrentCell(DataGridViewCell value)

回答:

回答№1の11

試してください:

dataGridView1.ClearSelection();//If you want

int nRowIndex = dataGridView1.Rows.Count - 1;
int nColumnIndex = 3;

dataGridView1.Rows[nRowIndex].Selected = true;
dataGridView1.Rows[nRowIndex].Cells[nColumnIndex].Selected = true;

//In case if you want to scroll down as well.
dataGridView1.FirstDisplayedScrollingRowIndex = nRowIndex;

次の出力を提供します:(最後の行、スクロールして選択)

代替テキスト


回答№2については4

私はこれが少し遅いかもしれないことを知っていますが、それは他の誰かに役立つかもしれません。

あなたはこれを試しましたか?

grid.Rows.Row[grid.Rows.Count -1].Selected = true;

Windowsアプリでは、最初にデータグリッドビューでコードを使用しましたが、同じ例外が発生しました。その後、ベッドにいたときに夜になりました(私はプログラミングの初心者です)。

私が次のように書く場合: Rows[Rows.count-1] 最初の行は「0」と「0-1 = -1」なので、範囲外です:)

次に、コードを Rows.Row[index] 出来た! :)


C#3.0以降を使用する場合の代替案:CellAddress()をチェックアウトしてください。 ;)

心から


答え№3の2

これにLinqを使用することを考えましたか?

    grid.Rows.OfType<DataGridViewRow>().Last().Selected = true;
grid.CurrentCell = grid.Rows.OfType<DataGridViewRow>().Last().Cells.OfType<DataGridViewCell>().First(); // if first wanted

回答№4の場合は1

IndexOutOfRangeExceptionの「キャッチ」ブロックは空であり、エラーはまったく表示されません。

質問が正確ではないか、例外が別の場所にスローされています。

編集: 追加したコールスタックに目を通すと、実際にエラーが発生していることがわかります。 ない ここに投げられますが、むしろ CurrencyManager クラス "s Current/Item プロパティは、最終的にの呼び出しによってトリガーされます CurrentCell セッター。

結論:問題はこのコードにはありません。例外は、現在のセルの設定によってトリガーされる他のコードによってスローされています。


回答№5の場合は0
dataGridView1.Rows[dataGridView1.Rows.Count - 1].Selected = true;

答え№6の場合は-1

最終的には最後の行が空になりますユーザーが新しい行を追加できる空の行。この行は選択できません。 grid.Rows.Count-2を試しましたか?別の方法として、AllowUserToAddRowsをfalseに設定できます。