Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/297.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何交替更改RTB文本的背景色_C#_Winforms - Fatal编程技术网

C# 如何交替更改RTB文本的背景色

C# 如何交替更改RTB文本的背景色,c#,winforms,C#,Winforms,我需要在RTB中更改文本背景色。RTB是在循环中为来自DB的消息数创建的。 我实现了一个逻辑来实现它,但感觉逻辑很简单。 那个么,你们能给出实施相同或我的想法吗 代码: foreach (DataSet.NoteRow note in _ds.Note) { CreateNotes(note); } private void CreateNotes(string note) { //txt : Rich Text Box dynamical

我需要在RTB中更改文本背景色。RTB是在循环中为来自DB的消息数创建的。
我实现了一个逻辑来实现它,但感觉逻辑很简单。
那个么,你们能给出实施相同或我的想法吗

代码:

foreach (DataSet.NoteRow note in _ds.Note)
        {
            CreateNotes(note);
        }
private void CreateNotes(string note)
{
//txt : Rich Text Box dynamically created for each note
//test : Selected text in 'note'
int index = txt.Text.ToUpper().IndexOf(test.ToUpper());
txt.Select(index, test.Length);
txt.SelectionFont = new Font(txt.Font.Name, txt.Font.Size, txt.Font.Style^ FontStyle.Bold);
//x global variable initialised as 1
if(x % 2 == 1)
txt.SelectionBackColor = System.Drawing.Color.Gray;
x++;  }
场景:
如果Notes有5条消息,则备选消息的背景颜色应为灰色。

试试这个

private void CreateNotes(string note)
{
//txt : Rich Text Box dynamically created for each note
//test : Selected text in 'note'
int index = txt.Text.ToUpper().IndexOf(test.ToUpper());
txt.Select(index, test.Length);
txt.SelectionFont = new Font(txt.Font.Name, txt.Font.Size, txt.Font.Style^ FontStyle.Bold);
 Random rnd = new Random();

//x global variable initialised as 1
if(x % 2 == 1)
txt.SelectionBackColor = Color.FromArgb(rnd.Next(255), rnd.Next(255), rnd.Next(255));
x++;  }

如果逻辑更改出现在这一行,我会很高兴的
如果(x%2==1)
类似于计算消息的数量,我们可以使用它吗?我没有得到你想要的逻辑让我们假设我有5条消息。因此,当第一条消息进入时,
x
将为1,如果(x%2==1)满足并应用颜色,则处于条件
。对于第二条消息,
x
将为2,条件失败,因此没有背景色..流将继续..此逻辑正在工作..我在问是否有其他有效的方法来实现此目的。