Home > Blockchain >  Different textbox values need to be seperated
Different textbox values need to be seperated

Time:10-04

Random number = new Random();
int num = number.Next(0, 11);
textBox2.Text  = num.ToString();

When the random numbers are being added to the textbox they are being connected, I need them to be seperate numbers. I tried fixing it by inserting a blank space after every button click so that it would register as different numbers but its still connecting the 2 numbers.

Later when I add the 2 numbers they register as one, this is the code i use for the addition of the 2 textboxes

decimal a, b;
a = Decimal.Parse(textBox1.Text);
b = Decimal.Parse(textBox2.Text);
textBox3.Text = (a   b).ToString();

CodePudding user response:

They are "being connected" because textBox2 can have only one value, and that value is a string. Everything you do is either writing to or reading from that one string value.

So if you do this:

textBox2.Text = "1";

And then this:

textBox2.Text  = "2";

Then textBox2 doesn't have two values, 1 and 2. It has one value, "12".


You could create your own data serialization standard for this simple case. For example, you mentioned including a blank space to separate the values. In that case your immediate goal is for the value to be "1 2". Each time you append to the text value, de-serialize what's already there and add to that data and then re-serialize it. For example:

// generate your random number
Random number = new Random();
int num = number.Next(0, 11);

// de-serialize the text into an array of numbers
var values = textBox2.Text.Split(' ').ToList();

// add your new value
values.Add(num.ToString());

// re-serialize the data back to the text box
textBox2.Text = string.Join(' ', values);

Later, when you want to get that value to perform calculations, you would again de-serialize it. For example:

var b = textBox2.Text.Split(' ').Select(x => Decimal.Parse(x));

Since b is multiple values then clearly you can't just add it to a value. If your intent is to add all of them then you can add their sum:

textBox3.Text = (a   b.Sum()).ToString();

CodePudding user response:

private void btnShowNumbers_Click(object sender, EventArgs e)
        {
            Random number = new Random();
            int num = number.Next(0, 11);
            int c = 0;
            textBox2.Text  = ($" {num.ToString()} 0169"); // ads random number and space

            decimal a, b;
            a = Decimal.Parse(textBox1.Text);
            b = Decimal.Parse(textBox2.Text); // cant parse if a decimal has " " 
            
            string nr = b.ToString();

            label1.Text = b.ToString() ;
            
            
            
            
            lblContains.Text = nr.Replace("0169", " ");

        }
    }
}

Maybe converting decimal to string and then showing string and replacing (in this example) 0169 to space?

output

  • Related