如何在C#中使用ToString()后清除不需要的空格
本文关键字:清除 不需要 空格 ToString | 更新日期: 2023-09-27 18:19:34
我不确定这可能是Session而不是ToString()的问题。
我有两个.aspx页面,我想将数据表中的IP地址从一个页面传递到另一个页面。当我这样做时,会添加我不想要的空格。代码的简单版本是:
第一个.aspx页面
int num = DropDownList1.SelectedIndex;
DataView tempDV = SqlDataSource2.Select(DataSourceSelectArguments.Empty) as DataView;
Session["camera"] = tempDV.Table.Rows[num].ItemArray[2];
Response.Redirect("test.aspx");
test.aspx页面
string ipCamAdd = Session["camera"].ToString();
TextBox1.Text = "http://" + ipCamAdd + "/jpg/image.jpg?resolution=320x240";
我想打印的是
http ://ipadd/jpg/image.jpg?resolution=320x240
但是打印出来的是
http//ipaddress /jpg/image.jpg?resolution=320x240
我该怎么解决这个问题?
此外,我问了这个问题,希望有人能告诉我为什么会发生这种情况。抱歉犯了这个错误。
试试这个:
string ipCamAdd = Session["camera"].Trim().ToString();
对于有效的问题,会话["相机"]可能为空,请在代码中添加以下功能
static string ToSafeString(string theVal) { string theAns; theAns = (theVal==null ? "" : theVal); return theAns; }
然后使用:
string ipCamAdd=Session["camera"].ToSafeString().Trim();
如果只想去掉空格,可以使用string.Replace
:
TextBox1.Text = "http://" + (ipCamAdd ?? "").Replace(" ", "") + "/jpg/image.jpg?resolution=320x240";
在设置为会话之前修剪结果。
Session["camera"] = tempDV.Table.Rows[num].ItemArray[2].Trim();
似乎在SQL中,您的数据类型是char(*)
。如果您将数据类型转换为varchar
并重新输入数据,则不会获得任何额外的空格