DataGrid is big, discovered an article, but looked at it ..

xiaoxiao2021-03-06  42

I hope some people translate ...

5 Data Grid

A DataGrid is used to display an independent Table or a collection of Tables contained in a DataSet. It also provides a UI for editing, deleting and inserting records along with a set of event notifications for programmatic response and for data change tracking. In addition it supports a collection of DataGrid Table Styles that provides custom presentation for each table in its DataSource WebForms and WinForms can both display a DataGrid bound and unbound to a database;. however, there are significant differences in usage.

This Section Will Present How To Work with a DataGrid and Its Many Features and Different Use Models.

5.1 Methods and Properties

Methods Description Collapse Collapse a specified row or all rows. Expand Expand a specified row or all rows IsExpanded Returns true if a specified row is expanded otherwise false. NavigateBack Navigates back to the previously displayed table in the grid. NavigateTo Navigate to a table in the grid. SetDataBinding Binds a dataset to the DataSource and selects a table. Select This method selects row and highlights it. It is not necessarily the same as the current row. UnSelect This method unselects a row and turns of highlighting. It does not change the Current row.

Properties Description AllowSorting Set to True allows column sorting using the column headers. AllowNavigation Allows navigation within the data grid using for example the arrow or tab keys. AlternatingBackColor This sets a background color for alternating rows in the DataGrid making it easier to read across a row . DataSource This returns or sets the source of data for the DataGrid. It is either a DataSet or a DataTable. DataMember This sets the table to be displayed. When the DataSource is a DataSet the DataGrid display is in a hierarchical mode, setting this to one of the Tables in the DataSet automatically forces it to be displayed. CurrentCell Gets or Sets the currently active cell including the currentRowIndex currentRowIndex Gets or Sets the current row5.2 Assigning Data Sources

The Datasource for a DataGrid IS Either A Table OR A Dataset. For Example, a Previous Is Assigned to the DataGrid As Using The DataGrid's Datasource Member Follows:

Dg.DataSource = DT; // DataSource Contains Only A

// DataTable Object

A DataSet Table's Collection Can Be Assigned Using The DataGrid's DataSource Member As Follows ::

DataSet DS = New DataSet ();

DS.Tables.Add (DT1);

DS.TABLES.ADD (DT2);

...

DS.Tables.Add (DTN);

DG.DataSource = DS; // DataSource Contains a DataSet Object

BY Default The First Table in The Collection Is Displayed In The Collection, But a Particular Table Can Be Selected Using The DataGrid's DataMber Property As Follows:

Dg.DataMember = DT2.TABLENAME;

OR Equivalenti:

Dg.DataMember = ds.tables [1] .tablename; // Zero-based index

Or a DataSet Can Be Assigned and a Table Selected At the Same Time Using The setDatabase: Dg.SetDataBinding (DS, DT2.TABLENAME);

Note: The Only Restriction For DataSets Is Tables Must Have A Primary Key, IF NOT The Time of Assigning The Dataset To The DataSource.

5.3 Formatting

5.3.1 DataGridtablesTyle - WinForms

A DataTable is used to hold a collection of Column definitions and a collection of rows containing data for each column. A DataSet contains a collection of Tables and a DataGrid provides the interactive UI for the presentation of a table from a DataTable or from one contained in a dataset.

The rendering of each table being managed by the DataGrid is carried out through the collections of individual table styles (DataGridTableStyle) where each table style contains a collection of column styles. Refer to Figure 1 for a pictorial view of these relationships.

Microsoft's .NET IDE provides DataGridTextBoxColumn or DataGridBoolColumn objects that are as there name implies a TextBox and Boolean or CheckBox column respectively. The TextBox column is the default column type used when declaring a DataGrid.

Unique rendering for each column is provided through the column style properties and methods. In addition it is possible to modify the .NET provided column styles or define new column styles such as ComboBoxes and ImageControls that are inherited from the base classes.

Note: DataGridTableStyle Is Not Available for WebForms Instead ONE MUSE ITEMSTYLES - See Webform Example.

In The Following Example Assume The Following:

A DataTable DT IS defined

A DataSet ds is defined and contains dt at index equal 0 in its Tables collection A DataGrid dg is defined with DataSource containing dsInitially the DataGrid dg does not have any TableStyles contained in the TableStyles collection, which can be seen through the Count property value:

Dg.TablesTyles.count;

Also, The Dg.Controls Collection Only Contains Vertical and Horizontal ScrollBar Controls.

// first, a DataGridtableStyle Object is Declared

// That Will Hold A Collection of

// GridColumnStyles.

System.windows.Forms.DataGridtableStyle Dgstyle =

New DataGridtableStyle ();

// in this Example The .NET DataGridTextBoxColumn Class Is Used.

DataGridTextBoxColumn TextColumn;

// loop through each column in Table Dt to Get a datacolumn

// Object That Will BE Used

// TO Define Properties for ITS TextBoxColumn Style.

Foreach (Datacolumn DC in DT.columns)

