TextChanged之后,TextBox值为null

时间:2018-10-31 08:22:46

标签: c# .net

我目前正在使用.Net Framework v4.6.1开发Windows窗体应用程序。

我的目标是用户可以在DataGridViewColumnTextBox中输入他的数据,并且在每个TextChanged事件中它应该计算输入数据的总数。

问题在于,除非我从字符串中删除字符,否则列值的Value始终为null。

我的代码如下:

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

1 个答案:

答案 0 :(得分:1)

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