如何从datagridview textchanged事件中的当前单元格中获取文本?

我正在制作一个Windows表单应用程序,其中我使用了datagridview。 我希望当我在datagridview中的文本框中写一些东西,而不是出现包含我写的字符串的消息框.. ican’t在textchanged事件中获取我的文本..

所有的东西都必须在textchanged事件中触发..这是我的代码: –

void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) { if (dataGridView1.CurrentCell.ColumnIndex == 1) { TextBox tb = (TextBox)e.Control; tb.TextChanged += new EventHandler(tb_TextChanged); } } void tb_TextChanged(object sender, EventArgs e) { //listBox1.Visible = true; //string firstChar = ""; //this.listBox1.Items.Clear(); //if (dataGridView1.CurrentCell.ColumnIndex == 1) { string str = dataGridView1.CurrentRow.Cells["Column2"].Value.ToString(); if (str != "") { MessageBox.Show(str); } } 

 void tb_TextChanged(object sender, EventArgs e) { var enteredText = (sender as TextBox).Text ... } 

试试吧。 考虑到Control Object被声明为Global。

 Control cnt; void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) { e.Control.TextChanged +=new EventHandler(tb_TextChanged); cnt=e.Control; cnt.TextChanged +=tb_TextChanged; } void tb_TextChanged(object sender, EventArgs e) { if(cnt.Text!=string.Empty) { textBox.Text=cnt.Text; MessageBox.Show(textBox.Text); } } 

TextChanged显示MessageBox会非常烦人。

相反,您可以在DataGridView.CellValidated事件中尝试它,该事件在完成单元格validation后触发。

示例代码:

 dataGridView1.CellValidated += new DataGridViewCellEventHandler(dataGridView1_CellValidated); void dataGridView1_CellValidated(object sender, DataGridViewCellEventArgs e) { if (dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null) { MessageBox.Show(dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString()); } }