C# Winforms bold treeview node doesn't show whole text - c#

I'm using the following code to make my treenodes bold:
Font font = new Font(tvQuestionSequence.Font, FontStyle.Bold);
foreach (QuestionnaireBuilder_Category cat in categories)
{
TreeNode node = new TreeNode();
node.Text = cat.Description;
node.Name = cat.Id.ToString();
node.NodeFont = font;
tvQuestionSequence.Nodes.Add(node);
}
But the text of the bold nodes is not displayed correctly. The last letter(s) are not shown. How come? And how to solve this problem?

I found this Post when searching through the web because I am facing the exact same problem.
However, appending a white space to the end of the node was not an option, and I found an alternative way that seems to fix the issue.
After setting my node font Bold, all I need to do is reset the node text with the same value.
Here is the Code Sample:
Font boldFont = new Font(treeview.Font, FontStyle.Bold);
node.NodeFont = boldFont;
node.Text = node.Text;
It seems that the node is redrawn after changing the text, which is exactly what I wanted in the first place.

I've found that this is a Windows issue. A workaround for this problem is this:
In the form constructor set the font of the treeview to bold. When adding nodes which must not be bold, change the font to regular:
// Constructor of your form
public Form()
{
InitializeComponent();
Font font = new Font(tvQuestionSequence.Font, FontStyle.Bold);
tvQuestionSequence.Font = font;
}
// Add regular nodes (not bold)
Font font = new Font(tvQuestionSequence.Font, FontStyle.Regular);
TreeNode treeNode = new TreeNode();
treeNode.Text = "Foo";
treeNode.NodeFont = font;
TreeNode parent = tvQuestionSequence.Nodes.Find("parent", true);
parent.Nodes.Add(treeNode);

Simply use treeView.BeginUpdate() before you bold the node then treeView.EndUpdate() after you've bolded the node.

This is a known Windows bug.
The simple solution is just to append an extra space character at the end of your strings. The space character will not be visible, but it will increase the number of pixels needed to draw the string, so the entire string will be visible.

This is all not helping for me.
What DID the trick is making the font a little bigger and bold at DESIGN time.
(In the Properties window)
So make sure you define the treeview with big enough font, then later you can add nodes with smaller font. They will fit.

I do agree with the solution provided. I just want to add to it to shed a little more light on what the problem is.
The treeview has its own font which determines the width of items at the root level. That compensates for the fact that there is only an item height property available and no item width property.
The solution to your problem is to determine what the font of your root node should be, then set the tree to that same font. You can do that at design time also.
Hope that helps someone.

A workaround for this problem is this:
Set the defaul font of treeview to bold in the properties.
And chnage to not bold when you need.

I do the following, I set the DrawNode Event to call, it sets the node to bold and removes the highlighted colour.
You can set any colour you like using the first parameter of the e.Graphics.FillRectangle function.
private void SetNodeBoldWhenSelected(object sender, DrawTreeNodeEventArgs e)
{
if (e.Node == null) return;
var font = e.Node.NodeFont ?? e.Node.TreeView.Font;
if (e.Node.IsSelected)
{
font = new Font(font, FontStyle.Bold);
}
var bounds = new Rectangle( e.Bounds.X,e.Bounds.Y,e.Bounds.Width+20,e.Bounds.Height);
e.Graphics.FillRectangle(SystemBrushes.ControlDarkDark, bounds);
TextRenderer.DrawText(e.Graphics, e.Node.Text, font, bounds, SystemColors.HighlightText, TextFormatFlags.GlyphOverhangPadding);
}
Now when I select a node I get 20 pixels more space, for my font, this works well, one can calculate the "real" size needed but there is no specification stating it needs to do this but you can use Graphics.MeasureString if you feel you need to do that.

Very easy and works fine
treeView1.SelectedNode.NodeFont = new System.Drawing.Font(treeView1.SelectedNode.TreeView.Font, treeView1.SelectedNode.TreeView.Font.Style | FontStyle.Bold);
this.treeView1.SelectedNode.Text += string.Empty;

I realize this is an old thread and it may have been answered. I just ran across this problem as I'm learning to use TreeViews. What worked for me was changing the font size for the entire TreeView to the same size, or bigger than the font of the level you want to bold. The default font size is 8.something. I changed mine to 10, which was the size I wanted my nodes, and the truncating was gone.

