Nida Nida - 16 days ago 5
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 + ", ";
else
Address1C = Address1;

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



lblAdderssX1.Text = Address1C + Address2C;

string City = ds.Tables[0].Rows[0]["PhysicalAddressCity"].ToString();
string CityC;
if (City != "")
CityC = City + ", ";
else
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 + ", ";
else
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

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

List<string> address = new List<string>();
address.Add(ds.Tables[0].Rows[0]["PhysicalAddressLine1"].ToString());
address.Add(ds.Tables[0].Rows[0]["PhysicalAddressLine2"].ToString());
address.Add(ds.Tables[0].Rows[0]["PhysicalAddressCity"].ToString());
address.Add(ds.Tables[0].Rows[0]["JurisdictionX"].ToString());
address.Add(ds.Tables[0].Rows[0]["PhysicalAddressPin"].ToString());

string list = string.Join(", ", address.Where(x => !string.IsNullOrEmpty(x)));
Comments