Lij*_*ina 5 .net c# datagridview winforms
我TextBox在网格中添加了控件:我希望我的DataGridView TextBox列保存没有任何小数值的数字.我该怎么做?
在要限制输入的列中进行编辑时,可以处理 DataGridView.EditingControlShowing 事件将编辑控件投射到 TextBox,并将 KeyPress 事件附加到 TextBox,在 KeyPress 事件处理函数中,我们可以调用 char.IsNumber( ) 方法来限制键盘输入,如下所示:
private void Form1_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("c1", typeof(int));
dt.Columns.Add("c2");
for (int j = 0; j < 10; j++)
{
dt.Rows.Add(j, "aaa" + j.ToString());
}
this.dataGridView1.DataSource = dt;
this.dataGridView1.EditingControlShowing +=
new DataGridViewEditingControlShowingEventHandler(
dataGridView1_EditingControlShowing);
}
private bool IsHandleAdded;
void dataGridView1_EditingControlShowing(object sender,
DataGridViewEditingControlShowingEventArgs e)
{
if (!IsHandleAdded &&
this.dataGridView1.CurrentCell.ColumnIndex == 0)
{
TextBox tx = e.Control as TextBox;
if (tx != null)
{
tx.KeyPress += new KeyPressEventHandler(tx_KeyPress);
this.IsHandleAdded = true;
}
}
}
void tx_KeyPress(object sender, KeyPressEventArgs e)
{
if (!(char.IsNumber(e.KeyChar) || e.KeyChar == '\b'))
{
e.Handled = true;
}
}
Run Code Online (Sandbox Code Playgroud)