0

I have a car class with four attributes (colour, model, mileage, year) and I get these attributes from four text boxes. I then assign these attributes to a new object of the car class and assign this new object to an object array in the car class. I need to be able to highlight the mileage attribute but I am outputting in a string builder like this it like this:

private void button1_Click(object sender, EventArgs e)
{
    carColourIN = colour.Text;
    carModelIN = model.Text;
    carMileageIN = Double.Parse(mileage.Text);
    carYearIN = Int32.Parse(year.Text);

    Car user = new Car(carColourIN, carModelIN, carMileageIN, carYearIN);

    Car.vehicles[i] = user;
    StringBuilder sb = new StringBuilder();


    sb.Append("Colour: " + Car.vehicles[i].CarColour + "\nModel: " + Car.vehicles[i].CarModel + "\nMileage: " + Car.vehicles[i].CarMileage
                    + "\nYear: " + Car.vehicles[i].CarYear + "\n\n");

    displayLabel.Text = sb.ToString();
    i++;
}

how would I highlight the mileage attribute in the appended string builder so that either the background of that particular section of text is a different colour or the actual text is.

kara
  • 3,205
  • 4
  • 20
  • 34
dusk42
  • 21
  • 4
  • You'd need to use a `RichTextBox` instead of a `Label` to have parts of the text coloured. – Enigmativity Apr 06 '19 at 09:01
  • And if I used a RichTextBox, how exactly do I highlight the attribute if I am adding it to the string builder like this: `Car.vehicles[i].CarMileage` – dusk42 Apr 06 '19 at 09:09
  • Or you could owner-draw the Label. – TaW Apr 06 '19 at 09:29
  • @dusk42 - You set the colour based on position after you've assigned the `.Text` property. It's a bit annoying. There's no markup that you can apply. – Enigmativity Apr 06 '19 at 09:37
  • i think you can do something like this displayLabel.BackColor = System.Drawing.Color.Green or Car.vehicles[i].CarColour; – jalil Apr 06 '19 at 12:22
  • _You set the colour based on position after you've assigned the .Text property._ Actually you select the portion you want to color and then set the SelectionColor. __Never__ directly set the Text property or you will mess up all previous formatting. – TaW Apr 06 '19 at 13:18

1 Answers1

1

I see a few different options. The answers to this question Multiple Colors in C# Label explain the first two options.

Option 1: Do not use your StringBuilder, and use a rich text box. Then loop through the properties and add them one at a time using the rtb_AppendText function in the provided link.

Option 2: Create a custom label control and override the OnPaint method. In the OnPaint method you can use MeasureText and DrawString to accomplish your goal.

Option 3: Create a user control with four different labels, this way you could control the color/font/appearance of each label, and in the long run gives you the most flexibility.

TaW
  • 53,122
  • 8
  • 69
  • 111
Kevin
  • 2,566
  • 1
  • 11
  • 12