Photon Light
Photon Light

Reputation: 777

Getting data from textbox into array

How to stream data entered by the user in text box into int array? Let's say, that I've got a window with 2 text boxes and buttons and buffer, that is not visible in interface.
I want data from textbox1 (for example CAT) to be saved into int buffer[255] after clicking button1. Then, after clicking button2, 'CAT' should appear in textbox2 and being deleting from buffer.
It should be like:

int buffer[255]={0};
//user entered 'CAT' in textbox1
//clicking button1
//now:
buffer[0]=[67]; //67 = 'C' in ASCII
buffer[1]=[65];
buffer[2]=[84];
//clicking button2
//in read-only textbox2 'CAT' appears
//now:
buffer[]={0};

I guess there will be need some conversion while displaying word in textbox2 (for loop with System.Convert.ToChar(buffer[i])), but what puzzles me most is how to save text from textbox1 into buffer.

Ok, thx for responses, now I need to make my button work, but don't know why, I've got now this method:

public int saveToBuffer(string text)
        {
            string txt = text;
            int[] receivedBuffer = new int[255];
            int count = 0;
            //int i = 0;

            foreach(char c in txt)
            {
                receivedBuffer[count] = c;
                count++;
            }
            return receivedBuffer[255];
        }

Which returns text from textbox1 to array receivedBuffer. I also got this button:

private void saveToBufferButton_Click(object sender, EventArgs e)
        {

        }

and I don't know what to put beetwen {} to make it work.

Upvotes: 0

Views: 682

Answers (3)

2GDev
2GDev

Reputation: 2466

A simple method to retrieve ASCII code from string is :

string value = textbox1.Text;

// Convert the string into a byte[].
byte[] asciiBytes = Encoding.ASCII.GetBytes(value);

Upvotes: 0

Thulani Chivandikwa
Thulani Chivandikwa

Reputation: 3539

Great response from Rob Epsteing, just to add a different approach without LINQ that might give an good idea of what we is essentially shown by Rob Epstein in 2 statements.

        string text = "CAT";
        int[] buffer = new int[text.Length];
        int count = 0;
        //add to buffer
        foreach(char c in text)
        {
            buffer[count] = c;
            count++;
        }

        //from buffer to text
        StringBuilder builder = new StringBuilder();
        foreach(char c in buffer)
        {
            builder.Append(c);
        }
        text = builder.ToString();

Upvotes: 0

Rob Epstein
Rob Epstein

Reputation: 1500

Appreciating that I'm not using a statically defined buffer in this example, hopefully this will help you get to the desired solution:

int[] buffer = "CAT".Select(Convert.ToInt32).ToArray();
string result = new string(buffer.Select(Convert.ToChar).ToArray());

Replace "CAT" in the sample above with textbox1.Text.

Upvotes: 1

Related Questions