Home > Mobile >  Int64.TryParse on mix concentration of integers and strings C#
Int64.TryParse on mix concentration of integers and strings C#

Time:09-06

I'm working on a personal project where I wanted to allows user to TryParse selected cell values on Datagridview (if cell values is $4000 then TryParse button function should convert the cell value to something like $4,000).

Now in my case I have two buttons;

  • TryParse selected cell value
  • Insert $ symbol into cell (e.g when button is pressed selected cell value should looks like $4000)

Now that in order to make it possible to convert a cell that contains value of $4000 to $4,000 I need to use a TryParse function (as far as I know), but the thing is its obviously not possible to convert $4000 to $4,000 because $ is not a valid integer therefore the cell value will be 0.

Now my question is, how do I make it possible to TryParse a cell that contains value of $nnn to $n,nn (where n is positive integers)?.

TryParse the cell value on button click:

    private void guna2Button28_Click(object sender, EventArgs e) {
        try {
            foreach(DataGridViewCell selected_cells in guna2DataGridView2.SelectedCells) {
                long num;
                long.TryParse(selected_cells.Value.ToString(), out num);
                string commas = num.ToString("N0");
                selected_cells.Value = commas;
            }
        } catch (Exception eq) {
            MessageBox.Show("Comma Points can only be used on integers","System",
                    MessageBoxButtons.OK,MessageBoxIcon.Error);
        }
    }

Insert $ symbol into cell on button click:

    private void guna2Button21_Click(object sender, EventArgs e) {
        try {
            foreach(DataGridViewCell convert in guna2DataGridView2.SelectedCells) {
                convert.Value = "$"   convert.Value;
            }
        } catch (Exception eq) {
            MessageBox.Show("An error occurred","System",
                MessageBoxButtons.OK,MessageBoxIcon.Error);
        }
    }

CodePudding user response:

You can just replace $ with string.Empty. Something like...

string value = "$4000";
int i = Convert.ToInt32(value.Replace("$", string.Empty));
Console.WriteLine(i.ToString("C", CultureInfo.CurrentCulture));

CodePudding user response:

You could just check if the first character of the string is $

long num;
int startPos = selected_cells.Value.ToString()[0] == '$' ? 1 : 0;
long.TryParse(selected_cells.Value.ToString().Substring(startPos), out num);
  • Related