Regarding the problem of DataGrid, how to make the line width cannot be changed by the user. (Ie the row width fixation, cannot change by drag) When defining the DataGrid, set the width
How to click on a row in WinForm, make the data in TEXTBOX in TEXTBOX? DataGrid's KeyPress event
TextBox1.text = MyDataGrid (MyDataGrid.currentcell.Rownumber, 0) TextBox2.text = myDataGrid (MyDataGrid.currentcell.Rownumber, 1) ........
Push
Namespace DataGriddoubleClick {using system; using system.collections; using system.componentmodel; using system.windows.form; using system.data;
public class Form1: System.Windows.Forms.Form {private System.Windows.Forms.DataGrid dataGrid1; private DataSet myDataSet; DateTime gridMouseDownTime; private System.Windows.Forms.Label label1; private System.ComponentModel.Container components = null;
Public form1 () {INITIALIZECMOMPONENT (); gridMousedowntime = DATETIME.NOW; setup ();
Private void setup () {// creates a DataSet MakeDataSet () with 2 Table and 1 and Relation DataGrid1.SetDataBinding (MyDataSet, "Customers");
// Add a style addCustomDataTableStyle ();
Private void makeDataSet () {// creates a DataSet. mydataset = new dataset ("MyDataSet"); // Create 2 DataTables. DataTable Tcust = New DataTable ("Customers"); // Create two columns and added to the first a table DataColumn cCustID = new DataColumn ( "custID"); DataColumn cCustName = new DataColumn ( "custName"); DataColumn cCurrent = new DataColumn ( "custCity"); tCust.Columns.Add (cCustID); tCust.Columns.Add (ccustname); tcust.column.add (ccurrent);
// Add tables to DataSet. MyDataSet.Tables.Add (TCUST); / * Calculate Tables. For each customer, create a DataRow variable * / DATAROW newRow1; // Add record to Customers Table. For (int i = 1; i <4; i ) {newrow1 = tcust.newrow (); newrow1 ["custom"] = (100 * i) .tostring (); tcust.rows.add (newRow1);} tcust.rows [0] [" CustName "] =" Wonderful World of Mengxian] "; tcust.rows [1] [" CustName "] =" Net_Lover "; tcust.rows [2] [" CustName "] =" http: // XML. sz.luohuedu.net/ ";
TCUST.ROWS [0] ["CustCITY"] = "Beijing"; tcust.rows [1] ["custom"] = "Shanghai"; tcust.rows [2] ["custom"] = "Henan";
Private void addcustomDataTyleStyle () {dataGridTableStyle Ts1 = new dataGridtableStyle (); ts1.mappingname = "customers"; // setting attribute TS1.ALTERNATINGCKCOLOR = Color.lightgray;
// add Textbox column styles, so that we can capture mouse events DataGridTextBoxColumn TextCol = new DataGridTextBoxColumn (); TextCol.MappingName = "custID"; TextCol.HeaderText = "number"; TextCol.Width = 100;
// add event handlers TextCol.TextBox.MouseDown = new MouseEventHandler (TextBoxMouseDownHandler); TextCol.TextBox.DoubleClick = new EventHandler (TextBoxDoubleClickHandler); ts1.GridColumnStyles.Add (TextCol);
TextCol = new DataGridTextBoxColumn (); TextCol.MappingName = "custName"; TextCol.HeaderText = "Name"; TextCol.Width = 100; // add event handlers TextCol.TextBox.MouseDown = new MouseEventHandler (TextBoxMouseDownHandler); TextCol. TextBox.doubleClick = New EventHandler (TEXTBOXDOUBLICKHANDLER); Ts1.GridColumnStyles.Add (Textcol);
TextCol = new DataGridTextBoxColumn (); TextCol.MappingName = "custCity"; TextCol.HeaderText = "address"; TextCol.Width = 100; // add event processor TextCol.TextBox.MouseDown = new MouseEventHandler (TextBoxMouseDownHandler); TextCol. TextBox.DoubleClick = new EventHandler (TextBoxDoubleClickHandler); ts1.GridColumnStyles.Add (textCol); dataGrid1.TableStyles.Add (ts1);!} protected override void Dispose (bool disposing) {if (disposing) {if (components = null ) {Components.dispose ();}} Base.dispose (Disposing);
#region Windows Form Designer generated code private void InitializeComponent () {this.dataGrid1 = new System.Windows.Forms.DataGrid (); this.label1 = new System.Windows.Forms.Label (); ((System.ComponentModel.ISupportInitialize ) (this.dataGrid1)) BeginInit ();. this.SuspendLayout (); // // dataGrid1 // this.dataGrid1.CaptionBackColor = System.Drawing.SystemColors.Info; this.dataGrid1.CaptionForeColor = System.Drawing.SystemColors .WindowText; this.dataGrid1.CaptionVisible = false; this.dataGrid1.DataMember = ""; this.dataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText; this.dataGrid1.Location = new System.Drawing.Point (11, 9 This.dataGrid1.name = "DataGrid1"; this.dataGrid1.size = new system.drawing.size (368, 144); this.dataGrid1.tabindex = 0; this.DataGrid1.mousedown = new System.Windows. Forms.mouseeventhandler (this.DataGrid1_mousedown); /// Label1 // this.labe L1.Location = new system.drawing.point (4, 166); this.label1.name = "label1"; this.label1.size = new system.drawing.size (383, 23); this.label1.tabindex = 1; this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.label1.Click = new System.EventHandler (this.Form1_Click); // // Form1 // this.AutoScaleBaseSize = new System.Drawing.Size (5, 13); this.clientsize = new system.drawing.size (387, 201);
This.Controls.addrange (new system.windows.forms.control [] {this.label1, this.dataGrid1}; this.name = "form1"; this.text = "Example of the mouse double-click event"; ((System .ComponentModel.isupportinitialize (this.DataGrid1)))). Endinit (); this.ResumeLayout (false);} #ENDREGION
[Stathread] static void main () {application.run (new form1 ());}
Private Void TextBoxDoubleClickHandler ("Object Sender, Eventargs E) {MessageBox.show (" Double-click Event. The value of the mouse doubles: " ((textbox) .Text.toString ());}
private void TextBoxMouseDownHandler (object sender, MouseEventArgs e) {if (DateTime.Now Private void DataGrid1_mousedown (Object sender, system.windows) {gridmousedowntime = datetime.now; label1.text = "DataGrid1 mouse presses."; Private void form1_click (object sender, system.eventargs e) {label1.text = "";} private void label1_click (object sender, system.eventargs e) {label1.text = ";} this.mydataGrid.currentcellchanged = news.mydataGrid_currentcerchanged; /// private void myDataGrid_CurrentCellChanged (object sender, System.EventArgs e) {textBox1.Text = "Col is" myDataGrid.CurrentCell.ColumnNumber ", Row is" myDataGrid.CurrentCell.RowNumber ", Value is" myDataGrid [myDataGrid. CurrentCell];} and the dsCustomers1 Customers into your private void dataGrid1_Click (object sender, System.EventArgs e) {textBox1.BindingContex [this.dsCustomers1, "Customers"] Position = dataGrid1.BindingContext [this.dsCustomers1.Customers]. .Position; DataGrid's CurserChange event TextBox1.text = MyDataGrid (MyDataGrid.currentcell.Rownumber, 0) TextBox2.text = myDataGrid (MyDataGrid.currentcell.Rownumber, 1) ........ Push The TextBox control is bound Dataset to TextBox1.Database. DataBindings.add (New Binding ("Text", DS, "Customers.custName")); Set DataGridTableStyle (MappingName as a table name) in DataGrid's TableSytle attribute, then add custom DataGridTextBoxColumn (mappingname as field name) in the order you want. Each DataGridTextBoxColumn can set a width independently. In WinForms DataGrid 1. How to achieve line alternating discoloration 2. How to join the link (for example, put the order table in the DataGrid, I want to click any of the rows to pop up a new form, put this order - user information) 3. How to delete information in DataGrid (with Checkbox) DataGridtablesTyle TS1 = New DataGridTableLe (); DataGrid1.datasource = Atable; // Specify the table from dataset (required step) ts1.MappingName = "A"; // Set other properties (optional step) ts1.AlternatingBackColor = Color.LightBlue; // ts1.AllowSorting = false; ts1.BackColor = Color. Cyan; DataGrid1.tables.add (TS1); Ts1.GridColumnStyles [0] .width = 200; ts1.dataGrid.refresh (); Your first question I give an example to you: DataGrid style sheet (DataGridTableStyle) app ... First we first define a DataTable and a DATAROW Private IDTB_TEMP AS NEW DATATABLE PRIVATE IDRW_ROW AS DATAROWPRIVATE SUB GETDATABLE () IDTB_TEMP.COLUMNS.ADD ("prdodr_subodr_code") '' Defines the column name of DataBole idtb_temp.TableName = "SearchTable" Dim ldcl_header As Windows.Forms.DataGridTextBoxColumn Dim ldgts_styles As New Windows.Forms.DataGridTableStyle ldgts_styles.SelectionForeColor = System.Drawing.Color.Yellow '' 'foreground color of the selected row, i.e., font color ldgts_styles.SelectionBackColor = System.drawing.color.brown '' 'Select the background color of the row Color ldgts_styles.BackColor 'color ldgts_styles.AlternatingBackColor datagrid word will be displayed = System.Drawing.Color.Cyan' ldgts_styles.ForeColor = System.Drawing.Color.Coral '' '' datagrid odd lines displayed = System. Drawing.color.cyan '' DataGrid Doll Double Digital Color LDGTS_STYLES.AllowSorting = false '' '' 'Style Table Definition DataGrid is not allowed to be sorted.. LDGTS_Styles.mappingName = "SearchTable" ldcl_header = New Windows.Forms.DataGridTextBoxColumn '' 'instantiate a datagridtextboxcolumn ldcl_header.MappingName = "prdodr_subodr_code"' '' defined hereinbefore referenced "column name" ldcl_header.HeaderText = "first column" '' 'in the table show datagrid List text LDCL_HEADER.Readonly = true '' 'Some columns set to read-only LDCL_Header.TextBox.Borderstyle = Border.Drawing.forecolor = system.drawing.color.red LDGTS_Styles.GridColumnStyles.Add (LDCl_Header) For i as integer = 0 to 7 idrw_row = idtb_temp.newi id/row.item ("prdodr_subodr_code") = "" "& I &" line "idtb_temp.rows.add (idrw_row) Next IDTB_TEMP.DEFAULTVIEW.ALLLOWNEW = false me.dataGrid1.tablestyles.add (ldgts_styles) me.dataGrid1.datasource = idtb_temp end sub The third question: Look at my blog Use Checkbox, Combobxo, and DateTimePicker in DataGrid http://blog.9cbs.net/zwxrain/archive/2005/01/19/25898.aspx 1. After setting the data source DataSource for DataGrid, you can add DataGridTableStyle, and then set its alternatingbackcolor attributes and backcolor properties to the color of the alternate row. Main topic: What is the triggering event in the middle cell clicking on DataGrid? private void dataGrid1_MouseUp (object sender, System.Windows.Forms.MouseEventArgs e) {System.Drawing.Point pt = new Point (eX, eY); DataGrid.HitTestInfo hti = dataGrid1.HitTest (pt); if (hti.Type = = DataGrid.hittesttype.cell) {DataGrid1.currentcell = new DataGridcell (hti.row, hti.column); DataGrid1.Select (hti.row);}} 1. Substructure; How to write after paged page and page number by pagedage with the property generator paging? 2. Edit; Edit the implementation. Look at MSDN, look at it, ask you to ask you to think about it. Thank you! ! Page: public void dg_PageIndexChanged (object source, System.Web.UI.WebControls.DataGridPageChangedEventArgs e) {MyDataGrid.CurrentPageIndex = e.NewPageIndex; BindData ();} Editing: public void edit (object sender, DataGridCommandEventArgs e) {type_dg.EditItemIndex = E.Item.itemindex; binddata ();} public void update (object sender, datagridcommandeventAndeventAndeventAndAndeventAndeventEventEventAndeventEventEventAndeventAndcommandeventAndeventEventEventAndeventEventEventEventAndeventEventEventEventEventAndeventEventEventEventEventEventEventEventEventEventEventEventEventEventEvent) E.Item.cells [0] .controls [0]; TextBox name = (TextBox) E .ITEM.Cells [1] .controls [0]; TextBox Num = (TextBox) E.Item.cells [2] .controls [0]; string Update_oledb = "Update Blog_Type Set B_TYPE_NAME = '" Name.Text "' , b_type_num = '" Num.Text "' where id = '" id.text "' "; OLEDBConnection myconn = new oledbconnection (Application [" strconn "]. Tostring ()); myconn.open (); oledbcommand update_com = new oledbcommand (update_oledb, myconn); Update_com.executenonQuery (); type_dg.edititemindex = -1; myconn.close (); binddata (); Public Void Cancel (Object Sender, DataGridCommandeventArgs E) {type_dg.edititemindex = -1; binddata (); Delete:. Public void delete (object sender, DataGridCommandEventArgs e) {string no = type_dg.Items [e.Item.ItemIndex] .Cells [0] .Text; OleDbConnection myconn = new OleDbConnection (Application [ "strconn"] ToString () ); myconn.Open (); string deleteOleDb = "delete from blog_type where id =" no; OleDbCommand deletecom = new OleDbCommand (deleteOleDb, myconn); deletecom.ExecuteNonQuery (); myconn.Close (); BindData ();} How to change the title and set column content in the WinForm's DataGrid. Table: ID Name STRDATE ENDDATE 1 A 2004/2/1 2005/2/1 Requires the date of the name start date overdue (yes / No) A 2004/2/1 2005/2/1 overdue 365 days thank you! private void Form1_Load (object sender, System.EventArgs e) {SqlConnection CS = new SqlConnection ( "server = mengxianhui; database = SqlPUB2; User Id = sa; password ="); SqlDataAdapter myCommand = new SqlDataAdapter ( "Select lastmodified, objectId from BaseObject ", CS); DataSet myDataSet = new DataSet (); myCommand.Fill (myDataSet," BaseObject "); this.dataGrid1.DataSource = myDataSet.Tables [0]; // set of columns DataGridTextBoxColumn c1 DataGrid = new DataGridTextBoxColumn (); DataGridTextBoxColumn C2 = New DataGridTextBoxColumn (); c1.mappingname = "LastModified"; c2.mappingname = "ObjectID"; C1.Headertext = "Time [Hello, Hawaii]"; c2.headertext = "Number"; c1.format = "YYYY MM Moon DD Day"; c1.width = 200; DataGridTableStyle dts = new DataGridTableStyle (); dts.GridColumnStyles.Add (c1); dts.GridColumnStyles.Add (c2); dts.MappingName = "BaseObject"; this.dataGrid1.TableStyles.Add (dts);} Main topic: DataGrid CheckBoxList application problem You can add a template column, then edit the template column, join a checkbox and a checkboxlist, then name the two controls, add the checkbox1_checkedchanged event, set the checkbox's auto postback to true, then write you at the checkbox1_checkedchanged event. Implemented features. Here is a simple example, delete the DataGrid current row data: (the front data is bound to DataGrid1) string strSQL = "DELETE FROM Table1 WHERE Id = @ Id"; string text = dataGrid1 [dataGrid1.CurrentCell.RowNumber, 0] .ToString (); testDataSet1.Table1.Rows [dataGrid1.CurrentCell.RowNumber] .Delete (); testDataSet1 .AcceptChanges (); sqlDataAdapter2.DeleteCommand.Parameters [ "@ Id"] Value = text;. sqlDataAdapter2.DeleteCommand.Connection.Open (); sqlDataAdapter2.DeleteCommand.ExecuteNonQuery (); sqlDataAdapter2.DeleteCommand.Connection.Close (); theme : Do you ask how to generate adaptive columns in DataGridView? Adaptive column width: 'Dategrid column width control function Public Sub SizeColumnsToContent (ByVal dataGrid As DataGrid, ByVal nRowsToScan As Integer) Dim Graphics As Graphics = dataGrid.CreateGraphics () Dim tableStyle As DataGridTableStyle = New DataGridTableStyle Try DIM DATATABLE AS DATATABLE = CTYPE (DataGrid.DataSource, DataTable) IF -1 = nrowstoscan then nrowstoscan = dataatable.Rows.count Else nrowstoscan = system.math.min (nrowstoscan, datatable.rows.count) endiff dataGrid.TableStyles.Clear () tableStyle.MappingName = dataTable.TableName Dim columnStyle As DataGridTextBoxColumn Dim iWidth As Integer For iCurrCol As Integer = 0 To dataTable.Columns.Count - 1 Dim dataColumn As DataColumn = dataTable.Columns (iCurrCol) columnStyle = New DataGridTextBoxColumn columnStyle.TextBox.Enabled = True columnStyle.HeaderText = dataColumn.ColumnName columnStyle.MappingName = dataColumn.ColumnName iWidth = CInt (Graphics.MeasureString (columnStyle.HeaderText, dataGrid.Font) .Width) Dim dataRow As DataRow For iRow As Integer = 0 To nRowsToScan - 1 dataRow = dataTable.Rows (iRow) If dataRow (dataColumn.ColumnName) <> Nothing Then Dim iColWidth As Integer = CInt (Graphics.MeasureString (dataRow.ItemArray (iCurrCol) .ToString (), dataGrid.Font) .Width Dim iColHight As Integer = CInt (Graphics.MeasureString (dataRow.ItemArray (iCurrCol) .ToString (), dataGrid.Font) .Height) iWidth = CInt (System.Math.Max (iWidth, iColWidth)) End If Next columnStyle.Width = iWidth 10 tableStyle.GridColumnStyles.Add (columnStyle) Next dataGrid.TableStyles.Add (tableStyle) Catch ex As Exception MessageBox.Show (ex.Message) Finally Graphics.Dispose () End Try End Sub Main topic: Is there a simple way to hide the DataGrid in WinForm? I also use DataGrid.TablesTyles [Table] .vercolumnstyles [0] .width = 0; doing this. It should be no other way. Master: How to capture DataGrid's double-click event in WinForm? Namespace DataGriddoubleClick {using system; using system.collections; using system.componentmodel; using system.windows.form; using system.data; public class Form1: System.Windows.Forms.Form {private System.Windows.Forms.DataGrid dataGrid1; private DataSet myDataSet; DateTime gridMouseDownTime; private System.Windows.Forms.Label label1; private System.ComponentModel.Container components = null; Public form1 () {INITIALIZECMOMPONENT (); gridMousedowntime = DATETIME.NOW; setup (); Private void setup () {// creates a DataSet MakeDataSet () with 2 Table and 1 and Relation DataGrid1.SetDataBinding (MyDataSet, "Customers"); // Add a style addCustomDataTableStyle (); Private void makeDataSet () {// creates a DataSet. mydataset = new dataset ("MyDataSet"); // Create 2 DataTables. DataTable Tcust = New DataTable ("Customers"); // Create two columns and added to the first a table DataColumn cCustID = new DataColumn ( "custID"); DataColumn cCustName = new DataColumn ( "custName"); DataColumn cCurrent = new DataColumn ( "custCity"); tCust.Columns.Add (cCustID); tCust.Columns.Add (ccustname); tcust.column.add (ccurrent); // Add tables to DataSet. MyDataSet.Tables.Add (TCUST); / * Calculate Tables. For each customer, create a DataRow variable * / DATAROW newRow1; // Add record to Customers Table. For (int i = 1; I <4; i ) {newrow1 = tcust.newrow (); newrow1 ["custom"] = (100 * i) .tostring (); tcust.rows.add (newrow1); TCUST.ROWS [0] ["custname"] = "Wonderful World of Mengxian]"; tcust.rows [1] ["CustName"] = "Net_lover"; tcust.rows [2] ["CustName"] = "http://xml.sz.luohuedu.net/";tcust.rows[0]["custcity"] = "Beijing"; tcust.rows [1] ["custom"] = "Shanghai"; TCUST. Rows [2] ["CustCITY"] = "Henan"; Private void addcustomDataTyleStyle () {dataGridTableStyle Ts1 = new dataGridtableStyle (); ts1.mappingname = "customers"; // setting attribute TS1.ALTERNATINGCKCOLOR = Color.lightgray; // add Textbox column styles, so that we can capture mouse events DataGridTextBoxColumn TextCol = new DataGridTextBoxColumn (); TextCol.MappingName = "custID"; TextCol.HeaderText = "number"; TextCol.Width = 100; // add event handlers TextCol.TextBox.MouseDown = new MouseEventHandler (TextBoxMouseDownHandler); TextCol.TextBox.DoubleClick = new EventHandler (TextBoxDoubleClickHandler); ts1.GridColumnStyles.Add (TextCol); TextCol = new DataGridTextBoxColumn (); TextCol.MappingName = "custName"; TextCol.HeaderText = "Name"; TextCol.Width = 100; // add event handlers TextCol.TextBox.MouseDown = new MouseEventHandler (TextBoxMouseDownHandler); TextCol. TextBox.doubleClick = New EventHandler (TEXTBOXDOUBLICKHANDLER); Ts1.GridColumnStyles.Add (Textcol); TextCol = new DataGridTextBoxColumn (); TextCol.MappingName = "custCity"; TextCol.HeaderText = "address"; TextCol.Width = 100; // add event processor TextCol.TextBox.MouseDown = new MouseEventHandler (TextBoxMouseDownHandler); TextCol. TextBox.DoubleClick = new EventHandler (TextBoxDoubleClickHandler); ts1.GridColumnStyles.Add (textCol); dataGrid1.TableStyles.Add (ts1);!} protected override void Dispose (bool disposing) {if (disposing) {if (components = null ) {Components.dispose ();}} Base.dispose (Disposing); #region Windows Form Designer generated code private void InitializeComponent () {this.dataGrid1 = new System.Windows.Forms.DataGrid (); this.label1 = new System.Windows.Forms.Label (); ((System.ComponentModel.ISupportInitialize ) (this.dataGrid1)) BeginInit ();. this.SuspendLayout (); // // dataGrid1 // this.dataGrid1.CaptionBackColor = System.Drawing.SystemColors.Info; this.dataGrid1.CaptionForeColor = System.Drawing.SystemColors .WindowText; this.dataGrid1.CaptionVisible = false; this.dataGrid1.DataMember = ""; this.dataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText; this.dataGrid1.Location = new System.Drawing.Point (11, 9 This.dataGrid1.name = "DataGrid1"; this.dataGrid1.size = new system.drawing.size (368, 144); this.dataGrid1.tabindex = 0; this.DataGrid1.mousedown = new System.Windows. Forms.mouseeventhandler (this.DataGrid1_mousedown); /// Label1 // this.labe L1.Location = new system.drawing.point (4, 166); this.label1.name = "label1"; this.label1.size = new system.drawing.size (383, 23); this.label1.tabindex = 1; this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.label1.Click = new System.EventHandler (this.Form1_Click); // // Form1 // this.AutoScaleBaseSize = new System.Drawing.Size (5, 13); this.clientsize = new system.drawing.size (387, 201); This.Controls.addrange (new system.windows.forms.control [] {this.label1, this.dataGrid1}; this.name = "form1"; this.text = "Example of the mouse double-click event"; ((System .ComponentModel.isupportinitialize (this.DataGrid1)))). Endinit (); this.ResumeLayout (false);} #ENDREGION [Stathread] static void main () {application.run (new form1 ());} Private Void TextBoxDoubleClickHandler ("Object Sender, Eventargs E) {MessageBox.show (" Double-click Event. The value of the mouse doubles: " ((textbox) .Text.toString ());} private void TextBoxMouseDownHandler (object sender, MouseEventArgs e) {if (DateTime.Now Private void DataGrid1_mousedown (Object sender, system.windows) {gridmousedowntime = datetime.now; label1.text = "DataGrid1 mouse presses."; Private void form1_click (object sender, system.eventargs e) {label1.text = "";} private void label1_click (object sender, system.eventargs e) {label1.text = ""}}} Namespace DataGriddoubleClick {using system; using system.collections; using system.componentmodel; using system.windows.form; using system.data; public class Form1: System.Windows.Forms.Form {private System.Windows.Forms.DataGrid dataGrid1; private DataSet myDataSet; DateTime gridMouseDownTime; private System.Windows.Forms.Label label1; private System.ComponentModel.Container components = null; public Form1 () {INITIALIZEC MOMPONENT (); gridmousedowntime = datetime.now; setup (); Private void setup () {// creates a DataSet MakeDataSet () with 2 Table and 1 and Relation DataGrid1.SetDataBinding (MyDataSet, "Customers"); // Add a style addCustomDataTableStyle (); Private void makeDataSet () {// creates a DataSet. mydataset = new dataset ("MyDataSet"); // Create 2 DataTables. DataTable Tcust = New DataTable ("Customers"); // Create two columns and added to the first a table DataColumn cCustID = new DataColumn ( "custID"); DataColumn cCustName = new DataColumn ( "custName"); DataColumn cCurrent = new DataColumn ( "custCity"); tCust.Columns.Add (cCustID); tCust.Columns.Add (ccustname); tcust.column.add (ccurrent); // Add tables to DataSet. MyDataSet.Tables.Add (TCUST); / * Calculate Tables. For each customer, create a DataRow variable * / DATAROW newRow1; // Add record to Customers Table. For (int i = 1; I <4; i ) {newrow1 = tcust.newrow (); newrow1 ["custom"] = (100 * i) .tostring (); tcust.rows.add (newrow1); TCUST.ROWS [0] ["custname"] = "Wonderful World of Mengxian]"; tcust.rows [1] ["CustName"] = "Net_lover"; tcust.rows [2] ["CustName"] = "http://xml.sz.luohuedu.net/"; TCUST.ROWS [0] ["CustCITY"] = "Beijing"; tcust.rows [1] ["custom"] = "Shanghai"; tcust.rows [2] ["custom"] = "Henan"; private void AddCustomDataTableStyle () {DataGridTableStyle ts1 = new DataGridTableStyle (); ts1.MappingName = "Customers"; // set the property ts1.AlternatingBackColor = Color.LightGray; // add Textbox column styles, so that we can capture mouse events DataGridTextBoxColumn TextCol = new DataGridTextBoxColumn (); textcol.mappingname = "custom"; textcol.Headertext = "serial number"; TextCol.width = 100; // add event handlers TextCol.TextBox.MouseDown = new MouseEventHandler (TextBoxMouseDownHandler); TextCol.TextBox.DoubleClick = new EventHandler (TextBoxDoubleClickHandler); ts1.GridColumnStyles.Add (TextCol); TextCol = new DataGridTextBoxColumn (); TextCol.MappingName = "custName"; TextCol.HeaderText = "Name"; TextCol.Width = 100; // add event handlers TextCol.TextBox.MouseDown = new MouseEventHandler (TextBoxMouseDownHandler); TextCol. TextBox.doubleClick = New EventHandler (TEXTBOXDOUBLICKHANDLER); Ts1.GridColumnStyles.Add (Textcol); TextCol = new DataGridTextBoxColumn (); TextCol.MappingName = "custCity"; TextCol.HeaderText = "address"; TextCol.Width = 100; // add event processor TextCol.TextBox.MouseDown = new MouseEventHandler (TextBoxMouseDownHandler); TextCol. TEXTBOX.DOUBLICK = New EventHandler Protected Override Void Dispose (bool disposing) {if (disponents! = null) {components.dispose ();}} Base.Dispose (Disposing); #region Windows Form Designer generated code private void InitializeComponent () {this.dataGrid1 = new System.Windows.Forms.DataGrid (); this.label1 = new System.Windows.Forms.Label (); ((System.ComponentModel.ISupportInitialize ) (this.dataGrid1)) BeginInit ();. this.SuspendLayout (); // // dataGrid1 // this.dataGrid1.CaptionBackColor = System.Drawing.SystemColors.Info; this.dataGrid1.CaptionForeColor = System.Drawing.SystemColors .WindowText; this.dataGrid1.CaptionVisible = false; this.dataGrid1.DataMember = ""; this.dataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText; this.dataGrid1.Location = new System.Drawing.Point (11, 9 This.dataGrid1.name = "DataGrid1"; this.dataGrid1.size = new system.drawing.size (368, 144); this.dataGrid1.tabindex = 0; this.DataGrid1.mousedown = new System.Windows. Forms.mouseeventhandler (this.DataGrid1_mousedown); /// Label1 // this.labe L1.Location = new system.drawing.point (4, 166); this.label1.name = "label1"; this.label1.size = new system.drawing.size (383, 23); this.label1.tabindex = 1; this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.label1.Click = new System.EventHandler (this.Form1_Click); // // Form1 // this.AutoScaleBaseSize = new System.Drawing.Size (5, 13); this.clientsize = new system.drawing.size (387, 201); This.Controls.addrange (new system.windows.forms.control [] {this.label1, this.dataGrid1}; this.name = "form1"; this.text = "Example of the mouse double-click event"; ((System .ComponentModel.isupportinitialize (this.DataGrid1)))). Endinit (); this.ResumeLayout (false);} #ENDREGION [Stathread] static void main () {application.run (new form1 ());} Private Void TextBoxDoubleClickHandler ("Object Sender, Eventargs E) {MessageBox.show (" Double-click Event. The value of the mouse doubles: " ((textbox) .Text.toString ());} private void TextBoxMouseDownHandler (object sender, MouseEventArgs e) {if (DateTime.Now Private void DataGrid1_mousedown (Object sender, system.windows) {gridmousedowntime = datetime.now; label1.text = "DataGrid1 mouse presses."; Private void form1_click (object sender, system.eventargs e) {label1.text = "";} private void label1_click (object sender, system.eventargs e) {label1.text = ""}}} Main topic: How to set the background color of the DataGrid in the C # (WinForm), or the color of the font? Master help! ! Using system.drawing; using system.componentmodel; using system.windows.form; using system.data; Namespace DataGridcellFormatting {/// /// tDO: Add any constructor code after the initializationComponent call //} /// #REGION Windows Form Designer The code /// } #endregion Private void formatgridcells (Object Sender, DataGridFormatCelleventargs e) {// color row 1 redif (E.ROW == 0) E.BackBrush = brushes.red; if (E.Row == 1) E.BackBrush = brushes.red; IF (E.Row == 2) E.BackBrush = brushes.red; if (E.Row == 3) E.BackBrush = brushes.red; // color column 4 blue // if (E.COLUMN == 4 ) // E.BackBrush = brushes.blue; // set font of some cells to bold // IF ((E.ROW E.COLUMN)% 5 == 0) // e.TextFont = New font (e. TEXTFONT.NAME, E.TEXTFONT.SIZE, FONTSTYLE.BOLD); // SET TEXTCOLOR OF SOME CELLS To Blue // IF ((E.ROW E.COLUMN)% 8 == 0) // E.Forebrush = Brushes .Dodgerblue; // set font of some calls to bold, underline, italic with white text on green background // == 0) // {// e.TextFont = New font (e.TextFont.Name, E.TEXTFONT.SIZE, FONTSTYLE.BOLD | FONTSTYLE.ITALIC | FONTSTYLE.UNDERLINE); // E.Forebrush = Brushes.White; // E.BackBrush = brushes.green; // } } Private DataTable SomeDataTable () {DataTable DT = New DataBole ("MyTable"); // add some columnint ncols = 10; for (int J = 0; j // add some rowsint nrows = 40; for (INT i = 0; i Dt.defaultView.allownew = false; // Turn Off Append Rowreturn Dt;} Private Void AddCellFormattingColumnStyles (DataGrid Grid, Formatcelle) {DataGridtableTyle Ts = New DataGridtableStyle (); DataTable DT = (DATATABLE) Grid.DataSource; ts.MappingName = dt.TableName; for (int j = 0; j Grid.tables.clear (); grid.tablestyles.add (ts); } private void DataGrid1_navigate (Object Sender, System.windows.Forms.naVigateEventArgs Ne) { } Private void form2_load (object sender, system.eventargs e) {this.DataGrid1.datasource = somedataable (); AddcellFormattingColumnStyles (this.DataGrid1, New FormatcellendHandler (FormatGridcells); Public Delegate Void Formatcelle (Object Sender, DataGridFormatCelleventargs E); public class DataGridFormatCellEventArgs: EventArgs {private int _column; private int _row; private Font _font; private Brush _backBrush; private Brush _foreBrush; private bool _useBaseClassDrawing; public DataGridFormatCellEventArgs (int row, int col, Font font1, Brush backBrush, Brush foreBrush) {_ row = row; _column = col; _font = font1; _backBrush = backBrush; _foreBrush = foreBrush; _useBaseClassDrawing = false;} Public int column {get {_column = value;}} public int = value;}} public int rot = value;}}} public textfont;}} public font textfont;} set {_font = Value;}} public Brush BackBrush {get {return _backBrush;} set {_backBrush = value;}} public Brush ForeBrush {get {return _foreBrush;} set {_foreBrush = value;}} public bool UseBaseClassDrawing {get {return _useBaseClassDrawing;} set {_useBaseClassDrawing = Value;}}} public class DataGridFormattableTextBoxColumn: DataGridTextBoxColumn {// in your handler, set the EnableValue to true or false, depending upon the row & colpublic event FormatCellEventHandler SetCellFormat; private int _col; Public DataGridFormattableTextBoxColumn (int co) {_ col = col; protected override void Paint (System.Drawing.Graphics g, System.Drawing.Rectangle bounds, System.Windows.Forms.CurrencyManager source, int rowNum, System.Drawing.Brush backBrush, System.Drawing.Brush foreBrush, bool alignToRight) {DataGridFormatCellEventArgs e = new DataGridFormatCellEventArgs (rowNum, this._col, this.DataGridTableStyle.DataGrid.Font, backBrush, foreBrush); if (SetCellFormat = null!) {SetCellFormat (this, e);} if (e.UseBaseClassDrawing) base.Paint ( g, bounds, source, rowNum, backBrush, foreBrush, alignToRight); else {g.FillRectangle (e.BackBrush, bounds); g.DrawString (this.GetColumnValueAtRow (source, rowNum) .ToString (), e.TextFont, e .Forebrush, bounds.x, bounds.y;} if (e.textfont! = This.dataGridtable.DataGrid.font) E.TEXTFONT.DISPOSE (); protected override void Edit (System.Windows.Forms.CurrencyManager source, int rowNum, System.Drawing.Rectangle bounds, bool readOnly, string instantText, bool cellIsVisible) {// comment to make cells unable to become editablebase.Edit (source, rowNum , Bounds, Readonly, InstantText, Cellisvisible;} }}} Just change the line in formatgridcells. Master: How to make WinForm's DataGrid controls are read-only properties, some are not read-only properties 1, manual: DataGrid-> Properties -> TableStyles-> GridCoumnStyles 2, code: this.DataGrid1.tablestyles ["Tablename"]. GridColumnStyles ["ID"]. Readonly = true; THIS.DATAGRID1.TABLESTYLES ["TableName"]. GridColumnStyles ["ID"]. Readonly = true; Columns displayed and hidden in DataGrid ! <% @ Page Language = "vb" AutoEventWireup = "false" Codebehind = "ShowHideCols.aspx.vb" Inherits = "aspxWeb.ShowHideCols"%> Public Class ShowHideCols Inherits System.Web.UI.Page Protected WithEvents btnShow As System.Web.UI.WebControls.Button Protected WithEvents btnHide As System.Web.UI.WebControls.Button Protected WithEvents dtgCusts As System.Web.UI.WebControls.DataGrid #Region "The code" of the web form designer " 'This call is required for the web form designer. End Sub Private sub page_init (Byval e as system.Event, byval e as system.eventargs _ handles mybase.init 'Codegen: This method call is required by the Web Form Designer' Do not modify it using the code editor. InitializationComponent () End Sub #End region Private Sub Page_Load (Byval E AS System.Event, Byval E AS System.EventArgs) _ Handles mybase.load 'Place the initialization page here BTNSHOW.TEXT = "Display column" btnhide.text = "Hidden Column" DTGCUSTS .Columns (1) .Headertext = "" DTGCUSTS.COLUMNS (0) .Headertext = "Title" DTGCUSTS.COLUMNS (2) .Headertext = "Release Date" DTGCUSTS.COLUMNS (3) .Headertext = "Edit" if not ispostback Then bindthedata () end if End Sub Sub BindTheData () Dim objConn As OleDbConnection Dim objCmd As OleDbCommand objConn = New OleDbConnection ( "Provider = Microsoft.Jet.OLEDB.4.0; Data Source =" _ Server.MapPath ( "Test.mdb")) Dim strSql As String strSql = "SELECT Top 10 id, Title, CreateDate FROM Document" objCmd = New OleDbCommand (strSql, objConn) objConn.Open () dtgCusts.DataSource = objCmd.ExecuteReader () dtgCusts.DataBind () objConn.Close () objConn.Dispose ( ) End Sub Sub ShowDetails (ByVal sender As System.Object, ByVal e As System.EventArgs) Dim intCounter As Integer For intCounter = 1 To dtgCusts.Columns.Count - 1 dtgCusts.Columns (intCounter) .Visible = True Next End SubSub HideDetails (ByVal sender As System.Object, ByVal e As System.EventArgs) Dim intCounter As Integer For intCounter = 1 To dtgCusts.Columns.Count - 1 dtgCusts.Columns (intCounter) .Visible = False Next End Sub END CLASS Main topic: How to generate adaptive columns in DataGridView? You can implement: Private Void GridView1_mousemove (Object sender, system.windows.Forms.MouseEventArgs e) {int a = ex / colkeywords.width; int b = (E.Y 10) / Colkeywords.width-3 ; if (a> = 0 && b> = 0 && a