设置数据网格行背景颜色 WPF - 循环

Set datagrid row background color WPF - Loop

我有一个 Task 可以抛出 DataGridRow 并执行一些任务。当他完成时,为该行设置 background color。我添加了 cancel button 来停止任务,并添加了 continue button 来继续上次完成的地方。除了更改行的背景颜色外,所有工作都很完美。

这是 XAML 代码,我是 WPF 的新手,所以它对 DataGrid

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

这是更改背景颜色的 C# 代码。

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

当我点击开始 Button 并且它为每个 Row 更改 Background 颜色时,此代码有效。问题是当我单击取消 Button 然后单击继续 Button,然后我得到 NullReferenceException。继续按钮仅检查 DataBase Table.

中的最后一个 ID
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++;
}

继续 Button 的代码,除了更改行的背景。

更新: 取消代码 Button:

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

继续代码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);
        }

好的,我想我现在明白你的问题是什么了。它在您自己的代码中:

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++;
}

您的 foreach 循环运行的次数与 DataGrid 中的行数一样多。但是在某些情况下,根据您的逻辑,您会在内部将 number 变量增加两次。也就是说,如果您进入 if 语句,您会增加一次,然后在循环结束时再次增加。因此,无论何时进入该 if 语句,您都会将行数增加两次。

这就是为什么您的计数器的值高于您拥有的实际行数的原因。您需要删除 if 语句中的增量。

我解决了这个问题。所以问题是因为我再次用数据填充 DataGrid 。相反,我不填写它,我只得到我上次在 Table 中停止的地方和一些 ID。

Button 的代码继续:

 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
  ................