{

TextColumn = New DataGridTextBoxColumn ();

// the mappingname must correspond to the table color

// in Order to Establish The Relationship Between THEM

TextColumn.mappingName = dc.columnname;

// The Headertext Value Is Displayed in Header for the Column, Here

// The caption value is used.

TextColumn.Headertext = dc.caption;

// Specify Some Other Property Values

TextColumn.width = 200;

TextColumn.Alignment = system.windows.forms.horizontalalignment.LORMS.HORIZONTALALIGNMENT.EFT;

TextColumn.readonly = true;

// add this column Object with its specifications to the

// GridColumnStyles Collection

DGStyle.GridColumnStyles.Add (TextColumn);

}

// the name of the datagridtablestyleme must match there below the Table

// Since the DataGrid Can Contain Multiple Tables,

// similar the tablestyles collection

// CAN Contain Multiple DataGridtables, One for Each Table.dgStyle.MappingName = DS.TABLES [0] .tablename;

Dgstyle.alternatingbackbackcolor = color.gainsboro;

DGStyle.Allowsorting = FALSE;

Dgstyle.readOnly = true;

// the clear () Method is Called to Ensure That

// The prepovious style is removed.

Dg.TablesTyles.clear ();

// add the new datagridtablestyle collection to

// the TableStyles Collection

Dg.TablesTYLES.ADD (DGStyle);

5.3.2 Change Only One Table's DataGridtableStyles

The Following Shows How To Change Only One Table's DataGridtableStyles. Assume The Table's Style Is Conta $ TableStyles Collection At Index Equal 0

// Clear Only a Single Table of Its GridColumnStyles

DGConversionTable.TablesTyles [0] .gridcolumnstyles.cle ();

DataGridTextBoxColumn TextColumn;

// loop through compan collection in Table Dt to Get A

// Datacolumn Object That Will Be Used

// TO Define Properties for ITS TextBoxColumn Style.

Foreach (Datacolumn DC in DT.columns)

{

TextColumn = New DataGridTextBoxColumn ();

// the mappingname must correspond to the table color

// in Order to Establish The Relationship Between THEM

TextColumn.mappingName = dc.columnname;

// The Headertext Value Is Displayed in Header for the Column, Here

// The caption value is used.

TextColumn.Headertext = dc.caption;

// Specify Some Other Property Values

TextColumn.width = 200;

TextColumn.Alignment = system.windows.forms.horizontalalignment.LORMS.HORIZONTALALIGNMENT.EFT;

TextColumn.readonly = true;

// Add this column object with its specifications to

// the gridColumnStyles Collection

// for tablestyles [0]

DGCONVERSIONTABLE.TABLESTYLES [0] .GridColumnStyles.Add (TextColumn);

}

5.3.3 Change a single column in a Table's DataGridTableStyleOne or more columns in an existing Table's DataGridTableStyles collection can be changed using code to similar to the following. In this example, the first method uses the HeaderText to find the column that is to be changed in a table that is named "Demo". Once the desired object is obtained, the current HeaderText value for the TextBoxColumn "old header text" is changed to "new header text". Also, the Width of the column is changed to 150. In The Second Example The Column MappingName Must Be Used Instead of The Headertext If.

5.3.3.1 Method 1 - for-loop through collection

In this Example

GridColumnStylescollection gcscoll =

DGConversionTable.TablesTyles ["demo"]. GridColumnStyles

