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

209 Views Asked by At

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.

3

There are 3 best solutions below

7
On

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();

0
On

You can use string.Replace if you just want to get rid of the spaces:

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

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