Could someone tell me why I get the error "Operation failed:Index and lengt must refer to a location within the string Parameter:Length". It happened at this line: TheDataGridView.Rows[j].Cells[i].Value = tmpStr.Substring(0, 709);

                    tmpSize = g.MeasureString("Anything", tmpFont);
                    RowsHeight.Add(tmpSize.Height);

                    tmpSize = g.MeasureString(TheDataGridView.Rows[j].Cells[i].EditedFormattedValue.ToString(), tmpFont);
                    if (tmpSize.Width > 710)
                    {
                        string tmpStr = TheDataGridView.Rows[j].Cells[i].ToString();
                        TheDataGridView.Rows[j].Cells[i].Value = tmpStr.Substring(0, 709);
                        tmpSize = g.MeasureString(TheDataGridView.Rows[j].Cells[i].EditedFormattedValue.ToString(), tmpFont);
                        //tmpWidth = tmpSize.Width;

                        //MessageBox.Show(tmpStr);

                        //g.MeasureString(TheDataGridView.Rows[j].Cells[i]
                    }

The reason is because tmpString is less than 710 characters so it can not get a sub string with a length of 709 characters starting with the first one.

Try this:

string tmpStr = "This is a test.";

if (tmpStr.Length < 709)
{
    //MessageBox.Show("The string is too short.");
}
else
{
    string subStr = tmpStr.Substring(0, 709);
}

in line 4 you are getting the size of the string measured in (most likely) pixels. A single character occupies more than one pixel in width, so there aren't 709 characters available, but more than 709 pixels of width. If you are trying to get the longest string with less than 710 pixels of width you'd do something like

g.MeasureString(TheDataGridView.Rows[j].Cells[i].EditedFormattedValue.ToString(), tmpFont);

String str = TheDataGridView.Rows[j].Cells[i].EditedFormattedValue.ToString();

int p = str.Length;
while (g.MeasureString(str.Substring(0, p).Width, tmpFont) > 710) {
    p--;
}

str = str.SubString(0, p);

At the end of this code, 'str' would contain the longest string shorter than 710 pixels.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.