简体   繁体   English

在C#中使用ToString()后如何摆脱不需要的空格?

[英]How to get rid of unwanted spaces after using ToString() in C#?

This might be a problem with Session and not ToString(), I'm not sure. 我不确定这可能是Session而不是ToString()的问题。

I have two .aspx pages and I want to pass an IP address from a datatable from one page to the other. 我有两个.aspx页,我想将数据表中的IP地址从一页传递到另一页。 When I do this, spaces get added that I don't want. 当我这样做时,会添加不需要的空格。 The simple version of the code is this: 代码的简单版本是这样的:

first .aspx page .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 page test.aspx页

string ipCamAdd = Session["camera"].ToString();

TextBox1.Text = "http://" + ipCamAdd + "/jpg/image.jpg?resolution=320x240";

what I want to print is 我要打印的是

http ://ipadd/jpg/image.jpg?resolution=320x240

but what prints out is 但是打印出来的是

http//ipaddress      /jpg/image.jpg?resolution=320x240

how can I fix this? 我怎样才能解决这个问题?

Also, I asked this question hoping someone could tell me why this is happening as well. 另外,我问了这个问题,希望有人能告诉我为什么也会发生这种情况。 Sorry for the mistake. 对不起,这个错误。

Try this: 尝试这个:

string ipCamAdd = Session["camera"].Trim().ToString();

For the valid concern, Session["camera"] could be null, add function such as the following to your code 对于有效的关注,Session [“ camera”]可以为null,在您的代码中添加以下功能

  static string ToSafeString(string theVal) { string theAns; theAns = (theVal==null ? "" : theVal); return theAns; } 

Then use: 然后使用:

string ipCamAdd = Session["camera"].ToSafeString().Trim(); 字符串ipCamAdd = Session [“ camera”]。ToSafeString()。Trim();

如果只想摆脱空格,可以使用string.Replace

TextBox1.Text = "http://" + (ipCamAdd ?? "").Replace(" ", "") + "/jpg/image.jpg?resolution=320x240";

Trim the result before setting to session. 设置会话之前,请先修剪结果。

Session["camera"] = tempDV.Table.Rows[num].ItemArray[2].Trim();

Seems In SQL your data type is char(*) if you convert the data type to varchar and re enter data, you wont get any additional spaces 似乎在SQL中,如果将数据类型转换为varchar并重新输入数据,则您的数据类型为char(*) ,将不会获得任何其他空格

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM