首页 > 解决方案 > 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());
  }
}

标签: c#.net

解决方案


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);
        }
    }
}

推荐阅读