[英]Change the color of the Grid Cell in C#
我正在用C#编写用于占用网格映射的程序。 我想更改网格单元的颜色。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Controls;
using System.Windows;
namespace gridappl
{
public partial class Form1 : Form
{
private Window mainWindow;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// Create the application's main window
mainWindow = new Window();
mainWindow.Title = "Grid Sample";
// Create the Grid
Grid myGrid = new Grid();
myGrid.Width = 600;
myGrid.Height = 600;
//myGrid.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
//myGrid.VerticalAlignment = System.Windows.VerticalAlignment.Top;
myGrid.ShowGridLines = true;
// Define the Columns
ColumnDefinition colDef1 = new ColumnDefinition();
ColumnDefinition colDef2 = new ColumnDefinition();
ColumnDefinition colDef3 = new ColumnDefinition();
myGrid.ColumnDefinitions.Add(colDef1);
myGrid.ColumnDefinitions.Add(colDef2);
myGrid.ColumnDefinitions.Add(colDef3);
// Define the Rows
RowDefinition rowDef1 = new RowDefinition();
RowDefinition rowDef2 = new RowDefinition();
RowDefinition rowDef3 = new RowDefinition();
myGrid.RowDefinitions.Add(rowDef1);
myGrid.RowDefinitions.Add(rowDef2);
myGrid.RowDefinitions.Add(rowDef3);
// Add the Grid as the Content of the Parent Window Object
mainWindow.Content = myGrid;
mainWindow.Show();
}
}
}
我尝试使用许多如下命令:
myGrid.Background = Brushes.Azure;
myGrid.Background = System.Drawing.Brushes.Red;
但是,该程序仍会引发错误。 根据我们的选择应如何更改网格单元的颜色?
for (int i = 0; i < myGrid.Rows.Count; i++)
{
for (int j = 0; j < myGrid.Rows[i].Cells.Count; j++)
{
myGrid.Rows[i].Cells[j].Style.BackColor = /*color you want*/
}
}
尝试使用此方法动态填充背景色。
或尝试这个
myGrid.Background= new SolidColorBrush(Colors.Green);
您可以尝试以下代码:
for (int i = 0; i < myGrid.Rows.Count; i++)
{
myGrid.Rows[i].Cells[/*Cell you want the color*/].Style.BackColor = /*color you want*/
}
如果您想遍历所有行,则可以使用for循环,或者只需执行
myGrid.Rows[/*specific row number*/].Cells[/*Cell you want the color*/].Style.BackColor = /*color you want*/
例:
myGrid.Rows[0].Cells[1].Style.BackColor = Color.Red;
foreach (DataGridViewRow row in dgv_List.Rows)
{
if (intcolumncunt == 2)
{
if(Convert.ToInt32(row.Cells[2].Value.ToString()) > Convert.ToInt32(row.Cells[3].Value.ToString()))
{
row.DefaultCellStyle.BackColor = Color.Red;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.