有没有办法可以在DataGridViewTextBox列中禁用非数字数据?
我的数据库中的字段是浮点数,我希望用户只能输入数值。
答案 0 :(得分:0)
我个人没有遇到过,但我知道几种方法。您可以定义自己的列类型来限制它,或者您可以处理DataGridView事件。
看看这里:http://msdn.microsoft.com/en-us/library/wc5cbb9z.aspx
具体来说:CellValidating
和CellValueChanged
答案 1 :(得分:0)
您还可以尝试侦听DataFridViewTextBox列的编辑控件的TextChanged事件,并防止用户在文本框中输入无效值。 E.x:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
string _prevValue;
int _selLength;
int _selStart;
private bool _ignoreTxtChange;
public Form1()
{
DataGridView dataGridView = new DataGridView();
dataGridView.Dock = DockStyle.Fill;
Controls.Add(dataGridView);
DataTable ds = new DataTable();
ds.Columns.Add("FloatValue", typeof(float));
dataGridView.DataSource = ds;
dataGridView.EditingControlShowing += dataGridView_EditingControlShowing;
}
private void dataGridView_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
DataGridView dataGridView = (DataGridView)sender;
TextBox textBox = e.Control as TextBox;
if (textBox == null)
{
return;
}
textBox.TextChanged -= textBox_TextChanged;
DataGridViewColumn floatColumn = dataGridView.Columns["FloatValue"];
if (dataGridView.CurrentCell.ColumnIndex != floatColumn.Index)
{
return;
}
textBox.TextChanged += textBox_TextChanged;
_prevValue = textBox.Text;
}
void textBox_TextChanged(object sender, EventArgs e)
{
if (_ignoreTxtChange)
{
return;
}
_ignoreTxtChange = true;
TextBox textBox = (TextBox)sender;
float value;
if ((_prevValue == textBox.Text) || float.TryParse(textBox.Text, out value))
{
_prevValue = textBox.Text;
_selLength = textBox.SelectionLength;
_selStart = textBox.SelectionStart;
}
else
{
textBox.Text = _prevValue;
textBox.Select((_selStart == 0) ? 0 : _selStart - 1, _selLength);
}
_ignoreTxtChange = false;
}
}
}