DataGrid skills (1)

zhaozj2021-02-16  44

DataGrid skills (1)

------- How to Shield Unit Input

Sometimes I listen to some friends complaining that .NET's DataGrid is not very easy. As far as my personal experience, DataGrid's function is very powerful, which can make us complete a variety of work, but unfortunately, it is not simple enough. I have accumulated some solutions to some problems that I often encountered, and now I summarize them for your reference.

One problem that often encounters is: We hope that a column of DataGrid can only enter a specific text, such as: You cannot enter a number. The following example shows how to implement this function. Create a Window application, join a DataGrid and SqlConnection, connect the SQL database Northwind.

namespace WindowsApplication1 {public class Form1: System.Windows.Forms.Form {private myDataGrid dataGrid1; private System.Data.SqlClient.SqlConnection sqlConnection1; // global variables added oldValue, which represents a cell with the original text. PRIVATE STRING OLDVALUE;

private void Form1_Load (object sender, System.EventArgs e) {oldValue = ""; SqlDataAdapter sda = new SqlDataAdapter ( "select LastName, FirstName from employees", this.sqlConnection1); DataSet ds = new DataSet (); sda.Fill ( ds, "employees"); DataGridTableStyle ats = new DataGridTableStyle (); ats.MappingName = "employees"; DataGridColorColumn dcs1 = new DataGridColorColumn (); dcs1.HeaderText = "lastname"; ats.GridColumnStyles.Add (dcs1); DataGridTextBoxColumn dcs2 = new DataGridTextBoxColumn (); dcs2.HeaderText = "firstname"; dcs2.MappingName = "FirstName"; dcs2.TextBox.TextChanged = new EventHandler (DataGridTextChanged); dcs2.TextBox.Enter = new EventHandler (DataGridTextBox_Enter); ats.GridColumnStyles. Add (DCS2); this.dataGrid1.tablestyles.add (ats); this.DataGrid1.datasource = DS; this.DataGrid1.datamember = "EMPLOYEES";

Text oldValue private void DataGridTextBox_Enter (object sender, EventArgs e) {// When a cell receives focus, the recording of the cell = ((DataGridTextBoxColumn) this.dataGrid1.TableStyles [0] .GridColumnStyles [1]). TextBox. Text;} private void DataGridTextChanged (object sender, EventArgs e) {int index = 0; string str = ((DataGridTextBoxColumn) this.dataGrid1.TableStyles [0] .GridColumnStyles [1]) TextBox.Text;. // when the cell When the text changes, check if there is an illegal character while (index

转载请注明原文地址:https://www.9cbs.com/read-26530.html

New Post(0)