Set datagrid row background color WPF - Loop [clos

2019-09-21 18:53发布

I have one Task which go throw DataGridRow and do some task. When he finish it set background color for that row. I added cancel button to stop task, and continue button to continue where it finished last time. All work perfect except changing background color for row.

This is XAML code, i'm new to WPF so it's not too big for DataGrid

<DataGrid 
     Name="dataGridViewMyGroups" 
     Grid.Row="0" ColumnWidth="*" 
     VerticalScrollBarVisibility="Auto" 
     IsReadOnly="True" 
     SelectionUnit="FullRow" 
     SelectionMode="Single"    
     MouseDoubleClick="dataGridViewMyGroups_MouseDoubleClick">
</DataGrid>

Here is a C# code for changing background color.

DataGridRow rowColor = (DataGridRow)dataGridViewMyGroups.ItemContainerGenerator
                    .ContainerFromIndex(number);                                  
rowColor.Background = new SolidColorBrush(System.Windows.Media.Color.FromRgb(223, 227, 238)); 

This code work when I click on start Button and it change Background color for each Row. Problem is when I click cancel Button and then click on continue Button, then I got NullReferenceException. Continue button only check last ID in DataBase Table.

int number=0;
foreach (GroupsInList group in dataGridViewMyGroups.Items)
{
   if (fbgroupID != null && check==true)
   {
       number++;
       if (fbgroupID != groupLink)
       {
         continue;
       }
       check = false;
       continue;
   }

     //Do something and change background (code above).
     number++;
}

Code for continue Button work except changing row's background.

UPDATE: Code for Cancel Button:

 if (MessageBox.Show("Do you want to stop posting?", "Confirmation", 
 MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
        {
            tokenSource.Cancel(); 
        }

Code for Continue Button:

        int postID;
        string fbGroupID;
        int listID;

        using (OleDbConnection connection = new OleDbConnection(conn))
        {

           //code for getting value from `DB Table`

            postID = list[0].PostID;
            fbGroupID = list[0].FBGroupID;
            listID = list[0].ListForGroupID;
        }

        cmbSelectList.SelectedValue = listID;
        cmbSavedPosts.SelectedValue = postID;
        loadGroupsInList(); //Maybe this is problem because here I update(reload) DataGrid again.

        tokenSource = new CancellationTokenSource();

        try
        {                              
            await TaskPostToGroup(tokenSource.Token, fbGroupID, true);
        }
        catch (OperationCanceledException ex)
        {
            System.Windows.MessageBox.Show(ex.Message, "CANCELED", MessageBoxButton.OK, MessageBoxImage.Stop);
        }
        catch (NullReferenceException)
        {
            //I don't have solution for changing background color for each row when continue button is clicked
        }
        catch (Exception ex)
        {
            System.Windows.MessageBox.Show(ex.Message + "\n\n" + ex.StackTrace, "Exception", MessageBoxButton.OK, MessageBoxImage.Error);
        }

2条回答
The star\"
2楼-- · 2019-09-21 19:41

I resolved this problem. So the problem is because I fill DataGrid again with Data. Instead that I don't fill it I only get ID where I stopped from last time in that Table with some ID.

Code for Button Continue:

 int postID;
 string fbGroupID;
 int listID = int.Parse(cmbSelectList.SelectedValue.ToString());

 using (OleDbConnection connection = new OleDbConnection(conn))
 {

  ................

       commName.CommandText = "SELECT TOP 1 [FaceBookGroupID],[PostID] FROM [Advertiseing] WHERE [email] = @email AND [ListForGroupID]= @listID ORDER BY [Date-Time] DESC";

  ................

       postID = list[0].PostID;
       fbGroupID = list[0].FBGroupID;        
       *listID = list[0].ListForGroupID;* //Deleted
  }


  //cmbSelectList.SelectedValue = listID; - Deleted
    cmbSavedPosts.SelectedValue = postID;
  //loadGroupsInList(); - Deleted

  // Next part of code are the same
  ................
查看更多
Evening l夕情丶
3楼-- · 2019-09-21 19:54

OK I think I see what your problem is now. It's there in your own code:

int number=0;
foreach (GroupsInList group in dataGridViewMyGroups.Items)
{
    if (fbgroupID != null && check==true)
    {
        number++;
        if (fbgroupID != groupLink)
        {
             continue;
        }
        check = false;
        continue;
    }
    //Do something and change background (code above).
   number++;
}

Your foreach loop runs as many times as there are rows in your DataGrid. But inside you increment number variable twice in some cases depending on your logic. That is, if you go in the if statement you increase it once, and then again at the end of the loop. So whenever you go in that if statement you increment your row count twice.

Which is why your counter goes to a higher value than the actual number of rows you have. You need to remove the increment inside the if statement.

查看更多
登录 后发表回答