Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get IDs of only checked rows of a datagridview

I have a datagridview that contains list of subjects populated from Subject table from database.Columns include

  • Select(checkbox),
  • SubjectId,
  • SubjectName,
  • SubjectGroup.

Now I want if a user Selects on any of the desired rows, the corresponding SubjectId's should be added to a List. I have made and inserted into the desired table in the database. The problem is that the new column of checkboxes I have added to this datagridview is not being detected.

My code is:

    foreach (DataGridViewRow row in gvSubjectsOpted.Rows)
        {

            if (Convert.ToBoolean(gvSubjectsOpted.SelectedRows[0].Cells["SelectId"].Value=true))
            {
                olist.Add(gvSubjectsOpted.SelectedRows[0].Cells["SubjectId"].Value.ToString());
            }
        }
like image 420
Muhammad Suleman Avatar asked Feb 04 '14 11:02

Muhammad Suleman


Video Answer


1 Answers

Late to the party. I had the same issue with trying to get the checkbox column by name, use the index instead. Here is a linq example assuming the checkbox is column 0 and the stored values for TrueValue and FalseVale are true and false respectively.

        var checkedRows = from DataGridViewRow r in gvSubjectsOpted.Rows
            where Convert.ToBoolean(r.Cells[0].Value) == true
            select r;

        foreach (var row in checkedRows)
        {
            olist.Add(row.Cells["SubjectId"].Value.ToString());
        }
like image 104
Bleeped Avatar answered Oct 19 '22 11:10

Bleeped