Nida Nida - 1 year ago 61
C# Question

Formatting of full address using c# code

I have written following lines of code for formatting of address

string Address1 = ds.Tables[0].Rows[0]["PhysicalAddressLine1"].ToString();
string Address2 = ds.Tables[0].Rows[0]["PhysicalAddressLine2"].ToString();
string Address1C;
string Address2C;

if (Address1 != "")
Address1C = Address1 + ", ";
Address1C = Address1;

if (Address2 != "")
Address2C = Address2 + ", ";
Address2C = Address2;

lblAdderssX1.Text = Address1C + Address2C;

string City = ds.Tables[0].Rows[0]["PhysicalAddressCity"].ToString();
string CityC;
if (City != "")
CityC = City + ", ";
CityC = City;

string Pin = ds.Tables[0].Rows[0]["PhysicalAddressPin"].ToString();

string State = ds.Tables[0].Rows[0]["JurisdictionX"].ToString();
string StateC;

if (State != "")
StateC = State + ", ";
StateC = State;

// string CountryC = ds.Tables[0].Rows[0]["CountryX"].ToString();

lblAddressX2.Text = CityC + StateC + Pin;

"<asp:Label ID="lblAdderssX1" CssClass="ProfileLabel" runat="server"> </asp:Label>
<asp:Label ID="lblAddressX2" CssClass="ProfileLabel" runat="server"> </asp:Label>"

Actually we want that the format should be like

"Physical Address1, Physical Address2, City, State, Pin"

if any of them is missing let's say Physical Address2 then address should be

"Physical Address1, City, State, Pin"

and if City is missing in the table then it should be like

"Physical Address1, Physical Address2, State, Pin"

and if Physical Address2, City, State, Pin are missing then the address should be like

"Physical Address1" and currently the above is placing , in this case. I am not able to handle this. Please help !!!

Also if nothing is available then the text should come like "Not Available"

Answer Source

I suppose you want to write it cleaner. Create List<string>

List<string> address = new List<string>();

string list = string.Join(", ", address.Where(x => !string.IsNullOrEmpty(x)));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download