日期:2014-05-20  浏览次数:20894 次

asp.net(C#)读出数据库显示空格问题!!!!
代码如下:
public   void   tijiao(Object   sender,CommandEventArgs   e)
    {
        if(Page.IsValid)
{
string   neirong;
neirong=nr.Text.Replace( "\0 ", "   ");
neirong=nr.Text.Replace( "\n ", " <br> ");
//neirong=Server.HtmlEncode(nr.Text);
        string   sqlstring= "insert   into   news(lx,bt,zz,nr,ycc)   values( ' "+showlx.Text+ " ', ' "+bt.Text+ " ', ' "+zz.Text+ " ', ' "+neirong+ " ', ' "+ycc.Text+ " ') ";
SqlCommand   comm=new   SqlCommand(sqlstring,conn);
comm.ExecuteNonQuery();
Response.Write( " <script   language=javascript> alert( '新闻发布成功! '); </ "+ "script> ");
bt.Text= " ";
zz.Text= " ";
ycc.Text= " ";
nr.Text= " ";
}
else
{
Response.Write( " <script   language=javascript> alert( '新闻内容格式不符,请检查! '); </ "+ "script> ");
}
    }
我想把输入的内容空格和换行原样输出!用 "   "和 " <br> "进行转义字符的替换,结果换行倒是能做到,就是空格始终不行~特别的文字开头前的空格死都不显示!文字中间有空格的话可以显示空一格(不管空多少,都是显示空一格~),该怎么弄啊!在线等啊!!!请各位高手指点迷津~感激万千啊~

------解决方案--------------------
在插入数据前转换:

if(Page.IsValid)
{
string neirong;
neirong=nr.Text.Replace( "\0 ", " ");
neirong=nr.Text.Replace( "\n ", " <br> ");
//neirong=Server.HtmlEncode(nr.Text);
string sqlstring= "insert into news(lx,bt,zz,nr,ycc) values( ' "+Output(showlx.Text)+ " ', ' "+Output(bt.Text)+ " ', ' "+Output(zz.Text)+ " ', ' "+Output(neirong)+ " ', ' "+Output(ycc.Text)+ " ') ";

然后,Output改为:
public static string Output(string inputStr)
{
//构造临时字符串数组
StringBuilder retVal = new StringBuilder();
if(inputStr != String.Empty)
{
for (int i = 0; i < inputStr.Length; i++)
{
switch (inputStr[i])
{
case ' " ': retVal.Append( "&quot; "); break;
case '& ': retVal.Append( "&amp; "); break;
case ' < ': retVal.Append( "&lt; "); break;
case '> ': retVal.Append( "&gt; "); break;
case ' ': retVal.Append( "&nbsp; "); break;
case '\t ': retVal.Append( "&nbsp;&nbsp: "); break;
case '\r ': retVal.Append( " <br> "); break;
default: retVal.Append(inputStr[i]); break;
}
}
}
return retVal.ToString();