What worked for me: Hooking into the load event in the Control's constructor and tweaking the node as explained in BlunT's answer.
public MyControl()
{
InitializeComponent();
_head = new TreeNode();
this.Load += (s, e) =>
{
trvParts.Nodes.Clear();
_head.NodeFont = new Font(trvParts.Font, FontStyle.Bold);
trvParts.Nodes.Add(_head);
_head.Text = "Node Name";
};
}

It's in vb.Net however the solution to re-enter the value of the TEXT field gets around this nicely. As in:
With myNode
Dim myText As String = .Text 'capture the text
.NodeFont = New Font(<name of your treeview>.Font, FontStyle.Bold)
.Text = myText 'reset the text to the original value
End With

Based on MSDN Library, try change your code to:
Font font = new Font(tvQuestionSequence.Font, FontStyle.Bold);
foreach (QuestionnaireBuilder_Category cat in categories)
{
TreeNode node = new TreeNode();
node.Text = cat.Description;
node.Name = cat.Id.ToString();
node.NodeFont = font;
tvQuestionSequence.BeginUpdate(); //added newline here <--
tvQuestionSequence.Nodes.Add(node);
tvQuestionSequence.EndUpdate(); //added newline here <--
}
It work for me

Related

c# How to get standard font style object in Word

I'm inserting variable text from a *.html file into a Word document and have to adapt the font(name and size) of the inserted text to the rest of the document.
I have a working solution but I don't like the way I did it, so I'm searching another way to get the standard font name and size from Word application.
Another problem is that NameLocal can be in different languages. So I also need another way to find the Headers. I already tried Style.Type but it has always value "1"
My code so far:
foreach (Word.Style style in Globals.ThisAddIn.Application.ActiveDocument.Styles)
{
if (style.NameLocal.Equals("Normal")) // find correct style object
{
float size = style.Font.Size;
string font = style.Font.Name;
foreach (Word.Paragraph paragraph in Globals.ThisAddIn.Application.ActiveDocument.Paragraphs)
{
if (paragraph.Range.get_Style().NameLocal.Contains("Heading")) // find all headers
{
paragraph.Range.Font.Size = size;
paragraph.Range.Font.Name = font;
}
}
break;
}
}
The reason why I'm not simply changing the style is so the headers are still marked as headers.
I'm pretty clueless atm
For built-in styles, the Word object model provides the enumeration WdBuiltinStyle. Using this instead of a string value (the local name of a style) makes specifying a style language-independent. In addition, the built-in styles will always be present in a document so there's no need to loop the Styles collection of a document to get a particular style.
So, for example:
Word.Document doc = Globals.ThisAddin.Application.ActiveDocument;
Word.Style style = doc.Styles[Word.WdBuildinStyle.wdStyleNormal];
float size = style.Size;
string font = style.Font.Name;
foreach (Word.Paragraph paragraph in doc)
{
if (paragraph.Range.get_Style() = Word.WdBuildinStyle.wdStyleHeading1)
{
paragraph.Range.Font.Size = size;
paragraph.Range.Font.Name = font;
}
}

DataGridView - Suppress all word wrapping

