QmunkE QmunkE - 2 months ago 14
C# Question

Is it possible to have Label.Image appear inside the padding region?

I'd like to be able to have a

Label
such that it appears something like

[Some bit of text here] [ICON]

i.e. the icon follows the text, fairly straightforward.

I don't know what the text will be at design time, so I have
AutoSize
set to true on the
Label
control, but this means the image just gets drawn on top of the text. If I add
Padding
to the right hand side, it doesn't behave as I want (a la CSS, where background images are drawn inside the padding region). Is it possible to do this in C# Winforms? Or am I going to have to measure the text and then change the control width myself?

Thanks.

EDIT: Just to be clear, I wasn't proposing two controls, one after the other. Rather, setting the
Label.Image
property and have it appear to one side of the label's text. Apparently this is just not built-in functionality for autosized labels which seems pretty weak.

Answer

I think you have to set the ImageAlign to right and TextAlign to left, then calculate the width manually,

int gap=10;
myLabel.AutoSize=true;
int autoWidth=myLable.Width;
myLabel.AutoSize=false;
myLabel.Width=autoWidth+gap+myLabel.Image.Width;