masiboo
masiboo

Reputation: 4719

c# Console.WriteLine() with color text is massing the output

I am trying to show a warning to the user by the following code. But it is massing the output text.

Console.ForegroundColor = ConsoleColor.Yellow;
Console.BackgroundColor = ConsoleColor.Red;
Console.WriteLine($"The selected row {selection} is not found in the database.");
Console.ResetColor();
Console.ReadLine();
Environment.Exit(0);

The display looks as follows:- enter image description here

I only want to make coloring of the text "The selected row is not found in the database.". Nothing extra. Otherwise it looks ugly. How to do it?

Upvotes: 5

Views: 4966

Answers (1)

René Vogt
René Vogt

Reputation: 43936

The problem is that the carriage return and new line draws the background color for these lines. Simply use Console.Write() instead of Console.WriteLine():

Console.ForegroundColor = ConsoleColor.Yellow;
Console.BackgroundColor = ConsoleColor.Red;
// only write without new line
Console.Write($"The selected row {selection} is not found in the database.");
Console.ResetColor();
Console.WriteLine(); // if necessary
Console.ReadLine();
Environment.Exit(0);

Upvotes: 11

Related Questions