I'm trying to implement a DataGridView that has smaller cell width than autosize does.
If you look really close at a autosized cell you'll notice that there is still some space that is not used to actually display the cell's content.
That's why I started to measure the content's width by myself via TextRenderer and then manually set the column's width.
The initial problem was that a "A" was displayed as "A..." long before the cell was actually "filled". The reason for that was cell.Style.WrapMode set to "nonSet". I was quite happy that DataGridViewTriState.True did work for that "A"-example.
But now I just noticed that if the String has multiple words ("A, B") the DataGridView tries to display the content to several lines long before the cell is actually "filled".
What I'm now looking for is either a way to delete that "padding" of the cell's content or fully suppress the word wrapping on a certain cell/column (= single line without the String's cut off).
Additionally I should admit that there are no hidden blanks on that Strings so trim has no effect at all.
Edit:
I randomly stumbled upon some colleagues code that seems to do kind of what I'm searching.
StringFormat format = new StringFormat(StringFormatFlags.NoClip);
The documentation says that strings have some rectangle around them that is bigger than the string itself. If the rectangle sticks out of the writeable area the string is wrapped. That code snippet suppresses that (default) behaviour.
The only problem is that this solution only seems to work for drawing strings. I didn't find a possibility to assign a stringformat object to a string.
Try This Code
dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.DisplayedCells;
dataGridView1.DefaultCellStyle.WrapMode to DataGridView1TriState.True
Hope it helps you
Can you Try this code. That is working in my condition.
private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.Value == null)
return;
var s = e.Graphics.MeasureString(e.Value.ToString(), dataGridView1.Font);
if (s.Width > dataGridView1.Columns[e.ColumnIndex].Width)
{
using (
Brush gridBrush = new SolidBrush(this.dataGridView1.GridColor),
backColorBrush = new SolidBrush(e.CellStyle.BackColor))
{
e.Graphics.FillRectangle(backColorBrush, e.CellBounds);
e.Graphics.DrawString(e.Value.ToString(), dataGridView1.Font, Brushes.Black, e.CellBounds, StringFormat.GenericDefault);
dataGridView1.Rows[e.RowIndex].Height = (int)(s.Height * Math.Ceiling(s.Width / dataGridView1.Columns[e.ColumnIndex].Width));
e.Handled = true;
}
}
}

C# TreeView OnDrawNode is working slow and creating artifact

