c# - TextChanged 后 TextBox 值为空
问题描述
我目前正在使用 .Net Framework v4.6.1 开发 Windows 窗体应用程序。
我的目标是用户可以在 DataGridViewColumnTextBox 中输入他的数据,并且在每个 TextChanged 事件中它应该计算输入数据的总数。
问题是该列的值始终为空,除非我从字符串中删除了一个字符。
我的代码如下所示:
public GraspForm() {
InitializeComponent();
this.dgvRecords.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler(dgvControllHandling);
}
#region - DGV Eventhandling -
/// <summary>
/// Adds an event to the second textbox from the datagridview
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void dgvControllHandling(object sender, DataGridViewEditingControlShowingEventArgs e) {
if(dgvRecords.CurrentCell.ColumnIndex == 1) {
TextBox tb = (TextBox)e.Control;
tb.TextChanged += new EventHandler(CellTextboxTextChanged);
}
}
void CellTextboxTextChanged(object sender, EventArgs e) {
if(dgvRecords.CurrentRow.Cells[1].Value != null) {
dgvRecords.CurrentRow.Cells[2].Value = CalculateTotal(dgvRecords.CurrentRow.Cells[0].Value.ToString(), dgvRecords.CurrentRow.Cells[1].Value.ToString());
}
}
解决方案
DataGridView.EditingControlShowing 事件在显示用于编辑单元格的控件时发生,请尝试使用 DataGridView.CellValueChanged 事件来满足您的需要。
public GraspForm()
{
InitializeComponent();
this.dgvRecords.CellValueChanged += new DataGridViewCellEventHandler(dgvCellValueChanged);
}
private void dgvCellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if(e.ColumnIndex == 1)
{
var currentRow = this.dgvRecords.Rows[e.RowIndex];
if(currentRow.Cells[0].Value != null && currentRow.Cells[1].Value != null)
{
var val1 = currentRow.Cells[0].Value.ToString();
var val2 = currentRow.Cells[1].Value.ToString();
this.dgvRecords.Rows[e.RowIndex].Cells[2].Value = CalculateTotal(val1, val2);
}
}
}
推荐阅读
- huffman-code - 霍夫曼编码中如何存储频率表?
- javascript - 单击时的 Jquery 返回一个值并在另一个函数中使用它
- python - 如何恢复 pip freeze > requirements.txt?
- ansible - 错误!'copy' 不是 Play 的有效属性
- c++ - 拥有“受保护的非虚拟析构函数”与“受保护的虚拟析构函数”有什么好处?
- python - 按列中选定行分组
- c - 如何使用 gcc 在 windows 上编译 LIBVLC 示例代码
- ios - 我的应用程序关闭后如何保存结构?
- mysql - Amazon RDS:您尝试将用户“master”连接到 MySQL 服务器失败
- matlab - 如何在 MATLAB 中对慢速代码进行矢量化以提高性能?