Insert space between numbers in Textbox - c#

Hello and Thanks for reading.
I have this TextBox where a user can type in his/her Phone number.
<asp:TextBox runat="server" ID="txtPhone" CssClass="TicketField FieldWidthH txtboxStyle" />
If the user types 12345678 I would like it to auto "show" 12 34 56 78 so there is a space after each 2 numbers.
Here is my C# code:
if (IsPostBack) {
if (!string.IsNullOrEmpty(txtPhone.Text)) {
// Check if the value contains any non-numeric values and strip them out
string cleanedUpTextBoxValue = Regex.Replace(txtPhone.Text, #"^\d{6}$", "");
// Parse your number as an integer from your TextBox (after cleaning it up)
Int64 yourIntegerTextBoxValue = Int64.Parse(cleanedUpTextBoxValue);
// Format your number as a string
string formattedResult = yourIntegerTextBoxValue.ToString("## ## ## ##");
// Output the result into your TextBox
txtPhone.Text = formattedResult;
}
}
I also tried string cleanedUpTextBoxValue = Regex.Replace(txtPhone.Text, "[^\d]", "");
But then I type in the Textbox I still only displays the numbers as 12345678.
What am i doing wrong?
Thanks for your time

I'd generally recommend using JavaScript for this if possible, but if you want a C# solution, you can use this to strip out non-digit characters:
string text = Regex.Replace(txtPhone.Text, #"\D", "");
And then this to insert spaces around each pair of digits:
text = Regex.Replace(text, #"\d\d(?!$)", "$0 ");
txtPhone.Text = text;
If implemented in JavaScript, it would look a little bit like this:
text = text.replace(/\D/g, '').replace(/(\d\d)(?!$)/g, '$1 ')

Use the Insert method of string.
string phone = txtPhone.Text; // or your cleaned-up string
phone = phone.Insert(2, " ");
txtPhone.Text = phone;
You can put a loop in there to get spaces between every other digit as needed. Looping over the length of the string, starting from the end, is probably the easiest. Check the length of the string to determine your starting position (i.e., the last character or next to last). What happens if the user enters an odd number of digits?

Related

How can I keep the last 6 digits number in c#

If I copy " BOB3 27QK DEPM PJ7J T25G SJZI CJA5 BO5O|123456 " and I want to pass it to my text box, and get only the last 6 digits number in my text box, How to do in c#?
Using .Split would look like this:
string myString = "BOB3 27QK DEPM PJ7J T25G SJZI CJA5 BO5O|123456";
char[] mySplitChars = { '|' };
string[] myArray = myString.Split(mySplitChars);
Console.WriteLine(myArray[1]);
Using .Substring would look like this:
Console.WriteLine(myString.Substring(myString.Length - 6));
The latter is probably preferred because it is shorter and it does not rely on the "|" character being present. The former would be preferred if the "|" is always present but the number of characters at the end can change.
How are you passing it your text box? If it's just getting the last n characters:
refer to this answer

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

Format DataGridView TextBox Column Containing Numeric Values

I have a DataGridView with TextBox colums. One of the columns display record counts which are formatted as ###,###,000. The column itself isn't set to format the text, but the data is formatted when the data source is populated. The data source is a List by the way. The DataGridView merely displays everything as it gets it.
Now, I need to parse the numeric text value into a variable, which is fine by doing
int.Parse(data_grid_view_row.Cells["col_Record_Count"].Value.ToString())
but, if I have numbers reaching thousands, it displays as 1 000, because of the formatting. The formatting generates a space rather than a comma as this is how the environment has been configured. When I try to parse that value, I get an exception because of the space in the numeric value.
I have tried formatting the string value
int.Parse(String.Format("{0:000000000}", data_grid_view_row.Cells["col_Record_Count"].Value.ToString()))
and
int.Parse(String.Format("{0:########0}", data_grid_view_row.Cells["col_Record_Count"].Value.ToString()))
and all sorts of variants, but it keeps returning the space in the value, which then won't parse. I have tried replacing the space, but it is persistent. Also, the space shows ASCII keycode 63 which is supposed to be a question mark, not so? Even when I try to replace using the keycode... nothing!
Any ideas as to why this is happening and how to fix it?
The complete code block I have is
foreach (DataGridViewRow data_grid_view_row in dgv_Migration_Files.Rows)
{
if ((bool)data_grid_view_row.Cells["col_Select"].Value == true)
{
//-------------------------------------------------------------------------
// this is only to test and see what value I get for the space character, will be removed later
string test_str = data_grid_view_row.Cells["col_Record_Count"].Value.ToString().Replace(" ", string.Empty);
test_str = test_str.Replace(" ", "");
for (int k = 0; k < test_str.Length; k++)
{
string newstr = test_str.Substring(k, 1);
var kycode = ASCIIEncoding.ASCII.GetBytes(newstr);
}
//-------------------------------------------------------------------------
migrate.Add(new Migrate()
{
File_Folder = data_grid_view_row.Cells["col_File_Folder"].Value.ToString()
,
File_Name = data_grid_view_row.Cells["col_File_Name"].Value.ToString()
,
Record_Count = int.Parse(String.Format("{0:000000000}", data_grid_view_row.Cells["col_Record_Count"].Value.ToString()))
});
}
}
Use simple Solution:-
If space is available Remove it and then simply Parse into INT.
str.Replace(" ", String.Empty)
string data = data_grid_view_row.Cells["col_Record_Count"].Value.ToString().Replace(" ", String.Empty);
int.Parse(data);
Make it easier:-
int.Parse(data_grid_view_row.Cells["col_Record_Count"].Value.ToString().replace(" ", String.Empty));
And if you want to remove space and comma both while parsing using this Regular Expression
int.Parse(data_grid_view_row.Cells["col_Record_Count"].Value.ToString().replace(/[, ]+/g, " ").trim());
Check This Small Example First you will get Clear Idea:-
string data = "1 0000";
string result = data.Replace(" ", string.Empty);
Since the replace method didn't remove spaces as I expected to, I resorted to the below solution. This will also remove any other numeric separators irrespective of what the numeric separator has been set up as in the OS.
//get the numeric decimal seperator key code
string dummy_numeric = (1000).ToString(Helper.application_number_display_format);
char replace_char = (char)0;
foreach (char current_char in dummy_numeric)
{
if (!System.Char.IsDigit(current_char))
{
replace_char = current_char;
break;
}
}
//get all the files that are selected for migration
List<Migrate> migrate = new List<Migrate>();
foreach (DataGridViewRow data_grid_view_row in dgv_Migration_Files.Rows)
{
if ((bool)data_grid_view_row.Cells["col_Select"].Value == true)
{
migrate.Add(new Migrate()
{
File_Folder = data_grid_view_row.Cells["col_File_Folder"].Value.ToString()
,
File_Name = data_grid_view_row.Cells["col_File_Name"].Value.ToString()
,
Record_Count = int.Parse(data_grid_view_row.Cells["col_Record_Count"].Value.ToString().Replace(replace_char.ToString(), ""))
});
}
}

Remove characters from C# string not belonging to a specicif code page

In C# I have a string that goes on to be inserted into a db table using codepage 37 US. So for instance, the '€' will cause the insert operation to fail.
What is a good way to clean my string of characters not represented in code page 37 and possible replace those charaters with some default character?
Something like this?
var euroString = "abc?€./*";
var encoding37 = System.Text.Encoding.GetEncoding(
37,
new EncoderReplacementFallback("_"), //replacement char
new DecoderExceptionFallback());
var byteArrayWithFallbackChars = encoding37.GetBytes(euroString);
var utfStringFromBytesWithFallback = new string(encoding37.GetChars(byteArrayWithFallbackChars));
//returns "abc?_./*"
P.S.: you can just use GetEncoding(37), but in this case replacement char is ? which I think is not really OK for DB :)
Here is a regex to restrict input to a range of allowed characters:
https://dotnetfiddle.net/WIrSSO
const string Allowed = #"1-9\."; //Add allowed chars here
string cleanStr = Regex.Replace("£1.11", "[^" + Allowed + "]", "");

How to check if a position in a string is empty in c#

I have strings with space seperated values and I would like to pick up from a certain index to another and save it in a variable. The strings are as follows:
John Doe Villa Grazia 323334I
I managed to store the id card (3rd column) by using:
if (line.length > 39)
{
idCard = line.Substring(39, 46);
}
However, if I store the name and address (1st and 2nd columns) with Substring there will be empty spaces since they are not of the same length (unlike the id cards). How can I store these 2 values and removing the unneccasry spaces BUT allowing the spaces between name and surname?
Try this:
string line = " John Doe Villa Grazia 323334I";
string name = line.Substring(02, 16).Trim();
string address = line.Substring(18, 23).Trim();
string id = line.Substring(41, 07).Trim();
var values = line.Split(' ');
string name = values[0] + " " + values[1];
string idCard = values[4];
It will be impossible to do without database lookups on names if there aren't spaces for sure in the previous columns.
Are these actually space separated or are they really fix width columns?
By that I mean do the "columns" start at the same index into the string in each case - from the way you're describing the data is sounds like the later i.e. the ID column is always column 39 for 7 characters.
In which case you need to a) pull the columns using the appropriate substring calls as you're already doing and then, use "string ".Trim() to cut off the spaces.
If the rows, are, as it seems fixed with then you don't want to use Split at all.
How can you even get the ID like that, when everything in front of it is of variable length? If that was used for my name, "David Hedlund 323334I", the ID would start at pos 14, not 39.
Try this more dynamic approach:
var name = str.Substring(0, str.LastIndexOf(" "));
var id = str.Substring(str.LastIndexOf(" ")+1);
Looks like your parsing strategy will cause you a lot of trouble. You shouldn't count on the string's size in order to parse it.
Why not save the data in CSV format (John Doe, Villa Grazia, 323334I)?
that way, you can assume that each "column" will be separated by a comma which will make your parsing efforts easier.
Possible "DOH!" question but are you sure they are spaces and not Tabs? Looks like it "could" be a tab seperated file?
Also for browie points you should use String.Empty instead of ' ' for comparisons, its more localisation and memory friendly apparently.
The first approach would be - as already mentioned - a CSV-like structure with a defined token as the field separator.
The second one would be fixed field lengths so you know the first column goes from char 1 to char 20, the second column from char 21 to char 30, and so on.
There is nothing bad about this concept besides that the human readability may be poor if the columns are filled up to their maximum so no spaces remain between them.
You could write a helper function or class which knows about the field lengths and provides an index-based, fault-tolerant access to the particular column. This function would extract the particular string parts and remove the leading and trailing spaces but leave the spaces in between as they are.
If your values have fixed width, best not split it but use the right indexes in your array.
const string input = "John Doe Villa Grazia 323334I";
var name = input.Substring(0, 15).TrimEnd();
var place = input.Substring(16, 38).TrimEnd();
var cardId = input.Substring(39).TrimEnd();
Assuming your values cannot contain two sequential spaces in them we can maybe use " " (double space" as a separator?
The following code will split your string based on the double space
const string input = "John Doe Villa Grazia 323334I";
var entries = input.Split(new[]{" "}, StringSplitOptions.RemoveEmptyEntries)
.Select(s=>s.Trim()).ToArray();
string name = entries[0];
string place = entries[1];
string idCard = entries[2];

Categories