I am working on a custom C# TreeView and I would like to do some custom draw to highlight the keywords appear in the name of nodes.
I did :
DrawMode = TreeViewDrawMode.OwnerDrawText;
in the constructor of the custom TreeView and override the OnDrawNode:
protected override void OnDrawNode(DrawTreeNodeEventArgs e)
{
if (!e.Node.IsVisible) { return; }
if (e.Node.Bounds.IsEmpty) { return; }
e.DrawDefault = false;
...draw calls...
But it worked strangely after I coded like this, the perceived behaviors include:
OnDrawNode being call on the child nodes which is not expanded and invisible
When the content of the TreeView updates, the user would see the old content and new content at the same time overlapping with each other. The old content would disappear not until about half second or longer.
The rendering speed is much slower than the original draw call.
Another modification I did is the code snippet I found here to suppress the flickering happens when the TreeView is updating:
http://dev.nomad-net.info/articles/double-buffered-tree-and-list-views
But it seems not directly related to the problem since I can still see the text overlapping after removing it.
I wonder if anyone have any idea about this issue?
Any thought would be appreciated.
Thank you.
edit:
The content of the OnDrawNode is like:
string pattern = keyword;
if (!string.IsNullOrWhiteSpace(pattern))
{
Regex regularExpressionnew = Regex(pattern);
Match match = regularExpression.Match(e.Node.Text);
while (match.Success)
{
CaptureCollection captureCollection = match.Groups[0].Captures;
foreach (Capture capture in captureCollection)
{
int highlightStartIndex = capture.Index;
int highlightEndIndex = capture.Index + pattern.Length;
e.Graphics.FillRectangle(nodeHightLightColor, GetTextBoundsBetweenIndex(e.Graphics, e.Node.Text, highlightStartIndex, highlightEndIndex, e.Bounds));
}
match = match.NextMatch();
}
Brush drawBrush = new SolidBrush(Color.Black);
e.Graphics.DrawString(e.Node.Text, Font, drawBrush, e.Bounds);
GetTextBoundsBetweenIndex is essentially calculating the square area covering the characters between highlightStartIndex and highlightEndIndex.
But the lag and overlap would happen event the regular expression is commented out and only the text rendering left.

Remove FontStyle Bold from a Control's Font

I feel like a real noob posting this, but I can't seem to find anything for this...
I have a control that I'm basically trying to toggle the fontstyle between bold and not bold. This should be simple...
However, you can't acccess the Control.Font.Bold property as it is read only, therefore, you need to change the Font property.
To make it bold, I just do this:
this.btn_buttonBolding.Font = new Font(this.btn_buttonBolding.Font, FontStyle.Bold);
Not ideal, but it works. However, how do I go about removing this bold style (once it is bold already)?
I looked hard for duplicates; closest I could find was this, but it doesn't quite answer my situation:
Substract Flag From FontStyle (Toggling FontStyles) [C#]
And this which gives how to set it, but not remove it: Change a font programmatically
Am I missing a simple constructor for the font that could do this? Or am I just missing something easier?
I know this is a bit old, but I was faced with the exact same problem and came up with this:
Font opFont = this.btn_buttonBolding.Font;
if(value)
{
this.btn_buttonBolding.Font = new Font(opFont, opFont.Style | FontStyle.Bold);
}
else
{
this.btn_buttonBolding.Font = new Font(opFont, opFont.Style & ~FontStyle.Bold);
}
The magic is in the "~" which is the bitwise NOT. (See the MSDN KB article "~Operator")
VB.NET version:
Dim opFont As Font = me.btn_buttonBolding.Font
If (value)
me.btn_buttonBolding.Font = new Font(opFont, opFont.Style Or FontStyle.Bold)
Else
me.btn_buttonBolding.Font = new Font(opFont, opFont.Style And Not FontStyle.Bold)
End if
The FontStyle enum contains 5 distinct values.
The one that reset your previous set is FontStyle.Regular
Regular Normal text.
Bold Bold text.
Italic Italic text.
Underline Underlined text.
Strikeout Text with a line through the middle.
It's a bitwise enum where Regular is 0. So setting this value alone reset all other flags
Try this:
private void btn_buttonBolding_Click(object sender, EventArgs e)
{
var style = btn_buttonBolding.Font.Bold ? FontStyle.Regular : FontStyle.Bold;
btn_buttonBolding.Font = new Font(this.Font, style);
}

WPF RichTextBox appending coloured text

I'm using the RichTextBox.AppendText function to add a string to my RichTextBox. I'd like to set this with a particular colour. How can I do this?
Just try this:
TextRange tr = new TextRange(rtb.Document.ContentEnd,­ rtb.Document.ContentEnd);
tr.Text = "textToColorize";
tr.ApplyPropertyValue(TextElement.­ForegroundProperty, Brushes.Red);
If you want, you can also make it an extension method.
public static void AppendText(this RichTextBox box, string text, string color)
{
BrushConverter bc = new BrushConverter();
TextRange tr = new TextRange(box.Document.ContentEnd, box.Document.ContentEnd);
tr.Text = text;
try
{
tr.ApplyPropertyValue(TextElement.ForegroundProperty,
bc.ConvertFromString(color));
}
catch (FormatException) { }
}
This will make it so you can just do
myRichTextBox.AppendText("My text", "CornflowerBlue");
or in hex such as
myRichTextBox.AppendText("My text", "0xffffff");
If the color string you type is invalid, it simply types it in the default color (black).
Hope this helps!
Be Aware of TextRange's Overhead
I spent a lot of time tearing my hair out, because TextRange wasn't fast enough for my use-case. This method avoids the overhead. I ran some barebones tests, and its faster by a factor of ~10 (but don't take my word for it lol, run your own tests)
Paragraph paragraph = new Paragraph();
Run run = new Run("MyText");
paragraph.Inlines.Add(run);
myRichTextBox.Document.Blocks.Add(paragraph);
Credit
Note: I think most use cases should work fine with TextRange. My use-case involved hundreds of individual appends, and that overhead stacks up.
Just a complete example which mixes original question with previous remark from Tony
var paragraph = new Paragraph();
var run = new Run(message)
{
Foreground = someBrush
};
paragraph.Inlines.Add(run);
myRichTextBox.Document.Blocks.Add(paragraph);
Now, it is fast and coloured :)
Note that (unlike the TextRange solution) this solution also solved me a line break issue occurring at the first line of the RichTextBox.
I ended up synthesising Omni and Kishores' answers and creating an extension method as so:
public static void AppendText(this System.Windows.Controls.RichTextBox box, string text, SolidColorBrush brush)
{
TextRange tr = new TextRange(box.Document.ContentEnd, box.Document.ContentEnd);
tr.Text = text;
tr.ApplyPropertyValue(TextElement.ForegroundProperty, brush);
}
Which can be called as so:
MyTextBox.AppendText("Some Text\n", Brushes.Green);
the above single line answer:-
myRichTextBox.AppendText("items", "CornflowerBlue")
is not working.The correct way it should be writen is (i am using VS 2017) :-
Dim text1 As New TextRange(myRichTextBox.Document.ContentStart, myRichTextBox.Document.ContentEnd)
myRichTextBox.AppendText("items")
text1.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.CornflowerBlue)

Categories

Resources