Programmatically adding Label to Windows Form (Length of label?) - c#

In my code, i create a label with the following:
Label namelabel = new Label();
namelabel.Location = new Point(13, 13);
namelabel.Text = name;
this.Controls.Add(namelabel);
The string called name is defined before this, and has a length of around 50 characters. However, only the first 15 are displayed in the label on my form. I tried messing with the MaximumSize of the label but to no avail.

Try adding the AutoSize property:
namelabel.AutoSize = true;
When you place a label on a form with the design editor, this property defaults to true, but if you create the label in code like you did, the default is false.

Try the property AutoSize = true;
MSDN refs
Another way is using the MeasureString method of the Graphics class
Graphics e = nameLabel.CreateGraphics();
SizeF stringSize = new SizeF();
stringSize = e.MeasureString(name, namelabel.Font);
nameLabel.Width = (int)stringSize.Width;

You could use the property Label.AutoSize to automatically adjust the width of your label to properly fit all the contents stored in Label.Text.
It's worth mentioning that when creating the label using the design editor this property defaults to true, but when you programmatically creates a label on your own the property defaults to false.
namelabel.AutoSize = true;
Of course you could also manually set the width of your label using something as the below to calculate the required width.
Graphics namelabel_g = namelabel.CreateGraphics ();
namelabel.Width = namelabel_g.MeasureString (
namelabel.Text, namelabel.Font
);
Documentation regarding the use of Label.AutoSize use can be found on msdn:
msdn.microsoft.com - Label.AutoSize Property (System.Windows.Forms)
Documentation regarding Graphics.MeasureString can be found here:
msdn.microsoft.com - Graphics.MeasureString Method (String, Font) (System.Drawing)

panel_saved.Controls.Add(
new Label
{
Location = new Point(1, 2),
Size = new System.Drawing.Size(43, 18),
BorderStyle = BorderStyle.FixedSingle,
Text = "yourdata"
});

Related

Changing a Label font to bold in code C#

I searched for this for A while but I couldn't find the answer, so I hope it's not a duplicate.
I have the following code:
this.Controls.Add(new Label { Location = new Point(10, 10),
AutoSize = true,
Name = "jobNumStatic",
Text = "Job Number:",
Font = new Font(jobNumStatic.Font, FontStyle.Bold) });
I'm trying to change the font to bold. But that code gives the error, The name 'jobNumStatic' does not exist in the current context. Is there any way to make the font bold here?
I also tried:
jobNumStatic.Font = new Font(jobNumStatic.Font, FontStyle.Bold) });
After declaring the Label, and it gives me the same error.
To use a Label's default font as prototype just use the static Label.DefaultFont property:
this.Controls.Add(new Label { Location = new Point(10, 10),
AutoSize = true,
Name = "jobNumStatic",
Text = "Job Number:",
Font = new Font(Label.DefaultFont, FontStyle.Bold) });
jobNumStatic is not a variable in your scope. You provide the string "jobNumStatic" at runtime for the Name property of the newly created Label, but that does not mean you magically have a variable with that name at compile-time.
If you need to access this Label later you may of course declare a member variable:
private Label jobNumStatic;
and assign the created instance to that variable:
jobNumStatic = new Label { Location = new Point(10, 10),
AutoSize = true,
Name = "jobNumStatic",
Text = "Job Number:",
Font = new Font(Label.DefaultFont, FontStyle.Bold) });
this.Controls.Add(jobNumStatic);
Simply use the code below:
Label1.Font = new Font(Font, Size, FontStyle.Bold);

Render CheckBox to Image for Tile

I want to display one or more CheckBoxes on a tile in my Windows Phone app. This works already for TextBlocks, but with a CheckBox it shows only the Text of the CheckBox and not the Checkmark itself.
This is a sample of my code:
public void CreateTile()
{
StackPanel panel = new StackPanel();
panel.VerticalAlignment = VerticalAlignment.Top;
panel.Margin = new Thickness(7.0, 7.0, 7.0, 0);
panel.Width = 336;
panel.Height = 336;
panel.Orientation = Orientation.Vertical;
// Create and add a CheckBox for each task
foreach (var task in _tasks)
{
TextBlock textBlock = new TextBlock();
textBlock.TextWrapping = TextWrapping.Wrap;
textBlock.Style = App.Current.Resources["PhoneTextLargeStyle"] as Style;
textBlock.Foreground = new SolidColorBrush(Colors.White);
textBlock.Text = task.Text;
CheckBox checkBox = new CheckBox();
checkBox.IsChecked = task.IsDone;
checkBox.Content = textBlock;
panel.Children.Add(checkBox);
}
Grid layoutRoot = new Grid();
layoutRoot.Background = new SolidColorBrush(Colors.Blue);
layoutRoot.Width = 336;
layoutRoot.Height = 336;
layoutRoot.Children.Add(panel);
layoutRoot.Measure(new Size(336, 336));
layoutRoot.Arrange(new Rect(0, 0, 336, 336));
layoutRoot.UpdateLayout();
// Render grid into bitmap
WriteableBitmap bitmap = new WriteableBitmap(336, 336);
bitmap.Render(layoutRoot, null);
bitmap.Invalidate();
// Save background image for tile to isolated storage
Uri backgroundImage = TileHelper.SaveTileImage(bitmap);
}
If I create a tile with a background image created by the method above, the tile will look like this:
As you can see the text is displayed but there is no checkmark/square before the text.
I personally like to use Segoe UI Symbol as the Font Family in such situations. This gives me the flexibility to use Text and Symbols together while not messing around too much with code / images. SUS has great modern icons (or characters if you may call them) that are very much Metroish, I'd say.
Just open up Charmap (Win + R and type in charmap) and in the Font Select -> Segoe UI Symbol. Now you can select any character you like and paste into Visual Studio Editor itself. Yes, it works!
The symbol may not display properly in the Editor itself but it will at Runtime
Here are some suggestions:
Here are the corresponding characters:
☑

