【问题标题】:which control is clicked in datagridview在datagridview中单击了哪个控件
【发布时间】:2013-06-04 13:36:41
【问题描述】:

我想在 datagridview 中执行一个动作,比如计算。当用户在文本框中输入金额时,我想计算其分期付款。问题是我的datagridview 中还有一个组合框。当我从网格组合框中选择某些内容时,我的代码中出现异常,因此我想在用户单击组合框时停止执行我的计算。
我如何知道用户是否从组合框中单击或选择了某些内容?

private void prol04DataGridView_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
     TextBox tx = e.Control as TextBox;
     // Below line i am geting error Because i select combobox in datagrid
     DataGridViewTextBoxCell cell = DataGridViewTextBoxCell)prol04DataGridView.CurrentCell;
     if (tx != null && cell.OwningColumn == prol04DataGridView.Columns[5])
     {
         tx.TextChanged -= new EventHandler(tx_TextChanged);
         tx.TextChanged += new EventHandler(tx_TextChanged);
     }             
}

那么我怎样才能找到用户在数据网格上的哪个控件上执行了操作呢?

【问题讨论】:

  • tx == null 应该暗示它不是TextBox 单元的事实。
  • @Steve 执行是Unable to cast object of type 'System.Windows.Forms.DataGridViewComboBoxCell' to type 'System.Windows.Forms.DataGridViewTextBoxCell'.

标签: c# winforms visual-studio-2010


【解决方案1】:

将用于将 e.Control 转换为 TextBox 的相同逻辑应用于 CurrentCell

 TextBox tx = e.Control as TextBox;
 DataGridViewTextBoxCell cell = prol04DataGridView.CurrentCell as DataGridViewTextBoxCell;
 if (tx != null && cell != null && cell.OwningColumn == prol04DataGridView.Columns[5])
 {
       tx.TextChanged -= new EventHandler(tx_TextChanged);
       tx.TextChanged += new EventHandler(tx_TextChanged);

 }

【讨论】:

  • 我投了赞成票,因为这是正确的,但我建议添加一个可以获得当前单元格的列索引或拥有列,并使用它来检查您是否在正确的列中。如果(例如)您必须输入文本框并且只想处理一个列,则很有用。
  • 感谢它为我所做的工作,我赞成你的回答 :) 但是如果我想知道点击了哪种类型的单元格,我怎么知道。
猜你喜欢
  • 2012-05-31
  • 1970-01-01
  • 2014-10-28
  • 2012-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多