简体   繁体   中英

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.

I have two .aspx pages and I want to pass an IP address from a datatable from one page to the other. When I do this, spaces get added that I don't want. The simple version of the code is this:

first .aspx page

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

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

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

Then use:

string 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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