This question already has answers here:
Removing extra commas from string after using String.Join to convert array to string (C#)
(9 answers)
Closed 8 years ago.
In my C# form I have address field in that i need to fill address that already DoorNo, Street, Area, Location are stored separately in Access Database. I used string concatenation to merge full address.
object row = CBL_Customer_Name.Properties.GetDataSourceRowByKeyValue(CBL_Customer_Name.EditValue) as object;
string getblocation = (row as DataRowView)["BLocation"].ToString();
string getbcity = (row as DataRowView)["BCity"].ToString();
string getbstate = (row as DataRowView)["BState"].ToString();
string getbcountry = (row as DataRowView)["BCountry"].ToString();
TXE_Invoice_Address.Text = (row as DataRowView)["BFlatNo"].ToString() + ", " + (row as DataRowView)["BPremises"].ToString() + "," + System.Environment.NewLine + (row as DataRowView)["BStreet"].ToString() + ", " + getloction(getblocation) + "," + System.Environment.NewLine + (row as DataRowView)["BArea"].ToString() + ", " + getcity(getbcity) + "," + System.Environment.NewLine + getstate(getbstate) + ", " + getcountry(getbcountry) + ".";
If user enter complete address then no problem in this above code. If he doesn't enter location or some other fields then am getting , , or blank space in the end of line.
How to solve this ? I need a perfect address in my address field if user leave 1 or 2 fields also.
Use .replace() to replace empty values by a custom text.
Example
TXE_Invoice_Address.Text = TXE_Invoice_Address.Text.Replace(", ,", ", ")
This code will remove all , , that may cause a strange adress format.
Try this: var newAddress = string.Join(", ",TXE_Invoice_Address.Text.Split(',').Where(x => !string.IsNullOrWhiteSpace(x)));
This will eliminate all empty spaces and rejoin to new a string.
Related
I have a query string which passes 6 parameters in C# as shown below
string url = "Report.aspx?Desc=" + Desc.SelectedValue + "&PON=" + PNumber.Text + "&InsNme=" + ins.ToUpper().ToString() + "&BackTy=" + cb.SelectedValue + "&StartDate=" + txtDate.Text + "&EndDate=" + txtTodate.Text + "&Name=" + nme;
string s = "window.open('" + url + "', 'popup_window', 'width=1500,height=800,left=200,top=150,resizable=yes');";
ClientScript.RegisterStartupScript(this.GetType(), "script", s, true);
Now, in the above string InsNme contains a value of John Patrice Joanne. Instead of complete value of InsNme Report.aspx contains just John. How to handle this?
The spaces in the name are breaking the URL.
If you want to do it yourself, replace spaces with %20. Otherwise a simple, but not anywhere near "good" technique is:
url = "Report.aspx?";
// for each name value pair ...
url += dataLabel + "=" + System.Web.HttpUtility.UrlEncode( dataChunk ) +"&";
The utility is preferred as it will take care of other, similar issues such as literal '&' in a name.
Check this answer for better solutions.
How to build a query string for a URL in C#?
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Settings: asp.net mvc web app, azure sql db, EF code-first project
I am trying to combine 3 strings and a short into one string as given below:
CompanyAddress = company.ZipCode.ToString() + " " + company.City + ", " + company.Street + " " + company.StreetNr
ZipCode is a short, all others are strings. Using this code in a controller action returns no records (and no error message when run). When I omit the ZipCode part I get all records.
I also have tried ToString(company.ZipCode) and without .ToString(). Gives a wiggle-line (does not compile) and when run no error message and no records in return, respectively.
Please help.
Additional info:
The code line is part of an api controller (see below), ZipCode is nullable.
When ZipCode is part of the code line, then the controller delivers null, otherwise it delivers a proper string.
var companies = UnitOfWork.GetAll<Company>();
var query = company in companies
where company.Activ == true
select new ActiveCompaniesViewModel
{
CompanyAddress = company.ZipCode.ToString() + " " + company.City + ", " + company.Street + " " + company.StreetNr
};
return query;
This has been answered before,
Problem with converting int to string in Linq to entities
I think this will be your solution,
select new ActiveCompaniesViewModel
{
CompanyAddress = (company.ZipCode == null ? "" : SqlFunctions.StringConvert((int)company.ZipCode) + " ") +
company.City + ", " +
company.Street + " " +
company.StreetNr
};
That worked (does not make sense to me though!):
CompanyAddress = SqlFunctions.StringConvert((decimal?)company.ZipCode) + " " + company.City + ", " +
company.Street + " " +
company.StreetNr,
I have some vehicle information that I want to send in an email.
I have all code working but spacing out the information is a problem. Each vehicle has a checklist and that checklist then gets emailed. So I loop through the list and get the defect and the comment.
foreach (var item in chkList.CheckItems)
{
if (item.Defect == true)
{
defect += string.Format("{0,-40} {1}\n", item.ItemTitle, item.Comment);
}
}
if (hasDefect == true)
{
Utils.ChecklistSendMail("Checklist", ToAddresses.Split(';'),
"Vehicle Reg: " + reg + "\n" +
"Checklist No: " + chkList.CheckListNo + "\n"+
"Date: " + ChecklistDate.ToShortDateString() + "\n" +
"Defects: Comments: " + "\n" +
defect);
}
Email then looks like this:
Vehicle Reg: XLZ 8194
Checklist No: 0
Date: 22/03/2016
Defects: Comments:
Vehicle Secure comment1
Brakes comment2
I want the defects and the comments to be displayed like this:
Defects: Comments:
Vehicle Secure comment1
Brakes comment2
Since Vehicle Secure is longer than Brakes the comment is being pushed further out. But is there a way to fix the string at a certain position no matter how long first word is?
EDIT
code now looks like this:
string defect = "";
string comment = "";
string aheading = "Defects:";
string bheading = "Comments:";
foreach (var item in chkList.CheckItems)
{
if (item.Defect == true)
{
defect += item.ItemTitle;
comment += item.Comment;
}
}
string result = aheading.PadRight(20, ' ') + bheading.PadRight(20, ' ') + Environment.NewLine +
defect.PadRight(20, ' ') + comment.PadRight(20, ' ') + Environment.NewLine;
But the output looks like this:
Defects: Comments:
Vehicle SecureBrakestest1test2
If you really want to do this with spaces, you need to determine the label with the most characters and how much space you want after that. This creates a total number of characters. From this, you subtract the number of characters of the label to get the number of spaces necessary to line up the value.
However, you could just use a <table> or some other html.
A potential, quick and dirty solution would require you to generate the html as a part of your code. I seriously advise against some homegrown html generator logic. Invariably the data involved in the email becomes more complex. This leads to mixing code that is getting the data for the template and building the html, which is painful to debug. Also there are plenty of html templating solutions out there. You'd really be just reinventing the wheel to take on technical debt and the maintenance of more code.
A better solution would be use something like MvcMailer and build an html template. You then pass the template and a context object to the engine to render the resultant html.
Try and use String padding with ' ' as char
public string PadRight(
int totalWidth,
char paddingChar)
This method would complete the length of the string with the chosen char. by specifying the max length of the string and replacing the remaining length with " " (space). you can always have the strings aligned.
Read more about PadRight or PadLeft
string Defects ="Example"
Defects.PadRight(20," ");
Result: "Example "
Edit : Example Code .Please have a look at this code and check what you are doing wrong
string aheading = "Defects:";
string bheading ="Comments:";
string b = "Vehicle Secure";
string bComment = "My Comment value";
string c = "Brakes";
string cComment = "My Comment value";
string result= aheading.Trim().PadRight(20,' ')+bheading.Trim().PadRight(20,' ')+ Environment.NewLine +
b.Trim().PadRight(20, ' ') + bComment.Trim().PadRight(20, ' ') + Environment.NewLine +
c.Trim().PadRight(20,' ')+cComment.Trim().PadRight(20,' ')+Environment.NewLine ;
Console.WriteLine(result);
Edit:Answer based on the code you Posted
string aheading = "Defects:";
string bheading = "Comments:";
string result = aheading.PadRight(20, ' ') + bheading.PadRight(20, ' ') + Environment.NewLine ;
foreach (var item in chkList.CheckItems)
{
if (item.Defect == true)
{
string result += item.ItemTitle.Trim().PadRight(20,' ') + item.ItemTitle.Trim().PadRight(20,' ') + Environment.NewLine ;
}
}
Console.WriteLine(result);
wassup guys im new to C# coding and i did a search but couldn't find exactly what im looking for. So i have a couple of text-boxes which holds string elements and integers
what i want to do is when these boxes are filled in i want to send a summary of the email to client/customer but the format is whats getting me.
(first, one) are strings equaling different text-boxes
my code is:
emailCompseTask.Body = first + one + Enviroment.NewLine +
second + two + Enviroment.NewLine
and so on problem is which i send thru email it shows something like this:
computer service25.00
instead of:
computer service 25.00
is there a way to add spacing to make this more presentable? or even a better way perhaps thanks in advance guys
try this :
emailCompseTask.Body = first + one + " "+ second + two ;
body takes as HTML input, check here for more spacing option.
I'm a bit confused, but you just want to add some spacing in the output? Just throw some spaces in there like you would another variable.
first + " " + one + Environment.NewLine
+ second + " " + two + Environment.NewLine;
You can use a table
string tableRow = #"<tr>
<td>{0}</td>
<td>{1}</td>
</tr>";
string htmlTable = #"<table>
{0}
</table>";
string rows = "";
// Can do this in a loop
rows += string.Format(tableRow, first, one);
rows += string.Format(tableRow, first, one);
emailComseTask.Body = string.Format(htmlTable, rows);
I'm looking for guidance can someone help me out?
I need to separate the value in duration into a whole number and the decimal.
EDIT: I have a textbox in one page. If someone enters 1.5 and it gets stored in duration, I would like to retrieve that in another page and I would like to store the whole number in a textbox and the decimal number will select a value from a dropdownlist based on the response.
Sorry I added duration twice by accident.
context.Response.Write(dr["Title"].ToString()
+ '|' + dr["CourseId"].ToString() + '|' + dr["duration"].ToString()
+ '|' + dr["Code"].ToString() + '|'
+ dr["Category"].ToString() + School.NewLine);
If the value you are trying to split is a number, try this:
decimal number = 12.34;
int wholePart = decimal.Truncate(number);
decimal fractionPart = number - wholePart;
If is is a string, CLandry's answer should work, duration[0] would be the whole part and duration[1] would be the fraction part.
var duration = dr["duration"].ToString().Split(CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator);
int durationWhole = Int32.Parse(duration[0]);
int durationDecimal = Int32.Parse(duration[1]);
Duration will be a string array. duration[0] is the part of the number before the decimal, and duration[1] is the part after.
The split is being done with the decimal separator of the culture using it, so it should work globally as well.
Based on the edit in your question, I've updated the answer to give you numerical results as well. Now you can use the numbers or strings as needed.
context.Response.Write(dr["Title"].ToString()
+ '|' + dr["CourseId"].ToString() + '|' + dr["duration"].ToString().Split('.')[0]
+ '|' + dr["duration"].ToString().Split('.')[1] + '|' + dr["Code"].ToString() + '|'
+ dr["Category"].ToString() + School.NewLine);
You could use Substrings and IndexOf:
{ context.Response.Write(
dr["Title"].ToString() + '|' +
dr["CourseId"].ToString() + '|' +
dr["duration"].ToString().Substring(0, dr["duration"].ToString().IndexOf(".")) + '|' +
dr["duration"].ToString().Substring(dr["duration"].ToString().IndexOf("."), dr["duration"].ToString().Length()) + '|' +
dr["Code"].ToString() + '|' +
dr["Category"].ToString() +
School.NewLine);
}