How do specify string format C# - c#

I have ID as 10 digits int ex: 1023456789 and I need to set DataGridView format to have there "102-34567 add. 89".
string.Format("###-##### add. ##") doesn't work.
So how to do that?

var result = 1023456789.ToString("###-##### add\\. ##");

If the ID length is always 10 characters,you can use String.Insert(Int32, String)
string s = "1023456789";
string resultt = s.Insert(3, "_").Insert(9, " add. "); //"102-34567 add. 89"

Related

C# Finding numerical value from specific string

I have a string of varying length that I am trying to retrieve a number from. The format of the string is always:
"some text lines
FC = 1234
more text here
and so on"
So I know the string of numbers comes after "FC = ", and I know it finishes at the next \n. How can I return this number (which will vary in size) into a new string?
Try the following code snippet:
var str = "some text lines \nFC = 1234\n more text here and so on";
Console.WriteLine(Regex.Match(str, #"\d+\.*\d*").Value);
Thanks to all. Think I managed to find a way with Regex, based on ScareCrow's suggestion:
string rgSearch = searchString + #"\d+\.*\d*";
FC = Regex.Match(diagnostics, rgSearch).Value;
FC = FC.Replace(searchString, ""); //Leaves the number only

C# Equal Tab Spacing

So I have a C# program that collects a list of customers. The list displays Customer ID, Customer Name, and Customer Phone Number. The list is shown in a multi-line text box. My issue is, a customer is allowed to either use first and last name, or first middle and last name, and when the list is displayed, if one of the customers only put a first and last name, the phone number is literally right next to the name instead of tabbed like the others. I will demonstrate what I mean below.
Notice how Bob Anthony's phone number is off compared to Mary and John? What would I use to make sure that every line has the same space in the tabs?
While some type of a data grid or list view would probably be more appropriate, if you want to keep it in string form you can use some of the composite formatting features in String.Format - notably the alignment flag:
string.Format("{0,-8} {1,-20} {2}", stuff)
The negative/positive indicates left/right alignment. Note that strings aren't truncated for you, you'll have to do that if you don't already know the max width.
You should get length of the longest item and add space after other items so that all of them be equal. By the way, I suggest you to use DataGridView for your application. Something like this:
dataGridView1.Rows.Add(3);
dataGridView1.Rows[0].Cells[0].Value = customer.ID;
dataGridView1.Rows[0].Cells[1].Value = customer.Name;
dataGridView1.Rows[0].Cells[2].Value = customer.Phone;
As everyone has said a DataGridView is recomendable and easy to use, instead of truncating the information or padding it the user can resize the columns. If you still want to do it that way then you have to get each customer and format it accordingly:
var text = new StringBuilder();
foreach (var customer in Customers)
{
var format = String.Format("{0} {1} {2}\n",
FormatField(customer.Id,6),
FormatField(customer.Name,20),
FormatField(customer.Phone,10) // Might need extra formating
);
text.Append(format);
}
And to format it:
private string FormatField(object field, int size)
{
var value = field.ToString();
if (value.Length == size)
return value;
return value.Length > size
? value.Substring(0,size)
: value.PadRight(size, ' ');
}
Depending on where you display it you will see some inconsistencies, like its not the same "view width" the characters "iii" and "MMM" even that they have the same length.

grab value from string in reverse order

I have file with txt content inside. Content is generated dynamicly and I want to read in reverse order, from end of file to the first matched semicolon, for example:
sad12e1sadsadsadasdasd12e2q3312sdadasdasdasqe21231122123123asd1asda;123456
so I want to grab this 123456 integer, ofcourse this is generated content with random int length.
If you have always the searched text at the end of the string and after a semicolon you could use
string.LastIndexOf(';');
for example
string test = "sad12e1sadsadsadasdasd12e2q3312sdadasdasdasqe21231122123123asd1asda;123456";
int pos = test.LastIndexOf(';');
if(pos >= 0)
string myText = test.Substring(pos+1);
What #Steve said, or just
string value = "sad12e1sadsadsadasdasd12e2q3312sdadasdasdasqe21231122123123asd1asda;123456";
string number = value.Split(';')[1];
though this doesn't handle the case where a semi-colon is missing.

C# string problems

I have a multiline text box called txtOutput that receives messages from the serial port. Each new message is a new line and represents a number from 1 to a maximum of 4 digits.
The method used to add the data in the multiline textbox is an append.
I have no problems with the above feature, it is working fine.
I would like to take the last message from the txtOutput and show it in textBox2 if the number is less than 1000, and in textbox3 if it is not. Then both text boxes would be updated.
I would appreciate if someone can give in an example especially in how to get the last message from the multiline textbox to a variable and how to update the textboxes if there is a new value.
You should save the last message (from the serial port) in a variable such as lastSerialMesssage. You can then convert this value to an integer and use a conditional statement to check if the value is smaller than 1000, if it is, set TextBox3 to the last serial message value, else set the value to TextBox2.
string lastSerialMessage = SerialPortMessage;
int lastMessageValue;
Int32.TryParse(lastSerialMessage, out lastMessageValue);
if (lastMessageValue < 1000)
{
TextBox3.Text = lastSerialMessage;
} else {
TextBox2.Text = lastSerialmessage;
}
http://msdn.microsoft.com/en-us/library/f02979c7.aspx
Thanks to all for the suggestions but as I mentioned in my comments, the suggested methods did not work because the content of the string was not accurate and I ended up receiving in the textBox 2 and 3 only part of the data and not always. I have solved the problem (thanks to other advices) using RegEx in this way:
if (txtOutput.Text.Length > 0)
{
MatchCollection mc = Regex.Matches(txtOutput.Text, #"(\+|-)?\d+");
if (mc.Count > 0)
{
long value = long.Parse(mc[mc.Count - 1].Value);
if (value < 1000)
{
textBox2.Text = value.ToString();
}
else
{
value = value - 1000;
textBox3.Text = value.ToString();
}
}
}
this is working fine and no piece of information are lost.Thanks again for your advices.

Error on int.parse

Input string was not in a correct format. At this line:
int total = 0;
total = int.Parse(TextBox2.Text) + int.Parse(TextBox4.Text) + int.Parse(TextBox6.Text) +
int.Parse(TextBox8.Text) + int.Parse(TextBox10.Text) + int.Parse(TextBox12.Text) +
int.Parse(TextBox14.Text) + int.Parse(TextBox16.Text);
Label1.Text = total.ToString();
I would like to pass the value to another page.
what does it means? T_T
Thanks in advance :)
protected void Button1_Click(object sender, EventArgs e)
{
Session["Month"] = DropDownList2.SelectedValue;
Session["expen1"] = TextBox1.Text;
Session["expen2"] = TextBox3.Text;
Session["expen3"] = TextBox5.Text;
Session["expen4"] = TextBox7.Text;
Session["expen5"] = TextBox9.Text;
Session["expen6"] = TextBox11.Text;
Session["expen7"] = TextBox13.Text;
Session["expen8"] = TextBox15.Text;
int totalvalue = 0;
totalvalue = int.Parse(TextBox2.Text) + int.Parse(TextBox4.Text) + int.Parse(TextBox6.Text) + int.Parse(TextBox8.Text) + int.Parse(TextBox10.Text) + int.Parse(TextBox12.Text) + int.Parse(TextBox14.Text) + int.Parse(TextBox16.Text);
Label1.Text = totalvalue.ToString();
Session["price1"] = TextBox2.Text;
Session["price2"] = TextBox4.Text;
Session["price3"] = TextBox6.Text;
Session["price4"] = TextBox8.Text;
Session["price5"] = TextBox10.Text;
Session["price6"] = TextBox12.Text;
Session["price7"] = TextBox14.Text;
Session["price8"] = TextBox16.Text;
Session["total"] = Label1.Text;
Server.Transfer("sum.aspx");
}
I want to store the result in sum.aspx.
If any of your TextBox values are null or are not a number, this will break. In order for this to work, all of the TextBox values will need to have a default value of 0 and you will have to restrict the input of the TextBox to numbers.
Instead of using textboxes and parsing text you trust to be numeric, use some sort of input mask or validation BEFORE parsing. Alternatively, use a different control like a Numeric up/down or numeric spinner.
You need to learn about how to handle exceptions, when to use try parse and when to use parse...
If any of the textboxes is empty, you will get an exception, since empty text cannot be parsed.
Use int.TryParse instead.
what does it means?
One of your TextBoxes contains a text which can't be parsed as an Integer.
Check Each textbox data should be numbers. if try enter string and validating with int.parse you will get this error.
It means that one of the textboxes values (TextBox#.Text) contains a value that cannot be "converted" to an integer.
What values are inside the textboxes? For example, if the textbox contains a non-numeric character it wont be able to convert, since the letter 'a' has no numeric value.
It means that one of the calls to int.Parse threw an exception because the text value was not a value that could be parsed into an Integer (e.g. the text was a non numeric value).
A better way to do this would be:
var textBoxesToParse = new [] { TextBox2, TextBox4, TextBox6, TextBox8, TextBox10, TextBox12, TextBox14, TextBox16 };
int total = 0;
foreach (var textBox in textBoxesToParse)
{
int textBoxValue;
if(int.TryParse(textBox.Text, out textBoxValue))
{
total += textBoxValue;
}
else
{
// The textbox had an invalid value, up to you what you need to do here.
}
}
As has been mentioned, the error is that one of your textboxes has either a blank or a non-numeric value.
You can use a RegularExpressionValidator so that the user is permitted to submit the form only when the values are numeric.
<asp:RegularExpressionValidator ID="RegularExpressionValidator7" runat="server"
ControlToValidate="txtLastName"Display="Dynamic" ErrorMessage="Numeric characters only"
ForeColor="Red" ValidationExpression="^[0-9]*$"
Additionally, you should also look to use tryParse or Int32.Parse(); the latter returns 0 if it is passed a null string.

Categories