0

DataGridView在其中有一个带有文本(即DataGridViewTextBoxColumn),并且每次这些字段之一中的文本发生更改时,都必须在其他地方调用一些更新方法。但是,我注意到当您更新 TextBox 时,其中ValueCell尚未更新。

class MyForm : Form
{
    private System.Windows.Forms.DataGridView m_DataGridView;
    private System.Windows.Forms.DataGridViewTextBoxColumn m_textBoxColumn;

    private void m_DataGridView_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs editEvent)
    {
        if (editEvent.Control as TextBox != null)
        {
            TextBox textBox = editEvent.Control as TextBox;
            textBox.TextChanged -= new EventHandler(textBox_TextChanged);
            textBox.TextChanged += new EventHandler(textBox_TextChanged);
        }
    }

    private void textBox_TextChanged(object sender, EventArgs e)
    {
        UpdateText();
    }

    private void UpdateText()
    {
        foreach (DataGridViewRow row in m_DataGridView.Rows)
        {
            if (row.Cells[1].Value != null)
            {
                string text = row.Cells[1].Value.ToString();
                System.Diagnostics.Debug.WriteLine(text);
            }
        }
    }
}

举个例子:如果 TextBox 中的文本当前是"F",并且您键入"oo",我希望控制台输出:

"F"
"Fo"
"Foo"

相反,它实际上写的是:

"F"
"F"
"F"

有没有办法在编辑文本框时从 inUpdateText()方法中访问所有文本框的内容?

4

1 回答 1

1

DataGridViewCell.Value 不会在您输入时立即更新Editing control。这是设计使然。不在编辑模式下时更新Value。我想你想要这样的东西:ValidatedCurrentCell

private void textBox_TextChanged(object sender, EventArgs e)
{
    UpdateText(sender as Control);
}
private void UpdateText(Control editingControl)
{
  System.Diagnostics.Debug.WriteLine(editingControl.Text);
}

更新

我认为你可以尝试这样的事情:

string editingText;
int editingRowIndex = -1;
private void textBox_TextChanged(object sender, EventArgs e)
{
    editingRowIndex = ((DataGridViewTextBoxEditingControl)sender).EditingControlRowIndex;
    editingText = (sender as Control).Text;
    UpdateText();
}
private void UpdateText()
{
    foreach (DataGridViewRow row in m_DataGridView.Rows)
    {
        if (row.Cells[1].Value != null)
        {
            string text = row.Index == editingRowIndex ?
                          editingText : row.Cells[1].Value.ToString();
            System.Diagnostics.Debug.WriteLine(text);
        }
    }
}
于 2013-09-24T16:52:45.463 回答