我有一个DataGridView和一个文本框。我想显示datagridview单元格值(在编辑模式下)到Excel等文本框。 我正在尝试这样的事情:
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
var ctl = e.Control as DataGridViewTextBoxEditingControl;
if (ctl == null)
{
return;
}
ctl.KeyPress -= ctl_Keypress;
ctl.KeyPress += new KeyPressEventHandler(ctl_Keypress);
}
和:
private void ctl_Keypress(object sender, KeyPressEventArgs e)
{
var box = sender as System.Windows.Forms.TextBox;
if (box == null)
{
return;
}
tb_currendCellValue.Text = box.Text;
}
,但目前无法正常工作。 请帮我。谢谢。
解决:将“ KeyPress”更改为keyUp才能正常工作。
答案 0 :(得分:0)
我相信这是您的问题的答案:Change datagridview cell value in edit mode
我将上面的链接中的想法重新编码为您的案例,并对其进行了测试。我在编辑控件中创建了_KeyUp事件。如果编辑控件是TextBox类型,则应添加更多内容,例如测试。
C#
private TextBox CtrlTextbox;
private void DataGridView2_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (RowIdx >= 0)
{
CtrlTextbox = (TextBox)e.Control;
CtrlTextbox.KeyUp += CopyText;
}
}
private void CopyText(object sender, KeyEventArgs e)
{
this.TextBox1.Text = sender.Text;
}
VB.NET
Dim CtrlTextbox As TextBox
Private Sub DataGridView2_EditingControlShowing(sender As Object, e As DataGridViewEditingControlShowingEventArgs) Handles DataGridView2.EditingControlShowing
If RowIdx >= 0 Then
CtrlTextbox = CType(e.Control, TextBox)
AddHandler CtrlTextbox.KeyUp, AddressOf CopyText
End If
End Sub
Private Sub CopyText(sender As Object, e As KeyEventArgs)
Me.TextBox1.Text = sender.Text
End Sub
编辑:
哦,还有另一种好的方法-绑定。请参阅这篇文章:A Detailed Data Binding Tutorial 如果您看一章,数据绑定还有什么用?,您会确切地看到您的情况。