Search code examples
visual-studiowinformstooltipmultilinedesigner

How to create multi-line tooltips for a column header in a DataGridView in WinForms using the designer in Visual Studio (NOT code-behind)


I have Form1 with a DataGridView and a couple columns:

enter image description here

I'm trying to add a multi-line tool-tip to the Column1 header such that when you mouse over the "Column 1" text, the tool-tip is displayed. I can add a tool-tip to the header by opening the (Collections) item in the dataGridView's property page, selecting Column1, and adding text in the ToolTipText field as seen below: enter image description here

The problem is that my tool tip is very long (see picture) and I want it to wrap after a certain number of characters but no matter what I try, I can't insert a newline character into the ToolTipText property in the second image. It's always just one, long, continuous string of text.

My form is in both English and French and thus I am using resource files (.resx). I don't want to go in and manually edit the form's self-gerenated .resx files because I've had bad past experiences with manually editing .resx files that were generated by Visual Studio. It seems odd that I can't add a newline for the column's tooltip, but I can add a multi-line tooltip to the actual DataGridView by just hitting Enter (which does not work in the Column's case):

enter image description here

The only workaround I can think of is to create project level .resx files in the Properties section of my project and manually add the long tooltips into those files. Then, when the form loads at runtime I would explicitly assign the appropriate tool-tip text in the project level resource files to the column header. Something like this: dataGridView1.Column1.ToolTipText = Properties.MyToolTipStrings.ReallyLongToolTip

It should work with the project level resx files but it's really clunky and I'm thinking there must be a better way. Any suggestions?


Solution

  • You can use the following code to create create multi-line tooltips for a column header.

    public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private void Form1_Load(object sender, EventArgs e)
            {
                foreach (DataGridViewColumn column in dataGridView1.Columns)
                {
                    column.ToolTipText = Example.SpliceText(column.ToolTipText, 13);
                }
            }
        }
    
    public static class Example
    {
        public static string SpliceText(string text, int lineLength)
        {
            return Regex.Replace(text, "(.{" + lineLength + "})", "$1" + Environment.NewLine);
        }
    }
    

    Result: enter image description here