Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bold treeview node truncated - official fix will not work because code in constructor

I am experiencing the well known issue where after setting a TreeNode's font to bold, the text of the TreeNode gets truncated. However, I believe I have found a situation in which all of the commonly accepted "fixes" fail to work.

Common Solution: http://support.microsoft.com/kb/937215

node.NodeFont = new System.Drawing.Font(node.NodeFont, FontStyle.Bold);
node.Text += string.Empty;

Variation 1: C# Winforms bold treeview node doesn't show whole text (see BlunT's answer)

node.NodeFont = new System.Drawing.Font(node.NodeFont, FontStyle.Bold);
node.Text = node.Text;

Variation 2: http://social.msdn.microsoft.com/Forums/en/csharpgeneral/thread/acb877a6-7c9d-4408-aee4-0fb7db127934

node.NodeFont = new System.Drawing.Font(node.NodeFont, FontStyle.Bold);
treeView1.BackColor = treeView1.BackColor;      

Scenario In Which Above Fixes Do Not Work:

If the code that sets the node to bold is in the constructor (either of a form or, in this case, a user control), the fixes will not work:

public partial class IncidentPlanAssociations : UserControl
{
    public IncidentPlanAssociations()
    {
        InitializeComponent();

        TreeNode node = new TreeNode("This is a problem.");
        node.NodeFont = new Font(treeView1.Font, FontStyle.Bold);
        treeView1.Nodes.Add(node);

        // This does not fix problem
        node.Text += string.Empty;

        // This does not fix problem
        node.Text = node.Text;

        // This does not fix problem
        treeView1.BackColor = treeView1.BackColor;

    }
}

However, if I place any of these three "fixes" in code behind a button and click it after everything runs it will work just fine. I'm sure this is something to do with when the treeview is initially drawn or something, but I'm trying to figure out a good way around it. Any suggestions?

like image 495
Joe DePung Avatar asked Oct 23 '12 17:10

Joe DePung


1 Answers

Thanks @Robert Harvey for the assistance.

In case anyone is experiencing a similar issue, the workaround here was to move the code from the Constructor to the User Control's Load event. Any of the three variations above then work.

I personally chose to go with:

private void IncidentPlanAssociations_Load(object sender, EventArgs e)
{
    TreeNode node = new TreeNode("This is no longer a problem.");
    node.NodeFont = new Font(treeView1.Font, FontStyle.Bold);
    treeView1.Nodes.Add(node);

    // This fixes the problem, now that the code 
    //      is in the Load event and not the constructor
    node.Text = node.Text;

}

The code just needed to be in the Load event and not in the constructor for this workaround to the well-known bug to work correctly for me.

like image 184
Joe DePung Avatar answered Oct 11 '22 08:10

Joe DePung