简体   繁体   中英

Index was out of range when selecting row in DataGridView C#

I am using a DataSource to fill my DataGridView with available credit cards, then I add dummy credit card at the end to to use a new credit card.

private void ListCards()
    {            
        cards.Add(new CreditCard
        {
            Token = "new",
            LastFour = "New Card"
        });           
    }

When I go to select the "new" row and pass it to the next piece I get Index was out of range. Must be non-negative and less than the size of the collection. Index was out of range. Must be non-negative and less than the size of the collection.

private void Ok_btn_Click(object sender, EventArgs e)
    {
        int selectedRowIndex = CreditCards_grdvw.SelectedCells[0].RowIndex;
        tkn = Convert.ToString(CreditCards_grdvw.SelectedRows[selectedRowIndex].Cells[0]);
        this.DialogResult = DialogResult.OK;
        Close();

    }

I have checked to ensure that the row count is greater than SelectedRowIndex but I am still getting the error. Also when cards has one record in it initially and I add the dummy 'new' record, I used Visual Studio's immediate window ?CreditCards_grdvw.SelectedRows[0].Cells[0].Value , I get back "new". I should be getting the actual card at index 0, not the dummy card.

I realize I could just add another button to get the same functionality, but I would prefer not to. Any help would be greatly appreciated.

Is this the issue?

In getting the selectedRowIndex, you reference the first object in the SelectedCells collection. However, in the next line, you try to reference the SelectedRows collection. Does this fix it?

private void Ok_btn_Click(object sender, EventArgs e)
{
    int selectedRowIndex = CreditCards_grdvw.SelectedCells[0].RowIndex;
    tkn = Convert.ToString(CreditCards_grdvw.Rows[selectedRowIndex].Cells[0]);  //Reference the Rows[] collection, not SelectedRows[].
    this.DialogResult = DialogResult.OK;
    Close();

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM