I have DataGridView control with 2 editable columns. 1 of them (column 1) should accept only digits and decimal point, another (column 2) only digits.
void dGr_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (dGr.CurrentCell.ColumnIndex == 1)
{
if (e.Control is TextBox)
{
TextBox tb = e.Control as TextBox;
tb.KeyPress += new KeyPressEventHandler(tb_KeyPress);
}
}
else if (dGr.CurrentCell.ColumnIndex == 2)
{
if (e.Control is TextBox)
{
TextBox tb = e.Control as TextBox;
tb.KeyPress += new KeyPressEventHandler(tb_KeyPress2);
}
}
}
void tb_KeyPress(object sender, KeyPressEventArgs e)
{
if (!(char.IsDigit(e.KeyChar)))
{
if (e.KeyChar != '\b' && e.KeyChar != '.') //allow the backspace key and decimal point
e.Handled = true;
}
}
void tb_KeyPress2(object sender, KeyPressEventArgs e)
{
if (!(char.IsDigit(e.KeyChar)))
{
if (e.KeyChar != '\b')
e.Handled = true;
}
}
The problem: at the beginning column 1 accepts only digits and decimal point as intended, but after I try to edit column 2 cells, column 1 stops taking a decimal point and behaves exactly like column 2. Any idea why it happens?
Also -
I'd like to change a column's background color to yellow.
dGr.Columns["MyColumn"].DefaultCellStyle.BackColor = Color.LightYellow;
That statement will not change the alternating rows DefaultCellStyle. So I have only half of all rows with yellow background. How to fix that?