C#.net winform中,datagridview 符合条件的单元格字体变色
我想设置一个BUTTON,检索DATAGRIDVIEW1中的第一列的全部单元格,将包含空格的单元格找出来,并将符合条件的单元格字体变红,或者背景色变红。代码要怎么样写?求教达人哈。 展开
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
DataGridViewTextBoxColumn c1 = new DataGridViewTextBoxColumn();
DataGridViewTextBoxColumn c2 = new DataGridViewTextBoxColumn();
c1.HeaderText = "第一列";
c2.HeaderText = "第二列";
dataGridView1.Columns.Add(c1);
dataGridView1.Columns.Add(c2);
dataGridView1.AllowUserToAddRows = false;
Random r = new Random();
for (int i = 0; i < 100; i++) {
int x = r.Next(100, 500);
DataGridViewRow row = new DataGridViewRow();
DataGridViewTextBoxCell tc1 = new DataGridViewTextBoxCell();
DataGridViewTextBoxCell tc2 = new DataGridViewTextBoxCell();
row.Cells.Add(tc1);
row.Cells.Add(tc2);
if (x < 250)
{
row.Cells[0].Value = "how are you+" + x.ToString();
}
else {
row.Cells[0].Value = "HelloWorld!+" +x.ToString();
}
row.Cells[1].Value = x.ToString();
dataGridView1.Rows.Add(row);
}
}
private bool checkSpace(string txt) {
if (txt.IndexOf(" ") != -1) {
return true;
}
return false;
}
private void button1_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.Rows) {
if (checkSpace(row.Cells[0].Value.ToString())) {
row.Cells[0].Style.BackColor = Color.Red;
}
}
button1.Focus();
}
}
}
给分吧
采纳前最后一问,学习了半天,为什么非要加上“ dataGridView1.AllowUserToAddRows = false;
”这句代码才能执行呢?再讨教一下哈
就是不让datagridview自动在你最后一行添加新行,你做一个实验就知道了,我知识不让他自动新增行罢了。