繁体   English   中英

TextChanged之后,TextBox值为null

[英]TextBox Value is null after TextChanged

我目前正在使用.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());
  }
}

当显示用于编辑单元格的控件时,发生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);
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM