I am trying to remove the last 6 characters from item.Size because the data has a decimal place and 5 trailing 0s in the database.
sb.Append("<div>" + item.Size + " " + item.Units + " </div>");
ie. item.Size is displayed as 1.00000 and I need it to just be displayed as 1.
This is part of a StringBuilder, and as I'm new to coding, not even sure the right way to go about this.
sb.Append("<div>" + (int)item.Size + " " + item.Units + " </div>");
StringBuilder has the same formatting capabilities as String.Format when you use the AppendFormat method:
sb.AppendFormat("<div>{0:N0} {1} </div>", item.Size, item.Units);
The format string "N0" tells it to format the number with 0 decimal points. That assumes the item.Size is stored as a numerical type. If not, simply remove the part of the string you don't want:
sb.AppendFormat("<div>{0} {1}</div>", item.Size.Split('.')[0], item.Units);
Here I've used Split, assuming that the value is actually something like what you've shown in your example.
Better you use int.TryParse(or Int32.TryParse) method. because if item.Size is not convertible to int, then it wont give you any exception. you can use int or long according to your choice. So you can handle this in your code according to the if/else condition.
Sample Code:
int size;
string str = "";
if(int.TryParse(str, out size) == true)
{
}
else
{
}
Related
I'm trying to pad a textbox value with zeros and pass it to another page with Response.Redirect in asp.net webforms. I cannot get the number to be padded with zeros. If I enter 2 in the textbox it should display 000002 on the second page. Here's my code:
if (cmbSearchBy.Text == "Account Number")
{
var zeropadding = String.Format("{0:00000}", txtSearchKeyword.Text);
Response.Redirect("AccountTable.aspx?SearchBy=" + cmbSearchBy.SelectedValue + "&TableSelection=" + cmbSelectTable.SelectedValue + "&SearchTerm=" + zeropadding + "");
}
else
{
Response.Redirect("AccountTable.aspx?SearchBy=" + cmbSearchBy.SelectedValue + "&TableSelection=" + cmbSelectTable.SelectedValue + "&SearchTerm=" + txtSearchKeyword.Text + "");
}
Since the values are all strings, you don't need to use String.Format() like you would with numeric values. You can use the .PadLeft() method instead. Something like this:
var zeropadding = txtSearchKeyword.Text.PadLeft(6, '0');
This would pad the value with '0' on the left to a total width of 6. (Or simply return the string if it's already 6 characters or more.)
right now I am reading some lines from a .txt.
Lets say, a user enters his name and in the .txt will be saved "Logged in {username} on 13/04/2016 at 10:55 am".
(Just an example.)
Now I want to read the .txt and print only specific parts into a textbox.
Meaning, in the textbox shall appear "{Username} - 13/04/2016 - 10:55 am".
So far, I am able to read from the .txt and print the whole line.
private void button_print_results_Click(object sender, RoutedEventArgs e)
{
int counter = 0;
string actual_line;
System.IO.StreamReader file_to_read =
new System.IO.StreamReader("myText.txt");
while ((actual_line = file_to_read.ReadLine()) != null)
{
textBox_results.Text = textBox_results.Text +"\n"+ actual_line;
counter++;
}
file_to_read.Close();
}
Is there a way, to reach this without overwriting the whole file?
And no, I can't change the format how the names etc. are saved.
(I used them here for a better understanding, the actual lines I need to read/check are different and auto-generated).
I don't expect full working code, it would be just great if you could tell me for which commands I need to look. Been a long time since I last worked with c#/wpf and I never worked much with Streamreader...
Thanks
I think regular expressions is the best tool for what you're trying to achieve. You can write something like this:
Regex regex = new Regex("Logged in (?<userName>.+) on (?<loginTime>.+)");
while ((actual_line = file_to_read.ReadLine()) != null)
{
Match match = regex.Match(actual_line);
if (match.Success) {
string loginInfo = string.Format("{0} - {1}", match.Groups["userName"], match.Groups["loginTime"]);
textBox_results.Text = textBox_results.Text +"\n"+ loginInfo;
}
}
There are couple of possible solutions for this. One most straight forward way for your case would be to use Substring and Replace.
Since the earlier string is always Logged in (note the last space) and you simply want to get the rests of the string after the phrase, replacing only the preposition of time words (" on ", " at ") with dash (" - ") you could take advantage on that:
string str = "Logged in {username} on 13/04/2016 at 10:55 am";
string substr = str.Substring(("Logged in ").Length) //note the last space
.Replace(" on ", " - ")
.Replace(" at ", " - ");
In your implementation, this is how it look like:
while ((actual_line = file_to_read.ReadLine()) != null)
{
actual_line = actual_line.Substring(("Logged in ").Length) //note the last space
.Replace(" on ", " - ")
.Replace(" at ", " - ");
textBox_results.Text = textBox_results.Text +"\n"+ actual_line;
counter++;
}
(Note: the solution above assumes the {username} does not contain spaced preposition of time words - which would almost likely be the case for a {username})
You could split the actual_line String so you get an array of Strings. And then fill the Strings you want to show in the TextBox into it.
string[] values = actual_line.Split(' ');
textBox_results.Text = textBox_results.Text + "\n" + values[2] + " " + values[6] + " " + values[7];
The text in the TextBox for example is "{username} 10:55 am"
You can use Regex for better performances as #Dmitry-Rotay suggested in the previous comment, but if you jave a not-so-big file your loop+string manipulations is an acceptable compromise.
Always use Environment.NewLine instead of "\n", it's more portable.
while ((actual_line = file_to_read.ReadLine()) != null)
{
actual_line = actual_line
.Replace(("Logged in "), String.Empty)
.Replace(" on ", " - ")
.Replace(" at ", " - ");
textBox_results.Text = textBox_results.Text
+ System.Environment.NewLine
+ actual_line;
counter++;
}
I'm trying to create a STRING in JSON format. However, one of the fields (from my editing/removing ALL spaces) now leaves a line like "START":"13/08/1410:30:00". However, I want to add a space between the date and time? I have tried using the ToCharArray() method to split the string, but I am at a loss as to how to add a space between the DATE and TIME part of the string?
For Example, i am trying to get: "START":"13/08/14 10:30:00" but instead am getting
"START":"13/08/1410:30:00"
Please note. The length of the string before the space requirement will always be 17 characters long. I am using VS 2010 for NETMF (Fez Panda II)
If the split position is always 17, then simply:
string t = s.Substring(0, 17) + " " + s.Substring(17);
Obviously you will have to sort the numbers out, but thats the general idea.
String.Format("{0} {1}", dateString.Substring(0, 17), dateString.Substring(17, dateString.Length - 17);
Or you can use the StringBuilder class:
var finalString = new StringBuilder();
for (var i = 0; i < dateString.Length; i++){
if (i == 17)
finalString.Add(" ");
else
finalString.Add(dateString.ToCharArray()[i]);
}
return finalString.ToString();
If the date time format always the same you can use string.Insert method
var output = #"""START"":""13/08/1410:30:00""".Insert(17, " ");
Strings in .Net are immutable: you can never change them. However, you can easily create a new string.
var date_time = dateString + " " + timeString;
So I'm working on formatting a string and I need to line it up in a table, but this string has an undetermined number of characters. Is there anyway to have the string be in the same spot for each column? so far I have:
ostring += "Notes\t\t"
+ " : "
+ employees[number].Notes
+ "\t\t"
+ employees[number].FirstNotes
+ "\t\t"
+ employees[number].SecondNotes;
I use a similar fashion on the other rows, but they have a pre-determined number of digits, this however doesn't so I can't use the string modifiers like I would like.
Any ideas on what I need to do?
You can use String.PadRight() to force the string to a specific size, rather than using tabs.
When you are using String.Format item format has following syntax:
{ index[,alignment][ :formatString] }
Thus you can specify alignment which indicates the total length of the field into which the argument is inserted and whether it is right-aligned (a positive integer) or left-aligned (a negative integer).
Also it's better to use StringBuilder to build strings:
var builder = new StringBuilder();
var employee = employees[number];
builder.AppendFormat("Notes {0,20} {1,10} {2,15}",
employee.Notes, employee.FirstNotes, employee.SecondNotes);
You would first have to loop over every entry to find the largest one so you know hoe wide to make the columns, something like:
var notesWidth = employees.Max(Notes.Length);
var firstNotesWidth = employees.Max(FirstNotes.Length);
// etc...
Then you can pad the columns to the correct width:
var output = new StringBuilder();
foreach(var employee in employees)
{
output.Append(employee.Notes.PadRight(notesWidth+1));
output.Append(employee.FirstNotes.PadRight(firstNotesWidth+1));
// etc...
}
And please don't do a lot of string "adding" ("1" + "2" + "3" + ...) in a loop. Use a StringBuilder instead. It is much more efficient.
I have a textbox1 two and three. In textbox1 number zero, in two number one and in three number two and use this code
textBox4.Text = "" +
(int.Parse(textBox1.Text) +
(int.Parse(textBox2.Text +
(int.Parse(textBox3.Text)))));
but result is 012..you can have the entire amount, 3?
int result =
int.Parse(textBox1.Text) +
int.Parse(textBox2.Text) +
int.Parse(textBox3.Text);
textBox4.Text = result.ToString();
Try this
What's happening here is that the sum is being evaluated from left to right and this is causing a different type of addition to be performed than what you would expect. In C#, you can add two strings. If you add "foo" to "bar" then this will give you the string "foobar". If you add a string and a number together, then it will convert the number to a string and add the two strings together. So "foo"+13 yields "foo13".
So what's happening in your example is quite complicated. Starting from the inside, you have: int.Parse(textBox3.Text). This takes textBox3.Text which is "2" and converts it to the number 2. Next you do textBox2.Text + (int.Parse(textBox3.Text) which gets the string "1" and then adds the number 2 to it. This causes the number 2 to be converted to the string "2" and then adds "1"+"2", giving the string "12" as the answer since strings are added by joining them. Next you do int.Parse(textBox2.Text + (int.Parse(textBox3.Text)) which converts the string "12" to the number 12. You also do int.Parse(textBox1.Text) which gives the number 0. So at this point you're adding "" + 0 + 12. It does this from left to right, first adding "" to 0. This causes 0 to be converted to "0" and "" + "0" gives "0". Then we are adding "0" + 12. When we do this, 12 gets converted to "12" and "0"+"12" gives "012".
Without making big changes, you could get the correct result just by changing your parentheses. If the numbers were all added together before any of them are added to strings, then you'll get the correct result. We can accomplish this with parentheses.
textBox4 = "" + (int.Parse(textBox1.Text) + int.Parse(textBox2.Text) + int.Parse(textBox3.Text));
In short, it's really important to pay attention to what's happening in what order and what the types are because adding two strings is completely different from adding two numbers.
Put the " mark at the end that way it does the regular math first, then the string conversion.
You can you smth like this:
int sum=int.Parse(textBox1.Text) + int.Parse(textBox2.Text) + int.Parse(textBox3.Text);
textBox4.Text = String.Format("{0}",sum);
You have 2 problems here. The first one is the "" at the beginning. When you do the first +, textBox1.Text is first parsed, then converted to string again by the string concatenating operator. I'd prefer something like this:
textBox4.Text = (int.Parse(textBox1.Text) + int.Parse(textBox2.Text) + int.Parse(textBox3.Text)).ToString();
The second problem (the real one) is the fact that you miss a closing parenthesis after textBox2.Text. In this way you are first concatenating textBox1.Text ("1") and int.Parse(textBox2.Text).ToString() ("2"), and only at this point you parse the result. If the parenthesis were not missing your code would give "3" and not "012"