✅

Don't worry about them not looking right HERE. They should when you follow the above steps.
You can always "hack" it by using images of checkbox controls. Did you try to show created control in UI? i.e. adding it to page? Just to see if your code is executed correctly.
Or another solution would be to use check mark character - http://www.fileformat.info/info/unicode/char/2713/index.htm
I'll try to replicate this problem in my test app since it is strange that it does not work.

Simple way of changing the font of a dynamically created ToolTip in C# windows forms?

Anyone have any idea on how to change the font of a dynamically created ToolTip? What I usually do in Label is
string arialUnicodeFontFace = "Arial Unicode MS";
Font unicodeFont = new Font(arialUnicodeFontFace, 8);
if (unicodeFont.Name != arialUnicodeFontFace)
unicodeFont = new Font("NSimSun", 8);
Label lbl = new Label();
lbl.Font = unicodeFont;
for (int x = 0; x < dt.Rows.Count; x++)
{
TextBox txt = new TextBox();
txt.Name = dt.Rows[x]["field_name"].ToString();
txt.Width = 200;
txt.Height = 10;
ToolTip tooltip = new ToolTip();
foreach (DataRow row in dtchnge.Rows)
{
if (dt.Rows[x]["definition"].ToString() == row["term"].ToString())
{
tooltip.SetToolTip(txt, row["language_based_term"].ToString());
}
}
The basic ToolTip is drawn by the Operating System, if you want to Customize it you will need to set the OwnerDraw property to true and handle the Custom Fonts in the Draw Event like the MSDN example shows.
From first Link:
Usually, a ToolTip is drawn by the operating system, but to customize
the appearance of the ToolTip you can set the OwnerDraw property to
true and handle the Draw event.
The IsBalloon property takes precedence over the OwnerDraw property.
If both are set to true, the ToolTip will be displayed using a balloon
window rather than an owner drawn window.

creating dynamic textbox in wpf according to location

I'm trying to create dynamically text box in WPF. It is very essential that I will have the flexibility to determine where the text box will be - in pixel level.
I have found many answers which use stackpanel to create "run-time" text box - but couldn't find how to construct it according to specified location.
the textbox has to be "word wrap" and I'm using a button click event to create the text box
this is the code for now, I really don't know which methods or properties will be helpful.
thanks :)
private void button1_Click(object sender, RoutedEventArgs e)
{
TextBox x = new TextBox();
x.Name = "new_textbox";
x.TextWrapping= TextWrapping.Wrap;
x.VerticalScrollBarVisibility=ScrollBarVisibility.Visible;
x.AcceptsReturn = true;
x.Margin = new Thickness(5, 10, 0, 0);
}
TextBox x = new TextBox();
x.Name = "new_textbox";
x.TextWrapping= TextWrapping.Wrap;
x.VerticalScrollBarVisibility=ScrollBarVisibility.Visible;
x.AcceptsReturn = true;
x.Margin = new Thickness(5, 10, 0, 0);
HouseCanvas.Children.Add(x);
Canvas.SetLeft(x, 20);
Canvas.SetTop(x, 20);
You probably want to place it in a Canvas, if you care about pixel placement of the textbox itself. You'll need to use x.SetValue(Canvas.LeftProperty, pixelX) [and .RightProperty, etc...] to get the position exactly right. Having not done this myself, I'd guess that you need to put the canvas in the right Z-order (on top), and make it transparent. There may also be issues with events, depending on the z-order. Good luck!
-Kev

Measuring a string vertically

I have a C# Winform application. In my form, I have a panel and in my panel, I have a label. The label gets created dynamically. I have the following code:
Label label1 = new Label();
label1.MaximumSize = new Size(400, 0);
label1.Location = new Point(posX, posY);
label1.Text = myText;
label1.AutoSize = true;
posY += 15;
Okay, everything is working. The text of the label automatically wraps after 400 pixels. The problem is, I need to create a second label, but how do I know what to set the the Location to? This new label need to be placed just below the first label and the first label might be 1 line long or 5 lines long. any help would be appreciated.
try to place your label within FlowLayoutPanel, set the FlowDirection to Top Down.
I would support the answer which provided by Int3, and another solution is to read the Height of label1 before set the Top of label2.
For example:
label2.Top = label1.Top + label1.Height + 10;
A GridLayout with some rows might be a solution

Categories

Resources