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