如何在DataGridView中将单元格值更改为发件人

时间:2015-06-27 12:48:21

标签: c# winforms events datagridview event-handling

我还没找到符合我问题的东西,所以我在这里问。我有一些属于文本框的代码:

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

这来自TextBox TextChanged事件。因此,当TextChanged事件被触发时,它调用一个上面有if-construct的方法,并识别textchanged事件来自文本框。

现在我想要的只是当有人写入DataGridView中的单元格时(而不是当它被点击时 - 当内容发生变化时)。

如何正确地执行此操作以及当单元格中的内容发生更改而不离开单元格时会触发哪个事件?

2 个答案:

答案 0 :(得分:1)

我找到了解决方法:

 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");

    }

现在每当单元格中的值发生变化时它就会触发 - 它的行为类似于文本框。

现在 - 我仍然需要" if-construct"以上。怎么做到这一点?我已经将单元格放入文本框但是现在?这仍然来自dataGridview吗?

答案 1 :(得分:0)

一旦我遇到了类似的问题,就用这种方式解决了(想想有更好的问题但它有效)

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
}
相关问题