Search code examples
c#winformsdatagridviewtextbox

Dynamic value from TextBox to DataGridView


So i created a dynamic TextBox which allows the user to enter a description if requested, however I would like to populate my table with the description from the user. e.g.

dataGridView1.Rows[n].Cells[3].Value = textDescription.Text

But every time I do this, the testDescription name isn't available, I was wondering if there was any way to solve this issue.

Just want to say that my meaning of dynamic means i created the TextBox myself and not drag and drop.

private void button1_Click(object sender, EventArgs e)
{
    TextBox textDescription = new TextBox();
    this.Controls.Add(textDescription);
    textDescription.Location = new Point(180, 190);
    textDescription.Size = new Size(154, 20);
    textDescription.Font = new Font("Microsoft Sans Serif", 8, FontStyle.Regular);
    textDescription.Text = "";
}

Solution

  • I noticed that the TextBox is a local variable in "button1_Click". Maybe you can try to define it as a global variable.

    TextBox textDescription = new TextBox();
    
    private void button1_Click(object sender, EventArgs e)
    {
        this.Controls.Add(textDescription);
        textDescription.Location = new Point(180, 190);
        textDescription.Size = new Size(154, 20);
        textDescription.Font = new Font("Microsoft Sans Serif", 8, FontStyle.Regular);
        textDescription.Text = "123";
    }
    
    private void button2_Click(object sender, EventArgs e)
    {
        dataGridView1.Rows[0].Cells[0].Value = textDescription.Text;
    }