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?
开发者_如何学GoMany thanks
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)
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>";
}
reader["body"].ToString().Substring(0,20);
In addition to all the answers here, you could also push this substring back to the database - as SQL has a SubString function.
e.g. if you were using Linq 2 Sql then the c# SubString method can get translated back to a SQL operation within the database - http://weblogs.asp.net/dixin/archive/2010/04/15/understanding-linq-to-sql-4-data-retrieving-via-query-methods.aspx
Whether this is optimal or required depends on your application and database.
Hope that helps
Stuart
yes you can do it in Substring
in C#
newsLabel.Text += "<div style='float:left;'>" + Convert.ToString( reader["body"]).SubString(0,20) + "</div>";
read MSDN Link
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);
}
}
精彩评论