John
John

Reputation: 111

Parse text from cell from dataGridView to textboxes

For example the words in form one in dataGridView cell are: one;two;three .....

I want this display separately in form2 in textboxes:

text in textBox1: one
text in textBox2: two
text in textBox3: three

How do I parse this?

I fill datagrid in formOne this way :

foreach (DataGridViewCell cell in dataGridView1.SelectedCells)
        {

            string text = "";
            for (int i = 0; i < emails.Length ;i++)
            {

                if (emails[i].ToString().Trim() != "")
                {


                    text = text + emails[i] + ";"  ;
                    dataGridView1.Rows[cell.RowIndex].Cells[col].Value = text;
                }
            }

        }    

Upvotes: 0

Views: 1057

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236288

string cellValue = "one;two;three";
// should contain at least three values
var values = cellValue.Split(new[] {';'}, StringSplitOptions.RemoveEmptyEntries);
textBox1.Text = values[0];
textBox2.Text = values[1];
textBox3.Text = values[2];

Consider also to create texboxes dynamically if there is different number of values possible in cell. Another option is usage of grid.


Another option - get list of texboxes:

var textBoxes = new List<TextBox> { textBox1, textBox2, textBox3 };

Or if you will add texboxes to form in correct order:

var textBoxes = Controls.OfType<TextBox>().ToList();

And fill them all in a loop

string cellValue = "one;two;three";
var values = cellValue.Split(new[] {';'}, StringSplitOptions.RemoveEmptyEntries);

for (int i = 0; i < values.Length; i++)
   if (textBoxes.Count < i) // also you can ensure you have textBox for value
       textBoxes[i].Text = values[i];

Upvotes: 2

Related Questions