Locations of visitors to this page


Onteora Software - DataGrid

Onteora Software

Ken Tucker's Blog

About the author

Author Name is someone.
E-mail me Send mail

Recent posts

Recent comments

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2008

Datagrid Validation

Datagrid Validation


The DataGridView has a CellValidating Event to validate the data entered. Here is how to do it with the DataGrid.


There are 2 method to do this. My method is to add a tablestyle to the datagrid. For the cells I want to validate I handle the DataGridTextBoxColumn's Textbox's Validate event. George Shepherd's method is use the CurrentCellChanged event. You can read about this method in the Windows Forms FAQ.



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace CSDatagrid
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            String strConn = "Server = .\\SqlExpress;Database = Pubs;Integrated Security = SSPI;";
            DataTable dt = new DataTable();
            SqlConnection conn = new SqlConnection(strConn);
            SqlDataAdapter da = new SqlDataAdapter("Select Title, price from titles", conn);
            da.Fill(dt);
            dataGrid1.DataSource = dt;
            CurrencyManager cm = this.BindingContext[dt] as CurrencyManager;
            PropertyDescriptor pd = cm.GetItemProperties()["price"];

            DataGridTableStyle ts = new DataGridTableStyle();
            ts.MappingName = dt.TableName;

            DataGridTextBoxColumn tcTitle = new DataGridTextBoxColumn();
            tcTitle.MappingName = "Title";
            tcTitle.HeaderText = "Title";
            tcTitle.Width = 250;
            DataGridTextBoxColumn tcPrice = new DataGridTextBoxColumn(pd, "c2");
            tcPrice.MappingName = "price";
            tcPrice.HeaderText = "Book Price";
            tcPrice.Width = 100;
            tcPrice.TextBox.Validating += new CancelEventHandler(TextBox_Validating);
            ts.GridColumnStyles.Add(tcTitle);
            ts.GridColumnStyles.Add(tcPrice);

            dataGrid1.TableStyles.Add(ts);
        }

        void TextBox_Validating(Object sender, CancelEventArgs e)
        {
            TextBox txt = (TextBox)sender;
            txt.Text = txt.Text.Replace("$", "");
        }

    }
}

You will find a VB example on the VB-Tips Website

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: DataGrid | C#
Posted by Ken Tucker on Tuesday, December 19, 2006 11:12 PM
Permalink | Comments (0) | Post RSSRSS comment feed