user4671342
user4671342

Reputation:

How to catch if cell Value got changed in DataGridView as sender

I haven't found something that matches my problem so I ask it here. I have some code which belongs to a Textbox:

if ((sender as TextBox).Text == form1.filterType())
{
    //Do something
}

This comes from the TextBox TextChanged event. So when the TextChanged Event gets fired it calls a method which has the if-construct above and recognizes that the textchanged event came from the textbox.

Now I want exactly the same just when someone writes into a cell in a DataGridView (not when it's just clicked - when the content changes).

How to do this correctly and which event fires when the content changes in a cell without leaving the cell?

Upvotes: 0

Views: 807

Answers (2)

user4671342
user4671342

Reputation:

I have found a solution for this:

 private void Form1_Load(object sender, EventArgs e)

   {

  this.dataGridView1.EditingControlShowing += new    DataGridViewEditingControlShowingEventHandler(dataGridView1_EditingControlShowing);

 }

 void dataGridView1_EditingControlShowing(object sender, 
 DataGridViewEditingControlShowingEventArgs e)

    {

     if (dataGridView1.CurrentCell.ColumnIndex == 0)

        {

            TextBox tb = (TextBox)e.Control;

            //"unwire" the event before hooking it up ensures the event handler gets called only once
            tb.TextChanged -= new EventHandler(tb_TextChanged);
            tb.TextChanged += new EventHandler(tb_TextChanged);

        }

     }



     void tb_TextChanged(object sender, EventArgs e)

    {

        MessageBox.Show("changed");

    }

Now it fires everytime the value in the cell gets changed - it behaves like a textbox.

Now - I still need a solution for the "if-construct" above. How to do this exactly? I've casted the cell into a textbox but now? Does this still comes from the dataGridview?

Upvotes: 1

Maximilian Eheim
Maximilian Eheim

Reputation: 3

Once I had a similar problem an solved it this way (think there are better ones but it worked)

private void DataGridView1_onFocus ( Object sender, EventArgs e)
{
    DataGridView1.onKeyPress+=DataGridView1_onKeyStroke;
}
private void DataGridView1_onFocusLost( Object sender, EventArgs e)
{
    DataGridView1.onKeyPress-=DataGridView1_onKeyStroke;
}
private void  DataGridView1_onKeyStroke( Object sender , EventArgs e)
{
    //Do your thing
}

Upvotes: 0

Related Questions