2

I am trying to create a dataGridView which has 2 columns, column 1 contains names, and column 2 contains numbers, which is working fine.

I now want to allow the user to select a single or multiple rows using the keyboard or mouse which should automatically total up the numbers column based on the rows selected.

I so far have the following:

    private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
        if (dataGridView1.SelectedCells.Count > 0)
        {
            int selectedrowindex = dataGridView1.SelectedCells[0].RowIndex;

            DataGridViewRow selectedRow = dataGridView1.Rows[selectedrowindex];

            string a = Convert.ToString(selectedRow.Cells[0].Value);
        }
    }

Where string a will eventually show the total in a label on the form.

But this seems to be the wrong way to go about doing what I am trying to achieve. Any suggestions?

1
  • Your code only shows the current cell? You want a total sum of selected numbers instead? Commented Mar 18, 2015 at 12:40

1 Answer 1

2

If you want to find a total of a particular column of selected rows' value:

int total = dgv.SelectedRows.Cast<DataGridViewRow>().Sum(
    row => (int) row.Cells[colSomeNumber.Name].Value);

If you want to find a total of selected cells' values:

int total = dgv.SelectedCells.Cast<DataGridViewCell>().Sum(cell => (int) cell.Value);

If you want to find a total of selected cells' values for only some column(s), do it like this:

int total = dgv.SelectedCells.Cast<DataGridViewCell>().Where(
    c => c.OwningColumn == colSomeNumber).Sum(cell => (int) cell.Value);

Where colSomeNumber is the actual column.

Just put it in the dgv_SelectionChanged event and that's it. That's pretty much the "neatest" way to do it.

Sign up to request clarification or add additional context in comments.

3 Comments

That does work, but only if I click on the actual content within the cells. How do I get it to work if any part of a row is clicked to select it?
It currently looks like this: this.dataGridView1.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellContentClick); Can't seem to change that the _SelectionChanged.
SelectionChanged is another event, probably more suitable for what you need. If you want it to fire on selected rows I recommend you change the SelectionMode, e.g. .SelectionMode = DataGridViewSelectionMode.FullRowSelect; and use the first solution from the answer (user will still be able to edit individual cells).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.