5

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?

masiboo
  • 4,537
  • 9
  • 75
  • 136
  • 1
    Maybe use `Console.Write` instead of `Console.WriteLine` ? – cosh Feb 01 '18 at 10:41
  • I think you find your answer here https://stackoverflow.com/questions/2743260/is-it-possible-to-write-to-the-console-in-colour-in-net – pathik devani Feb 01 '18 at 10:41
  • It is caused by the console window scrolling, the new empty line revealed by the scroll is painted with the selected background color. Consider using Write() instead of WriteLine(). – Hans Passant Feb 01 '18 at 10:42

1 Answers1

11

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);
René Vogt
  • 43,056
  • 14
  • 77
  • 99