我有DataGridView
文本(即DataGridViewTextBoxColumn
),每当其中一个字段中的文字发生变化时,必须在其他地方调用某些更新方法。但是,我注意到当您更新TextBox时,Value
中的Cell
尚未更新。
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"
有没有办法在编辑TextBox时从UpdateText()
方法中访问所有TextBox的内容?
答案 0 :(得分:1)
当您输入DataGridViewCell.Value
时,Editing control
不会直接更新。这是设计的。当Value
未处于编辑模式时,Validated
会在CurrentCell
之后更新。我想你想要这样的东西:
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);
}
}
}