1
votes

I have a dataGridView in a WinForm that is bound to a SQL database table. I want to refresh the data every two seconds or so, but maintain any row selection the user has made. Therefore I have set up a timer and implemented some code during the tick event. The code works fine to refresh the data, but I am struggling to get row selection to persist. What is happening is that when the timer ticks a second time, all rows in the dataGridView become selected and every tick after that. I am not sure what is causing this since my code to select the rows is inside a foreach loop and an if statement that should block this from happening. Here is my code for this function:

private void dataRefreshTimer_Tick(object sender, EventArgs e)
    {
        string selRows = null;
        foreach (DataGridViewRow row in taskDataGrid.Rows)
        {
            if (row.Selected = true)
            {
                selRows += row.Cells[0].Value.ToString() + ",";
                Console.WriteLine(selRows);
            }
        }
        currenttasksTableAdapter.Fill(taskManagerDataSet.currenttasks);
        currenttasksBindingSource.ResetBindings(false);
        try
        {
            if (selRows != null)
            {
                foreach (DataGridViewRow row in taskDataGrid.Rows)
                {
                    if (selRows.Contains(row.Cells[0].Value.ToString() + ","))
                    {
                        row.Selected = true;
                    }
                }
            }
        } catch (Exception ex) { Console.WriteLine(ex); }

Can anyone tell me what I am missing that is causing all rows to become selected? Thanks for any advice!

1
what is the value in Cells[0], a number? primary key? - Dr. Stitch
It is a hidden column containing the Pkey from the table, so each entry will be unique. And it is a number, as the field is indexed on the database. - Alex Fulton
don't use Contains in if condition and check with exact value it might be solve your problem - Darshan Faldu
Hard to use an exact value since I need to leave the possibility for multiple row selections. I need a collection to contain the Pkey data from all selected rows, so my first thought was to simply append a string with this value by using the code in the first foreach loop. Thus after the refresh, the second foreach loop would need to look in the string again for the pkey data. I have done this by using the Contains() method. - Alex Fulton

1 Answers

1
votes

Can anyone tell me what I am missing that is causing all rows to become selected?

if (row.Selected = true)

Here you actually are selecting each row (= is assignment operator). It should really be

if (row.Selected)

or

if (row.Selected == true)