DataGridView的单元格字符格式设定

herryking 2011-02-24 03:41:24
这个问题我想了半天,最后是在单元格的 KeyPress事件中解决的。具体代码如下:
    //控制单元格内只能输入整数或带小数点的俩位小数

  private void tb_KeyPress_Decimal(object sender, KeyPressEventArgs e)
{
DataGridViewTextBoxEditingControl tb = sender as DataGridViewTextBoxEditingControl;
try
{
string Text = tb.Text;
if (e.KeyChar == 46)//如果输入的是小数点
{
if (Text == e.KeyChar.ToString())
{
tb.Text = "";
e.Handled = true;
}
if (Text.IndexOf(e.KeyChar) > 0)
{
e.Handled = true;
}
}
else if (Text.IndexOf(".") < 0 && Text.Length + 1 >= 7 && tb.SelectedText == "") //整数位不能超过6位
{
e.Handled = true;
}    //tb.SelectedText 是判断有没有选中的字符
else if (Text.IndexOf(".") > 0 && Text.Split('.')[1].Length + 1 > 2 && tb.SelectedText == "") //小数位不能超过2位
{
e.Handled = true;
}
if ((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 46 && e.KeyChar != 8 && e.KeyChar != 13)
{
e.Handled = true;
}


}
catch
{

}
}



如果谁有更好的解决办法,欢迎发表与讨论
...全文
235 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
bdmh 2011-02-24
  • 打赏
  • 举报
回复
很多地方都可以处理,哪个你自己觉得方便就用那个吧
yalan 2011-02-24
  • 打赏
  • 举报
回复
通过EditingControlShowing事件解决这个问题.


private void InputInteger(object sender, KeyPressEventArgs e)
{ //限制数量只能输入整数
if ((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar != 13 && e.KeyChar != 22 && e.KeyChar != 3 && e.KeyChar != 24 && e.KeyChar != 26)
{
e.Handled = true;
}
else
{
//如果第一位输入0,则不接收
if (e.KeyChar == 48 && (((TextBox)sender).SelectionStart == 0))
e.Handled = true;
//如果是回车键,则按tab序进行跳转
if (e.KeyChar == 13)
{
SendKeys.Send("{TAB}");
e.Handled = true;
}
}
}

#region 编辑某列的值事件
private void dgv_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (this.dgv.CurrentCell.ColumnIndex==5)//如果是第五列,只允许输入整数
{
e.Control.KeyPress += new KeyPressEventHandler(InputInteger);
}
}

#endregion

110,526

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