【问题标题】:How to get the text from current cell in datagridview textchanged event?如何从 datagridview textchanged 事件中的当前单元格获取文本?
【发布时间】:2014-02-06 09:46:09
【问题描述】:

我正在制作一个使用 datagridview 的 Windows 窗体应用程序。 我希望当我在 datagridview 的文本框中写一些东西时,会出现一个包含我写的字符串的消息框。 无法在 textchanged 事件中获取我的文本..

所有东西都必须在 textchanged 事件中触发。 这是我的代码:-

 void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            if (dataGridView1.CurrentCell.ColumnIndex == 1)
            {
                TextBox tb = (TextBox)e.Control;
                tb.TextChanged += new EventHandler(tb_TextChanged);
            }
        }
        void tb_TextChanged(object sender, EventArgs e)
        {
            //listBox1.Visible = true;
            //string firstChar = "";
            //this.listBox1.Items.Clear();
            //if (dataGridView1.CurrentCell.ColumnIndex == 1)
            {
                string str = dataGridView1.CurrentRow.Cells["Column2"].Value.ToString();
                if (str != "")
                {

                    MessageBox.Show(str);
                }
            }

【问题讨论】:

    标签: c# winforms datagridview


    【解决方案1】:
    void tb_TextChanged(object sender, EventArgs e)
    {
        var enteredText = (sender as TextBox).Text
        ...
    }
    

    【讨论】:

    • String enteredText = ((TextBox)sender).Text; 是等价的。
    【解决方案2】:

    TextChanged 中显示MessageBox 会很烦人。

    相反,您可以在单元格验证完成后触发的DataGridView.CellValidated 事件中尝试它。

    示例代码:

    dataGridView1.CellValidated += new DataGridViewCellEventHandler(dataGridView1_CellValidated);
    
    void dataGridView1_CellValidated(object sender, DataGridViewCellEventArgs e)
    {
        if (dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null)
        {
            MessageBox.Show(dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-10
      • 1970-01-01
      • 2019-09-30
      • 1970-01-01
      • 2010-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多