我正在为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;
但是,程序仍会抛出错误。根据我们的选择,应该怎么做才能改变网格单元的颜色?
答案 0 :(得分:2)
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);
答案 1 :(得分:1)
您可以尝试以下代码:
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;
答案 2 :(得分:1)
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;
}
}
}