Substring value retrieved from a database in .NET / C #

I use the following to read values ​​from my database:

    while (reader.Read())
    {
        newsLabel.Text += "<div style='float:left;'>" + reader["body"] + "</div>";
    }

It was interesting to me. How to reduce the value of "body" to 0.20 characters?

Is there a subscript function that I can use?

Many thanks

+3
source share
6 answers

You can do this as shown below. Be sure to check out DbNull.

while (reader.Read()) 
        {
            string body = reader["body"] is DBNull ? "" : Convert.ToString(reader["body"]);

            if(body.Length > 20)
              body = body .Substring(0, 20);

            newsLabel.Text += "<div style='float:left;'>" + body  + "</div>";   
        }
+2
source

Assuming the column bodycontains a row, you can truncate it like this:

var body = (String) reader["body"];
var truncatedBody = body.Substring(0, Math.Min(body.Length, 20));

If the column can be null, you will need to check it before calling Substring.

Substring , . .

, :

public static class StringExtensions {

  public static String Truncate(this String str, Int32 length) {
    if (length < 0)
      throw new ArgumentOutOfRangeException("length");
    if (str == null)
      return String.Empty;
    return str.Substring(0, Math.Min(str.Length, length));
  }

}

:

((String) reader["body"]).Truncate(20)
+4

, Substring #

newsLabel.Text += "<div style='float:left;'>" + Convert.ToString( reader["body"]).SubString(0,20) + "</div>";

MSDN

+1
reader["body"].ToString().Substring(0,20);
+1
while(reader.Read()) 
{
    string readBody = reader["body"] as string;
    if(!string.IsNullOrEmpty(readBody))
    {
        if(readBody.Length > 20)
           newsLabel.Text = string.Format("{0}<div style='float:left;'>{1}</div>",
                                     newsLabel.Text, readBody.Substring(0,20));
        else
           newsLabel.Text = string.Format("{0}<div style='float:left'>{1}</div>",
                                     newsLabel.Text, readBody);
    }
}
0

All Articles