For (int i = 0; i

{

IF (gcscoll [i] .gettype () == TypeOf (DataGridTextBoxColumn))

{

DataGridTextBoxColumn TextColumn = (DataGridTextBoxColumn) gcscoll [i];

IF (TextColumn.Headertext == "Old Header Text")

{

TextColumn.width = 150;

TextColumn.Headertext = "New Header Text";

Break;

}

}

}

5.3.3.2 Method 2 - Direct Access Using Column String Name

THIS Method Can Be Used If You Only Want To Change A Specific Column. Be Sure To Use The Column MappingName and Not ITS CAPTION OR Headertext If They Are Different.

GridColumnStylescollection gcscoll =

DGConversionTable.TablesTyles ["demo"]. GridColumnStyles

IF (GCSCOLL.CONTAINS ("mappingname"))

IF (gcscoll ["mappingname"] .gettype () == TypeOf (DataGridTextBoxColumn))

{

DataGridTextBoxColumn TextColumn =

(DataGridTextBoxColumn) gcscoll ["mappingname"];

TextColumn.width = 150;

TextColumn.Headertext = "New Header Text";

5.3.4 CREATE A DATAGRIDTABLESTYLE for TABLES BASED UPON ITS DATA

Each Table within a DataSet can have its own presentation and property style The formatDG method below provides an example of how to programmatically define a style for each table based upon the data type for each column It enforces these business rules..:

Width of a column is greater than whichever is larger - the width of the ColumnName text string or the maximum of the string length of the content of each cell in that column The maximum width is set to the width of 100 characters The letter '.. W 'IS Added to Each String for Padding Since It Is Usually The Widest Character in The Alphabet.

Columns of DataType System.String or System.Guid have Column alignment = HorizontalAlignment.Left and Readonly = false Columns of DataType of System.DateTime or typeof (int) have Column Alignment = HorizontalAlignment.Center and Readonly = false Columns of DateType System.Double , System.Float or System.Decimal have Column Alignment = HorizontalAlignment.Rignt and Readonly = false and a format of "0.00" The NullText property is set to string.empty. That is whenever a field has a null value then no text is displayed . This is only true for text columns and not for Boolean columns. Style column MappingName is the column's ColumnName that matches the name of the field in the corresponding database table while its HeaderText is set to the more readable string contained in the column's Caption property. The name of the datagridtablestyle is the same name as for the table. That IS, Both The DataSet Table and DataGridtable Collection Are IN Sync Through The Use of the Table Name Thathen the datagrid displays the table it will use the the corresponding tablestyle.public void formatdg (DataGrid DG)

{

// Assume DataGrid DataSource IS A Dataset That

// contains at Least One Table.

IF (DG.DataSource.gettype () == TypeOf (Dataset))

{

DataSet DS = (Dataset) DG.DataSource;

IF (ds! = null)

{

IF (dg.tablestyles.count> 0)

Dg.TablesTyles.clear ();

Float prevsumwidths = 0.0f;

INT maxheight = 0;

INT CALCH = 0;

Foreach (DataTable DT in ds.tables)

{

// DataTable DT = ds.tables [tablename];

DataGridTableStyle DGStyle = New DataGridTableLeStyle ();

DGStyle.mappingname = dt.tablename;

DGStyle.Allowsorting = FALSE;

DgStyle.alternatingbackbackColor = Color.gainsboro; DataGridTextBoxColumn TextColumn;

Int nbrcolumns = dt.columns.count;

DataRow DR;

ArrayList CWIDTHS = New ArrayList ();

Graphics g = dg.creategraphics ();

Font f = dg.font;

SIZEF SF;

// Get Widths for Each Column HEADER

Foreach (Datacolumn C in Dt.columns)

{

// "w" is buy as padding

sf = g.measureString ("w" c.caption, f);

CWIDTHS.ADD (sf.width);

}

// Loop Through Each Row Comparing Against Initial Column

// width and then against each new maximum width based upon

// Data Contained in Each Row for That Column.

String straTemp;

For (int i = 0; i

{

DR = dt.rows [i];

For (int J = 0; j

{

IF (! convert.isdbnull (DR [j]))

{

STRTEMP = DR [J] .tostring ();

// Careful strings Can Get

// Very Long, Limit It To 100 Characters

IF (DR [J] .gettype () ==

TypeOf (System.String) && Strtemp.Length> 100)

sf = g.measureString ("w"

Strtemp.substring (0,100), f);

Else

sf = g.measureString ("w" strtemp, f);

IF (sf.width> (float) CWIDTHS [J])

CWIDTHS [J] = sf.width;

}

}

}

// set Each Column with ITS Determined Width

// SET Alignment for Each Column

// set Format for Decimal Numbers

FLOAT SUMWIDTHS = 0.0f;

Foreach (Datacolumn C in Dt.columns)

{

IF (C.DataType == TypeOf (bool))

{

DataGridBoolColumn Boolcolumn =

New DataGridBoolcolumn ();

Boolcolumn.mappingname = c.columnname;

Boolcolumn.Headertext = "" c.caption;

Boolcolumn.width = 50;

Boolcolumn.readonly = false;

Boolcolumn.Alignment = horizontalalignment.center;

DGStyle.gridColumnStyles.Add (BoolColumn); Sumwidths = BoolColumn.width;

}

Else

{

TextColumn = New DataGridTextBoxColumn ();

TextColumn.mappingName = c.columnname;

TextColumn.Headertext = "" c.caption;

TEXTCOLUMN.Readonly = false;

TextColumn.nullText = String.empty;

IF (C.DataType == TypeOf (System.guid) ||

C.DataType == typeof (system.string))

{

TextColumn.Alignment = horizontalalignment.Left;

}

Else

IF (C.DataType == TypeOf (System.DateTime))

TextColumn.Alignment = horizontalalignment.center;

Else

IF (C.DataType == TypeOf (int))

{

TextColumn.Alignment = horizontalalignment.center;

}

Else

{

TextColumn.Alignment = horizontalalignment.right;

IF (C.DataType == TypeOf (System.double)

|| C.Datatype == TypeOf (System.Decimal)

|| c.Datatype == TypeOf (float))

TextColumn.Format = "0.00";

}

TEXTCOLUMN.WIDTH = (int) cwidths [c.ordinal];

DGStyle.GridColumnStyles.Add (TextColumn);

Sumwidths = TextColumn.width;

Maxheight

Maxheight = textColumn.TextBox.Height;

}

}

Dg.TablesTYLES.ADD (DGStyle);

// adjust width of datagrid to match calculate widths

// Select Maximum Width of All Tables in the DataSet

// Adjust Width to Fit Inside The Parent Container's Width

PrevsumWidths

{

Prevsumwidths = sumwidths;

PrevSumWidths = DG.Rowheaderwidth;

IF (Dg.visibleRowcount

PrevSumWidths = 16; // Add Width of Scrollbar

// Check to see if it is greater tour of the width of its parent

// E.g. A Panel or TabPage Control.

IF (prevsumwidths> (float) dg.parent.width)

// allow room for the scroll bar and provide a little padding.prevsumwidths = (float) DG.Parent.width - 16 - 5;

}

// Adjust Height Of DataGrid Based Upon Row Visiblity

IF (Dg.visibleRowcount> = DT.ROWS.CONT)

{

Calch = (Dg.visibleRowcount) * Maxheight 2 * DG.PREFERREDROWHEIGHT 16;

}

Else

{

Calch = (dt.rows.count) * maxheight 2 * DG.PREFERREDROWHEIGHT 16;

// Make a Correction Since All Rows Will Now Be Visible

Calch

PrevSumWidths - = 16;

}

IF (Calch> = DG.Parent.Height)

{

Calch = dg.parent.Height - Dg.top - 25; // Some Arbitrary Value

}

}

Dg.size = new size (int) PrevsumWidths, Calch);

}

}

5.3.5 Defining DataGridtables THROUGH VISUAL STUDIO .NET IDE

In the WinForm UI editor where a DataGrid control is placed onto the Form, the DataGridTableStyle's collection property can be selected that will bring up the DataGridTableStyle Collection Editor dialog box shown in Figure 3. Clicking on the Add button will create a new DataGridStyle that can be named. Shown in member's section of the dialog box are two styles names DGStyleElements and DGStyleIsotopes where the property values ​​for the former are shown. Note that DGStyleElements has a MappingName of Elements and whenever the DataGrid MappingName is also Elements then this style will be used to Render the datable with the same name.

Clicking on the GridColumnStyles collection property (indicated by Red Arrow) launches the DataGridColumnStyle Collection Editor dialog shown in Figure 4. In the member's section is a list of column styles, one for each column that is in the Elements Table. Shown in the dialog are the property values ​​for the TextBoxColumn style that is linked to the Atomic Number column in the Elements Table through the MappingName property.The two dialog boxes in Figures 3 and 4 clearly show the DataGrid style collections of collections model that the DataGrid uses when rendering tables.

Figure 3 DataGridtableStyle Collection Editor Dialog Box

Figure 4 DataGridColumnStyle Collection Editor Dialog Box

5.4 Navigation

5.4.1 CurrencyManager

The CurrencyManager is especially useful when the DataSet contains linked tables and there is a need to make sure records are being added correctly or in navigating between them. The CurrencyManager's Position property contains the zero-based index row number of the currently selected row of the table That it is bound to.

In a linked system such as the Element -> Isotope table relationship and the DataGrid DataMember property is set to the Isotope table, then the DataGrid CurrentRowIndex reflects the currently selected row in the Isotope table and the only way to know the row index in the Element Table to which it is linked can only be determined by using the currencymanger for the elements table.

The CurrencyManager can also be used to move to different rows in its bound table by using the Count property in conjunction with changing the value of the Position property; thus MoveNext, MovePrev, MoveFirst and MoveLast navigation methods can be created Also when the position is. Changed the currencymanager's currentchanged and positionchanged Events Can Be Monitored.for Example a Currencymanger Object with Event Handling Can Be Declared As Follows:

PRIVATE CURRENCYMANGER CMELEMENTS;

Cmelements = (currencessManager) this.bindingcontext [

DG.DataSource, "Elements"];

cmelements.currentchanged = new system.eventhandler

this.cmelements_currentchanged;

cmelements.positionchanged = new system.eventhandler

this.cmelements_positionchanged;

5.4.2 Currentcell

The DataGridCell class constructor can be used to change the currently selected cell and row in the table currently active as specified by dg.DataMember. It also has two members that can be used to independently get or set the current table column and row numbers. For EXAMPLE:

Dg.currentcell = New DataGridcell (Row, Column);

Row = dg.currentcell.rownumber;

Column = Dg.currentcell.columnnnnumber;

5.4.3 SELECTING ROWS

When Coordinating a DataGrid with Other Types of Ui Components The CurrentrowIndex, Select and Unselect Methods Need To Be Called.

Method Action dg.CurrentRowIndex = newRow; Sets or Gets the new current row and moves the cursor indicator to that row Refer to figure 3. dg.Select (newRow);.. Select () highlights the NewRow Refer to figure 3. dg. Unselect (previouSrow); unselect () un-highlights the previouSrow

5.4.4 Expand and Collapse Linked Tables

Figures 5 To 7 Show Tables in Different States After Calling The Collapse and Expand Methods.figure 5 Dg.collapse (-1); // Collapses All Rows

Figure 6 DG.Expand (-1); // Expands All Rows

Figure 7 DG.Expand (1); // Expands Only Row 2 (Zero Based Index)

Figure 8 illustrates the result of using the DataGrid NavigateTo (arg1, arg1) method where arg1 is an integer row index in the primary table and arg2 is a string specifying the name of the table to Navigate to. In this example, Mercury is at row INDEX = 79 in the elements Table and isotopes are Contained in the link Table "Isotopes" through the atomic number primary key-foreign key rellationship.

Figure 8 DG.NavigateTo (79, "isotopes");

5.5 Copy DataGrid to The Clipboard

The following sections contain Copy to Clipboard routines that access all tables or a specified table from a DataGrid and then they call a routine (TableToString) that formats table data into a string, which is copied to the Clipboard. Once the clipboard contains this string it Can Be Pasted Into Excel Or Into Any Other Application That Accepts Text Data. For Example, In Excel or Winword The String Data Will Be Pass Back Into Tables.

Each of the Methods Checks The DataGrid Data Source Member To Determine WHETHER IT IS A DATASET Containing a Collection of Table OR WHETHER IS SIMPLY A TABLE Object.

5.5.1 Copy Selected Table in DataGrid To Clipboard

Public Void CopyDGToClipboard (DataGrid DG, String TableName)

{

IF (DG.DataSource! = null)

{

DataTable DT = NULL;

IF (DG.DataSource.gettype () == TypeOf (Dataset))

{

DataSet DS = (Dataset) DG.DataSource;

// NEED TO Use Tablename When Dataset Contains More Than

// one table

IF (ds.tables.contains)

Dt = ds.tables [TABLENAME];

Else

IF (DG.DataSource.gettype () == TypeOf (DataTable))

{

DT = (DATATABLE) DG.DataSource;

IF (dt.tablename! = TableName)

{

Dt.clear ();

DT = NULL;

}

}

IF (dt! = null)

Clipboard.SetDataObject (TabletString (DT), true);

}

}

5.5.2 Copy All Tables in DataGrid To Clipboard

Public Void CopyDGTOCLIPBOARD (DataGrid DG)

{

IF (DG.DataSource! = null)

{

IF (DG.DataSource.gettype () == TypeOf (Dataset))

{

DataSet DS = (Dataset) DG.DataSource;

IF (ds.tables.count> 0)

{

String stratables = string.empty;

Foreach (DataTable DT in ds.tables)

{

Strtables = Tabletostring (DT);

STRTABLES = "/ r / N / r / N";

}

IF (Strtables! = String.empty)

Clipboard.SetDataObject (Strtables, True);

}

}

Else

IF (DG.DataSource.gettype () == TypeOf (DataTable))

{

DataTable DT = (DATATABLE) DG.DataSource;

IF (dt! = null)

Clipboard.SetDataObject (Tabletostring (DT),

True);

}

}

}

5.5.3 Format Table Data Into A String

This method returns a string containing the data in a DataTable object. The first line contains the name of the table, the second line contains the name of each column separated by a tab character and the remaining lines, one for each row in the table, Contains The Corresponding Column Data Separated By a Tab Character.

Private string Tabletostring (DataTable DT)

{

String strdata = dt.tablename "/ r / n";

String sep = string.empty;

IF (dt.rows.count> 0)

{

Foreach (Datacolumn C in Dt.columns)

{

IF (C.DataType! = TypeOf (System.guid) &&

C.DataType! = typeof (system.byte [])))

{

STRDATA = SEP C.COLUMNNAME;

SEP = "/ t";

}

}

STRDATA = "/ r / n"; Foreach (DataRow R in Dt.ROWS)

{

Sep = string.empty;

Foreach (Datacolumn C in Dt.columns)

{

IF (C.DataType! = TypeOf (System.guid) &&

C.DataType! = typeof (system.byte [])))

{

IF (! convert.isdbnull (r [c.columnname]))

STRDATA = SEP

R [c.columnname] .toString ();

Else

STRDATA = SEP ""

SEP = "/ t";

}

}

STRDATA = "/ r / n";

}

}

Else

STRDATA = "/ r / n ---> Table WAS Empty!"

Return strdata;

}

5.6 Exporting to a Tabbed Delimited TEXT FILE

The following two methods tabTextFile and SaveDataGridData along with the TableToString method defined in an another section can be used to save all data contained in the DataGrid to a tab delimited text file specified through a SaveAs Dialog box.

Public void TabTextFile (DataGrid DG)

{

OpenFiledialog OpenFileDialog1 = New OpenFiledialog ();

OpenFileDialog1.initialDirectory = "c: //";

OpenFiledialog1.Filter =

"Text Files (* .txt) | * .txt | all files | *. *";

OpenFileDialog1.RestRedirectory = True;

OpenFileDialog1.title = "export datagrid to text file";

System.windows.Forms.DialogResult res = OpenFiledialog1.showdialog ();

IF (res == DialogResult.ok)

{

DataSet DS = New DataSet ();

DataTable dtsource = NULL;

DataTable DT = New DataTable ();

DataRow DR;

IF (DG.DataSource! = null)

{

IF (DG.DataSource.gettype () == TypeOf (Dataset))

{

Dataset dssource = (dataset) DG.DataSource;

// Assume Dataset Contains Desired Table At Index 0

IF (dssource.tables.count> 0)

{

String stratables = string.empty;

Foreach (DataTable DT in dssource.tables)

{

Strtables = TableTString (DT); Strtables = "/ R / N / R / N";

}

IF (Strtables! = String.empty)

SaveDataGriddata (Strtables, OpenFileDialog1.FileName);

}

}

Else

{

IF (DG.DataSource.gettype () == TypeOf (DataTable))

DTSource = (DATATABLE) DG.DataSource;

IF (DTSource! = NULL)

SaveDataGriddata (TableToString (DTSource),

OpenFileDialog1.FileName);

}

}

}

}

Private Void SavedataGriddata (String Strfilename)

{

FileStream Fs;

Textwriter TW = NULL;

Try

{

File.exists (StrfileName))

{

FS = New filestream (StrfileName, FileMode.Open);

}

Else

{

Fs = new filestream (strfilename, filemode.create);

}

TW = New streamwriter (fs);

Tw.write (strdata);

}

Finally

{

IF (tw! = null)

{

Tw.flush ();

Tw.close ();

Messagebox.show ("DataGrid Data Has Been Saved to:" StrfileName

, "Save DataGrid Data As", System.Windows.Forms.MessageboxButtons.ok

System.windows.Forms.MessageBoxicon.information;

}

}

}

5.7 Cloning Table Contained in A DataGrid

This example shows how to clone a table in a DataGrid and then fill the cloned table with the content from the original table and return it in a new DataSet. Note that it checks to determine whether the DataSource is a DataSet or a Table.

Private Dataset CloneDataTable (DataGrid DGTABLE)

{

DataSet DS = New DataSet ();

DataTable dtsource = NULL;

DataTable DT = New DataTable ();

DataRow DR;

IF (DGTable.DataSource! = NULL)

{

IF (DGTable.DataSource.gettype () == TypeOf (Dataset))

{

Dataset dssource = (dataset) DGTABLE.DASOURCE;

// Assume Dataset Contains Desired Table At Index 0

DTSource = dssource.tables [0];

}

Else

IF (DGTable.DataSource.gettype () == TypeOf (DataTable)) DTSource = (DataTable) DGTable.DataSource;

IF (DTSource! = NULL)

{

DT = dtsource.clone ();

// DGConversionTable.captionText;

DT.TABLENAME = DTSource.tablename;

Dt.BeginLoadData ();

Foreach (DataRow Drsource In DTSource.Rows)

{

DR = DT.NEWROW ();

Foreach (Datacolumn DC in dtsource.columns)

{

DR [dc.columnname] = drsource [dc.columnname];

}

DT.ROWS.ADD (DR);

}

Dt.acceptchanges ();

Dt.endloadData ();

DS.TABLES.ADD (DT);

}

}

Return DS;

}

5.8 Comparison of WinForms & WebForms

..............................

5.8.1 WinForms

In Figures 9 and 10, it can be seen that the C-Terminal table contains text, decimal numbers and integers that have been formatted using a procedure similar to formatDG (DataGrid dg) that us DataGridTableStyles This DataGrid was formatted as follows.:

Integers are centered within the column

Text strings are left justified. In the Formula column, which is generated from the values ​​in the element decomposition columns, the electronic formula string has a space between each element instead of using numeric subscripts Decimal numbers have 4 decimal places and are right justified. The ID column is the primary key for the table. Note: Dc.caption is used as column headers in the datagrid, in this case dc.caption is equal to dc.columnname

Figure 9 Winform DataGrid Displaying C-Terminal Groups

In Figure 10, row 3, Hydrazine in the Name column is being edited. That is, editing is performed directly within each cell by simply moving the cursor to the cell and clicking on the left mouse button to set the focus. The dark blue arrow on the left margin of the table moves to the row being edited. If there are more rows than can be displayed in the DataGrid view then a scroll bar is used to bring other rows into view.Figure 10 WinForm DataGrid editing directly in a cell

To add more rows, the procedure is to enter new values ​​into each cell in the row marked with an asterisk. The table class manages all new cell and row entries. One of the available methods will return a value indicating that changes to the table has Occurred and tell Determine the Types of change Only the Create a Table Containing Only The Changes. Events Handlers Can Also Be Implement To Respond As Changes Are Being Made.

5.8.2 WebForms

Figures 11 - 13 illustrate the same table as in the Web Form, but there are differences First and foremost is that the DataGrid is really an HTML Table This can be readily seen by looking at the Formula column in Figures 11 and 12. The.. Numeric Subscript Values ​​Are Formatted Using The HTML ... Tags with Numbers Being Obtained from The Element Decompositions Columns {C, H, N, O, S, P, CL, BR, F, I}. That IS , all cell entries can modified using all style elements available in HTML. Below Figure 11 is listed the HTML code generated by Microsoft's Visual Studio .NET IDE for the DataGrid. It contains user defined and default property values. Notice in the HTML code that the blue background with white letters is defined for the header as well as the additional Edit and Delete columns that are used when modifying row values. Also, since an HTML table does not have scroll bars, a paging mechanism (Prev, Next) can be used With the number of lines per page defined with the page Ribute.figure 11 Webform DataGrid Being Displayed As an HTML Table

HTML Code That Was Generated for the DataGrid by Visual Studio .NET

Font-size = "small" font-names = "arial" horizontalalign = "left"

Width = "656px" allowpaging = "true" Pagesize = "10" Cellpadding = "3">

Headertext = "edit" canceltext = "ca Zan" edittext = "edit">

CommandName = "delete">

Horizontalalign = "center" forcolor = "White" backcolor = "navy">

5.8.2.1 Edit A Row

When a rows Edit linkbutton is clicked each cell in the row is converted to a TextBox control with its TextBox.text property initialized to the value obtained in the table cell. This is illustrated in row 3 of Figure 12 where each TextBox Control has been formatted as presented in the section of the dg_PreRender (object sender, System.EventArgs e, string strTableName) procedure code that follows Figure 13 where the EditItemIndex member is greater than -1. Note that the ID and Formula columns TextBox control is readonly, DarkGray colored Text and the border width is zero.

.................. ..

Private void DGCTERMINALGROUPS_EDITCOMMAND (Object Source,

System.Web.ui.WebControls.DataGridCommandEventArgs E)

{

DgnterminalGroups.edititeMindex = E.Item.itemindex; DGnterminalGroups.DATABIND ();

}

5.8.2.2 Cancel Editing A Row

..................

Private void DGNTERMINALGROUPS_CANCELCOMMAND (Object Source,

System.Web.ui.WebControls.DataGridCommandEventArgs E)

{

DgnterminalGroups.editItemIndex = -1;

DGnterminalGroups.DATABIND ();

}

Figure 12 Editing C-Terminal Group Row Id Equal 3

5.8.2.3 Entering a new row

In the WinForm DataGrid a new row can be entered in the line designated with an asterisk, but this mechanism does not exist in WinForms. This implementation has created a special last row with a Key Phrase "[New CTerm-Group]" that lets the user know that this line is similar to the WinForm line with an asterisk and Edit will have the same behavior as the other lines. This line empty line was added to the DataTable after the object was filled from the database query and the update handler will remove .

Figure 13 add a new c-terminal group rot

5.8.2.4 Updating A Row

This UpdateCommand Event Handler Does The Following:

DELETE The Last Row ([New CTERM-group]) from the dataset table if it is not the one beding

If it was deleted, then the AcceptChanges () is called so there will be no attempt to delete from the table in the database since it really does not exist there. Next get the value from each TextBox control and update the corresponding cell in the DataSet . Table Note the TextBox control has index equal zero in the Cells control collection Update the CTerminal Database table with the row changes or new row addition Reset the EditItemIndex to -1, Set the DataSource to the modified DataSet and Call DataBind () Note.: If The Update Does Not Appear To Work Even Though of The Event Handlers Are Being Called, Check To See if you are using the ispostback method in the point_onload () Event handler. for example

IF (! page.ispostback)

DGCTERMINALGROUPS.DATABIND ();

Private void DGCTERMINALGROUPS_UPDATECOMMAND (Object Source,

System.Web.ui.WebControls.DataGridCommandEventArgs E)

{

DataRow DR;

DataSet DS;

DS = (Dataset) DGCTERMINALGROUPS.DATASOURCE;

DataTable DT = DS.TABLES ["CTerminal"];

// this code segment simply deletes the blank row at The blank rot

// end of the table if it is not the row being modified / updated.

IF (E.Item.DataSetIndex

{

Dt.Rows [Dt.Rows.count-1] .delete ();

Dt.acceptchanges ();

}

DR = Dt.Rows [E.Item.datasetIndex];

For (int i = 0; i

{

// The textbox is the 0th Element of the controls collection.

// The Edit, Delete Column Are AT Cells i = 0

// and i = 1 respectively, Skip those

TextBox TBOX = (TextBox) E.Item.cells [i 2] .controls [0];

IF (! tbox.readonly) // Skip Readonly Cells;

// set in prender () Event handler.

DR [dt.columns [i] .caption] = TBOX.TEXT;

}

IF (ds.haschanges ())

{

Dataset DSChanges = ds.getchanges (); // Call An Update Database Function (Code for Method Not Shown)

// Merge the changes

// with the dataset contained by the datagrid

UpdateterminalTable (DSChanges, "CTerminal")! = Null

DS.MERGE (DSChanges);

}

// Switch out of edit mode.

DGCTERMINALGROUPS.EDITITEMINDEX = -1;

DGCTERMINALGROUPS.DATASOURCE = DS;

DGCTERMINALGROUPS.DATABIND ();

}

5.8.2.5 Setting Cell STYLE VALUES

When individual cells in the DataGrid Table need to be formatted beyond global grid and column settings, a user defined DataGrid PreRender event handler can be defined. The following code provides an example of a handler that can be used to set individual cell style values. The Result of formatting based Upon data type contained in the datagrid can be seen by committing fas

setting horizontal alignment properties for all cells setting the [New Term Group] row to be in Italic and to have the ForeColor and BackColor properties set to Color.DarkGray and Color.White respectively setting the ForeColor and BackColor to Color.DarkBlue and Color.LightGray Respectively for Decimal Numbers.

........... ..

This example further illustrates formatting using HTML CssStyles and control properties in the section of the code where it specifically handles the row currently being edited which is contained in the EditItemIndex member.

Note in the dg_prender code, the for-loopfor (int J = 0; j

System.EventArgs E, STRING STRTABLENAME

{

DataGrid DG = (DATAGRID) Sender;

DataTable DT = NULL;

IF (DG.DataSource.gettype () == TypeOf (Dataset))

{

DataSet DS = (Dataset) DG.DataSource;

DT = DS.TABLES [STRTABLENAME];

}

Else

IF (DG.DataSource.gettype () == TypeOf (DataTable))

DT = (DATATABLE) DG.DataSource;

IF (dt! = null)

{

For (int J = 0; j

{

IF (j == (Dg.Items.count-1) &&

(String) DT.ROWS [J DG.PageSize * Dg.currentPageIndex] [

"Name"]). Indexof ("[new")> -1)

BnewGrouprow = true;

Else

BnewGrouprow = false;

For (int i = 0; i <(dt.columns.count); i )

{

// accentuate [New Term Group] Row with font

// and color modifications

IF (BnewGrouprow && Dg.editItemIndex == -1)

{

Dg.Items [J] .cells [i 2]. manufacture = color.darkgray;

Dg.Items [J] .cells [i 2] .BackColor = Color.White;

Fontinfo Fi = DG.Items [J] .cells [i 2] .font;

Fi.italic = true;

}

IF (dt.columns [i] .datatype == TypeOf (System.guid) ||

Dt.columns [i] .DataType == typeof (system.string))

{

Dg.Items [J] .cells [i 2] .hizontalalign =

Horizontalalign.Left;

Dg.Items [J] .Cells [i 2] .wrap = true;

Else

IF (dt.columns [i] .DataType == typeof (system.datetime))

Dg.Items [J] .cells [i 2] .hizontalalign =

Horizontalalign.center;

Else

IF (dt.columns [i] .DataType == TypeOf (int))

{

Dg.Items [J] .cells [i 2] .hizontalalign =

Horizontalalign.center;

}

Else

{

IF (dt.columns [i] .DataType == typeof (system.double)

|| dt.columns [i] .DataType == TypeOf (System.Decimal)

|| dt.columns [i] .datatype == typeof (float))

{

Dg.Items [J] .cells [i 2] .hizontalalign =

Horizontalalighign.right;

// set the text color to DarkBlue and Background Color

//Lightgray

Dg.Items [J] .cells [i 2]. manufacture = color.darkBlue;

Dg.Items [J] .Cells [i 2] .BackColor = Color.lightGray;

}

}

}

}

// Check to see if a row is being edited, IF IS

// THE EditIndex Member Is Non-Negative

// Each Cell in The Row now Has An Edit Control,

// this code gets the EditControl Object for

// The Cell and the sets its cell specific attributes.

// this Example Uses The Caption Text As

// a filter to select the cell type and then sets its

// Individual Style Properties. Two Cells

// id and forumla area readonly and their text color is

// set to darkgray. The Example Also Uses

// CSSStyle to Set Global Style Attributes for Each Cell.

IF (Dg.editItemIndex> -1)

{

String strcaption;

For (int i = 2; i <= (dt.column.count 1); i )

{

Textbox TBOX =

(TextBox) DG.Items [Dg.edititeMindex] .Cells [i] .controls [0];

TBox.backcolor = color.white;

TBOX.FORECOLOR = color.darkBlue;

System.Web.ui.attributeCollection

TBOXATTRIBUTES = TBOX.ATRIBUTES;

TBoxAttributes.cssstyle.add ("Font-Weight", "Bold"); TBOXATTRIBUTES.CSSSTYLE.ADD ("Text-Align", "Center");

STRCAPTION = DT.COLUMNS [I-2] .caption.trim ();

IF (strcaption == "id")

{

TBox.readOnly = true;

TBox.Forecolor = color.darkgray;

TBOX.BORDERWIDTH = 0;

TBOX.WIDTH = 30;

}

Else

IF

Strcaption == "c" || strcaption == "h" ||

Strcaption == "n" || strcaption == "o" ||

Strcaption == "s" || strcaption == "p" ||

Strcaption == "br" || strcaption == "cl" ||

Strcaption == "f" || strcaption == "i")

{

TBOX.WIDTH = 30;

}

Else

IF (strcaption == "formula")

{

TBOX.WIDTH = 150;

TBox.readOnly = true;

TBox.Forecolor = color.darkgray;

TBOX.BORDERWIDTH = 0;

TBOX.TEXT = String.empty;

}

Else

IF (strcaption == "avgmass" || strcaption == "monomass")

{

TBOX.WIDTH = 75;

}

Else

IF (strcaption == "name")

{

TBOX.WIDTH = 150;

}

Else

TBOX.WIDTH = 75;

}

}

}

}

Figure 14 Formatting DataGrid Using Prerender Method

6 References

1. Microsoft Visual Studio .NET IDE help system Microsoft Developer Network online help system Programming Microsoft Windows with C #, Charles Petzold, Microsoft Press, 2002. ASP.NET Data Web Controls, Scott Mitchell, SAMS, 2003

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

New Post(0)