francesF
francesF

Reputation: 13

Assign DataGridView.SelectedRows to List

How can I accomplish assigning SelectedRows from a DataGridView to multiple lists?

I've been trying to do this with foreach and for loop statements, but it is not producing the expected results. It only displays the first row regardless of which row is selected.

How can I make the for loop statement search only for selected rows? Or is there a better way to do this?

List<string> dTitle = new List<string>();
List<string> dSku = new List<string>();
List<string> dPrice = new List<string>();
List<string> dDesc = new List<string>();
List<string> dImage = new List<string>();

foreach (DataGridViewRow r in dgvProducts.SelectedRows)
{
    for (int i = 0; i < dgvProducts.Rows.Count - 1; i++)
    {
        dSku.Add(dgvProducts.Rows[i].Cells[1].Value.ToString());
        dTitle.Add(dgvProducts.Rows[i].Cells[2].Value.ToString());
        dPrice.Add(dgvProducts.Rows[i].Cells[3].Value.ToString());
        dDesc.Add(dgvProducts.Rows[i].Cells[4].Value.ToString());
        dImage.Add(dgvProducts.Rows[i].Cells[5].Value.ToString());
    }
}

dgvProduct - the DataGridView

Upvotes: 1

Views: 4421

Answers (1)

jhmt
jhmt

Reputation: 1421

I think you don't need to use the nested loop to do this.

List<string> dTitle = new List<string>();
List<string> dSku = new List<string>();
List<string> dPrice = new List<string>();
List<string> dDesc = new List<string>();
List<string> dImage = new List<string>();

foreach (DataGridViewRow r in dgvProducts.SelectedRows)
{
    dSku.Add(r.Cells[1].Value.ToString());
    dTitle.Add(r.Cells[2].Value.ToString());
    dPrice.Add(r.Cells[3].Value.ToString());
    dDesc.Add(r.Cells[4].Value.ToString());
    dImage.Add(r.Cells[5].Value.ToString());
}

Upvotes: 2

Related Questions