Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Substring value retrieved from database in .NET / C#

I'm using the following to read out values from my database:

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

I was wondering. How do I reduce the value of "body" to just 0,20 characters?

Is there a Substring function I can use?

Many thanks

like image 627
michaelmcgurk Avatar asked Dec 18 '25 16:12

michaelmcgurk


2 Answers

Assuming that the body column contains a string 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 have to check for that before calling Substring.

Substring will throw an exception if the requested length of the substring is longer than the length of the actual string. That is why you have to use the minimum of the string length and the desired substring length.

If you do this a lot you can create an extension method:

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));
  }

}

You can use it like this:

((String) reader["body"]).Truncate(20)
like image 141
Martin Liversage Avatar answered Dec 20 '25 07:12

Martin Liversage


You can do that as shown below. Make sure to check for 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>";   
        }
like image 32
Amitabh Avatar answered Dec 20 '25 07:12

Amitabh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!