Reputation:
I'm currently trying to change the background color of an array, specifically in this case, grid[0, 0]. I've searched around for a while and can't seem to come up with anything. It's probably quite a simple problem, or maybe I need a break!
Console.BackgroundColor(grid[0,0]) = ConsoleColor.Cyan;
I'm trying to make the background colour Cyan. The variable is a string and contains a space.
Cheers in advance.
FULL SOURCE:
static void Main(string[] args)
{
Console.CursorSize = 100;
int row, col;
string[,] grid = new string[10, 10];
for (col = 0; col < 10; col++)
{
for (row = 0; row < 10; row++)
{
grid[col, row] = " ";
}
}
for (col = 0; col < 10; col++)
{
for (row = 0; row < 10; row++)
{
Console.Write(grid[col, row]);
}
Console.Write("\n");
}
Console.BackgroundColor(grid[0,0]) = ConsoleColor.Cyan;
Console.ReadKey();
}
Upvotes: 0
Views: 2153
Reputation: 5723
I am pretty sure that Console.BackgroundColor sets the color of the text to be printed. So, if you want to print a string with one word of another color, you would do:
Console.Write("Hello word, the following text is cyan: ");
Console.BackgroundColor = ConsoleColor.Cyan;
Console.Write("Cyan text ");
Console.BackgroundColor = ConsoleColor.Black;
Console.WriteLine("(but this is not cyan)");
Upvotes: 0
Reputation: 31194
Okay, first thing you need to do is to make grid
of a type that can contain both a color and a string.
public class ColoredString
{
public ConsoleColor Color{get; set;}
public string Content {get; set;}
}
and then, when you set your color, do it like this.
grid[0,0].Color = ConsoleColor.Cyan;
after that, you can print in color like this
public static void PrintColor(ColoredString str)
{
var prevColor = Console.BackgroundColor;
Console.BackgroundColor = str.Color;
Console.Write(str.Content);
Console.BackgroundColor = prevColor;
}
Here's a SSCCE
public class Program
{
static void Main(string[] args)
{
var str = new ColoredString()
{
Color = ConsoleColor.Cyan,
Content = "abcdef",
};
PrintColor(str);
Console.ReadKey(false);
}
public static void PrintColor(ColoredString str)
{
var prevColor = Console.BackgroundColor;
Console.BackgroundColor = str.Color;
Console.Write(str.Content);
Console.BackgroundColor = prevColor;
}
}
public class ColoredString
{
public ConsoleColor Color { get; set; }
public string Content { get; set; }
}
Upvotes: 1