English 中文(简体)
DataGridView 校验
原标题:DataGridView Validation
  • 时间:2012-05-26 07:14:54
  •  标签:
  • c#

对于文本框,我有一个数据验证方法 像这样:

string allowedCharacterSet = "1234567890
";

if (allowedCharacterSet.Contains(e.KeyChar.ToString()) == false)
{
        e.Handled = true;
}

它的工作方式是,如果用户键入一个不允许输入CharacterSet的字符,该字符就不会出现在文本框中,从而阻止他们输入无效数据。

我的问题是: 我如何将这个应用到 DataGridView 中? 假设我有三个单元格 - 第一个是名字, 所以我只想要字母。 第二个是数量整数, 所以只有数字。 第三个是电子邮件地址, 所以在允许的 CharacterSet 字符串中有数字、 字母、 时段和 @ 符号。 这些我很容易做到, 但是因为您无法将 KeyPress 事件附加到 DataGridView 单个单元格中, 我不知道该怎么办 。

问题回答

您必须将其应用到 DataGridView 单元格验证事件中。 下面是用来限制值在 0- 100 之间的一个例子。 您可以编辑验证 。

// validation on dgvLotDetail s Yield Column (only numeric and between 0 to 100 allowed)
    private void dgvLotDetail_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
    {
        if (dgvLotDetail.Rows[e.RowIndex].Cells[txtYield.Index].Value != null)
        {
            if (e.ColumnIndex == txtYield.Index)
            {
                int i;
                if ( !int.TryParse(Convert.ToString(e.FormattedValue), out i) ||
                    i < 0 ||
                    i > 100 )
                {
                    e.Cancel = true;
                    MessageBox.Show("Enter only integer between 0 and 100.");
                }
                else
                {
                }
            }
        }
    }




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签