Wednesday, September 7, 2011

DataGridView TextChanged Event Handling

Hi,
Find out the event handling for the datagridview events while changing its text in cells.
We can apply the validations on the text entered in text box cells of datagirdview


 private void dgvAttributes_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            try
            {
                index = 0;
                if (dgvAttributes.CurrentCell.ColumnIndex == 1)
                {
                    index = 1;
                    rowid = dgvAttributes.CurrentCell.RowIndex;
                    // Check box column
                    temp = (DataGridViewComboBoxCell)dgvAttributes.CurrentCell;
                    ComboBox comboBox = e.Control as ComboBox;
                    comboBox.SelectedIndexChanged += new EventHandler(comboBox_SelectedIndexChanged);
                }
                else  if (dgvAttributes.CurrentCell.ColumnIndex == 3)
                {
                    TextBox txt = e.Control  as TextBox;
                    txt.KeyPress += new KeyPressEventHandler(txt_SelectedTextChanged);
                }
               else  if (dgvAttributes.CurrentCell.ColumnIndex == 4)
                {
                    TextBox txt = e.Control as TextBox;
                    txt.KeyPress += new KeyPressEventHandler(txt_SelectedTextChanged);
                }
               else  if (dgvAttributes.CurrentCell.ColumnIndex == 5)
                {
                    TextBox txt = e.Control as TextBox;
                    txt.KeyPress += new KeyPressEventHandler(txt_SelectedTextChanged);
                }

            }
            catch (Exception ex)
            { }
        }
        void txt_SelectedTextChanged(object sender,KeyPressEventArgs e)
        {           
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
            {
                e.Handled = true;
            }
            // only allow one decimal point
            if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)
            {
                e.Handled = true;
            }
        }

No comments:

Post a Comment