Try this:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace daniweb
{
public partial class frmGridView2 : Form
{
DataTable dt;
private TextBox editingBox; //I cant find where the gridView holds the reference
public frmGridView2()
{
InitializeComponent();
editingBox = default(TextBox);
}
private void frmGridView2_Load(object sender, EventArgs e)
{
dt = new DataTable();
dt.Columns.Add(new DataColumn("string1", typeof(string)));
dt.Columns.Add(new DataColumn("int1", typeof(int)));
DataRow row = dt.NewRow();
row[0] = "string value";
row[1] = 31415;
dt.Rows.Add(row);
dataGridView1.Columns[0].DataPropertyName = "string1";
dataGridView1.Columns[0].Name = "string1";
dataGridView1.Columns[1].DataPropertyName = "int1";
dataGridView1.Columns[1].Name = "int1";
dataGridView1.DataSource = dt;
}
private void button1_Click(object sender, EventArgs e)
{
System.Diagnostics.Debugger.Break();
}
private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
if (e.ColumnIndex == dataGridView1.Columns["int1"].Index) //this is our numeric column
{
int i;
if (!int.TryParse(Convert.ToString(e.FormattedValue), out i))
{
e.Cancel = true;
MessageBox.Show("must be numeric");
}
}
}
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (dataGridView1.CurrentCell.ColumnIndex < 0) //i dont know if it ever fires with -1, so to be safe
return;
if (dataGridView1.CurrentCell.ColumnIndex != dataGridView1.Columns["int1"].Index) //not our numeric column
return;
TextBox tb = (dataGridView1.EditingControl as TextBox);
if (tb == null)
{
System.Diagnostics.Debugger.Break(); //you changed it to a non TextBox control. Add more support
return;
}
editingBox = tb;
tb.KeyPress += new KeyPressEventHandler(tb_KeyPress);
tb.TextChanged += new EventHandler(tb_TextChanged);
}
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
if (editingBox != null)
{
//Need to clean up our event handlers so the other columns can have string values
editingBox.KeyPress -= new KeyPressEventHandler(tb_KeyPress);
editingBox.TextChanged -= new EventHandler(tb_TextChanged);
editingBox = null;
}
}
void tb_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsNumber(e.KeyChar))
e.Handled = true;
}
void tb_TextChanged(object sender, EventArgs e)
{
//This handles if they paste crap in the textbox since that doesn't fire the KeyDown event
TextBox tb = (sender as TextBox);
int i;
if (!string.IsNullOrEmpty(tb.Text) && !int.TryParse(tb.Text, out i))
{
StringBuilder sb = new StringBuilder();
for (int i1 = 0; i1 < tb.Text.Length; i1++)
{
if (char.IsNumber(tb.Text[i1]))
sb.Append(tb.Text[i1]);
}
tb.Text = sb.ToString();
}
}
}
}
sknake
Industrious Poster
4,954 posts since Feb 2009
Reputation Points: 1,764
Solved Threads: 735