Question

I have the textbox that takes some string. This string could be very long. I want to limit displayed text (for example to 10 characters) and attach 3 dots like:

if text box takes value "To be, or not to be, that is the question:" it display only "To be, or..."

Or

if text box takes value "To be" it display "To be"

            Html.DevExpress().TextBox(
                    tbsettings =>
                    {
                        tbsettings.Name = "tbNameEdit";;
                        tbsettings.Width = 400;
                        tbsettings.Properties.DisplayFormatString=???
                    }).Bind(DataBinder.Eval(product, "ReportName")).GetHtml();
Was it helpful?

Solution 2

If you need to use a regex, you can do this:

Regex.Replace(input, "(?<=^.{10}).*", "...");

This replaces any text after the tenth character with three dots.

The (?<=expr) is a lookbehind. It means that expr must be matched (but not consumed) in order for the rest of the match to be successful. If there are fewer than ten characters in the input, no replacement is performed.

Here is a demo on ideone.

OTHER TIPS

You should use a Label control to display the data. Set AutoSize to false and AutoEllipsis to true. There are good reasons why a TextBox does not have this functionality, among which:

  • where are you going to store the truncated data?
  • if the user selects the text to edit or even copy, how do you handle that?

If you counter-argument is that the TextBox is read-only, then that is only more reason to re-think the control you are using for this.

Try this:

string displayValue = !string.IsNullOrWhiteSpace(textBox.Text) && textBox.Text.Length > 10
    ? textBox.Text.Left(10) + "..."
    : textBox.Text;

In an extension method:

public static string Ellipsis(this string str, int TotalWidth, string Ellipsis = "...")     
{
    string output = "";

    if (!string.IsNullOrWhiteSpace(str) && str.Length > TotalWidth)
    {
        output = output.Left(TotalWidth) + Ellipsis;
    }

    return output;
}

Using it would be:

string displayValue = textBox.Text.Ellipsis(10);
string textToDisplay = (inputText.Length <= 10) 
          ? inputText
          : inputText.Substring(0, 10) + "...";

Something like this?

static void SetTextWithLimit(this TextBox textBox, string text, int limit)
{
    if (text.Length > limit)
    {
        text = text.SubString(0, limit) + "...";
    }
    textBox.Text = text;
}

Show what you have tried and where you are stuck.

You don't need to use regex

string s = "To be, or not to be, that is the question:";
s = s.Length > 10 ? s.Remove(10, s.Length - 10) + "..." : s;
string maxStringLength = 10;
string displayStr = "A very very long string that you want to shorten";
if (displayStr.Length >= maxStringLength) {
    displayStr = displayStr.Substring(0, maxStringLength) + " ...";
}

//displayStr = "A very very long str ..."
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top