impulse101
impulse101

Reputation: 99

Automatic insertion of rows to DataGrid View without using a timer in Winforms

A row is to be automatically added in a datagridView of Winforms according to value changes in a text box.

A text box (textBox1) is used in the form to input the value. With the change in the value a row is to be inserted in the datagridview (dataGridView1)

I have used the following code for implementing the same,

    private void timer1_Tick(object sender, EventArgs e)
    {
        int value;

        value = Convert.ToInt32(textBox1.Text);

        if(value == 2)
        {
            string[] row1 = {"Value is 2"};
            dataGridView1.Rows.Add(row1);
        } 
     } 

The result I was expecting to get was a single row inserted in the dataGridView1.

I am getting the same row inserted a number of times since the code is running continuously inside the timer, timer1.

Can anyone help me with getting the expected result? Can it be done without using a timer?

Upvotes: 0

Views: 217

Answers (4)

germi
germi

Reputation: 4658

The usual approach would be to subscribe to the TextBox.TextChanged event:

//maybe in the form constructor
textBox1.TextChanged += HandleTextChanged;

Then you would need to implement a method HandleTextChanged somewhat like this (in the same class):

private void HandleTextChanged(object sender, EventArgs e)
{
    if(int.TryParse(textBox1.Text, out var number))
    {
        if(number == 2)
        {
            string[] newRow = { "Value is 2" };
            dataGridView1.Rows.Add(newRow);
        }
    }
}

For further information on events in WinForms, I propose you have a look at the documentation on learn.microsoft.com. Generally speaking WinForms is event-driven, so it's definitely useful to get used to the concept.

Upvotes: 1

apomene
apomene

Reputation: 14389

You could have your timer event tick once and then disable it:

    private void timer1_Tick(object sender, EventArgs e)
    {
        int value;

        value = Convert.ToInt32(textBox1.Text);

        if(value == 2)
        {
            string[] row1 = {"Value is 2"};
            dataGridView1.Rows.Add(row1);
        } 
        timer1.Enabled = false; //<--disable timer1 once your job is done
     } 

Upvotes: 0

simon
simon

Reputation: 73

The textbox has a multitude of events, which you can inspect in the designer, by clicking it and selecting in the Properties window the yellow flash on the top.

if you want to add your textbox always as row when you finsihed editing the textbox, use the apropiate event (Leave maybe) and add your row in there.

Upvotes: 0

EylM
EylM

Reputation: 6103

If you want to insert a new row according to the change in TextBox, you can use TextChanged event.

You delegate will be called each time the text is changed.

private void textbox_TextChanged(object sender, EventArgs e)
{
   // place your code here for adding a row.
}

Upvotes: 0

Related Questions