c# - 如何在编辑模式中获取 datagridview 单元格值以显示在文本框中(如 excel)
问题描述
我有一个 DataGridView 和一个文本框。我想向 Excel 等文本框显示 datagridview 单元格值(在编辑模式下)。我正在尝试这样的事情:
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 以正常工作。
解决方案
我相信这是您问题的答案: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
编辑:
哦,还有另一种很好的方法来实现这一点 -绑定。请参阅这篇文章:详细的数据绑定教程 如果您查看章节您还可以使用数据绑定做什么?,你会看到你的情况。
推荐阅读
- ios - 清除数据库后,iOS CoreData 实体返回 Null
- php - 如何通过单个 ajax 调用 POST 数据表单数据和其他数据
- python - python,编写嵌套for循环
- amazon-ec2 - 使用 cloud-init 将文件写入 ~/.ssh/ 会中断 SSH 到 EC2 实例(可能是任何机器)
- java - 将 Double 解析为特定格式
- javascript - webpack 中的构建过程出错
- python - 通过 pip 安装时获取命令“python setup.py egg_info”失败,错误代码 1
- vba - VBA 在行中搜索两个值并返回不同的列值
- jenkins-pipeline - 如何在 jenkinsfile / script 中知道当前构建是重播?
- java - 将数据保存在地图中还是以面向对象的方式保存为对象(类)?(性能)(一般 Java)