AutoColumnsizeGrid

xiaoxiao2021-03-06  37

Using system.componentmodel; using system.diagnostics; using system.drawing; using system.runtime.interopservices; using system.windows.form;

Namespace autocolumnize {

///

/// Windows Forms derived DataGrid that will keep the grid height /// to row-height increments so resizing vertically will snap between /// row-heights & never display a partial row. Rows will either be /// fully displayed or not shown. This grid will also resize column /// widths so that the grid will not display a horizontal scrollbar. /// This grid will take into account whether or not the vertical /// scrollbar is visible When it makes the column widths change. /// public class grid: DataGrid {

Private const Int minimum_column_width_default = 10;

Private static readonly object evented minimum = new object ();

Private int minimumcolumnwidth = minimum_column_width_default; private bool iner inensuretablestyleexists;

///

/// Initializes a new instance of the autogram. /// public grid () {

// we have to add an event handler for the OnNavigate event // because the DataGrid did not make its own OnNavigate routine // that raises the event virtual like most property event // raising routines ... // this.Navigate = New navigateEventHandler (ONNAVIGATE);

///

/// tells how many pixels the border of this grid will be /// private int BorderWidth {get {if (BorderStyle == BorderStyle.Fixed3D) {return SystemInformation.Border3DSize.Width; } Else if (borderstyle == borderstyle.fixedsingle) {return 2;} else {return 0;}}} /// /// Gets or sets the data member what the Grid Is Displaying data for. //// public new string DataMber {get {return base.datamember;} set {ENSURETABLESTYLEEXISTS (DataSource, value); base.DataMember = value;}}

///

/// gets or sets the data source that the grid is displaying data for /// public new object DataSource {get {return base.DataSource;.} Set {EnsureTableStyleExists (value, DataMember Base.DataSource = value;}}

///

/// width at which columns stop shrinking as the grid is resized. If /// the grid's width is not sufficient enough to display all columns /// with a width of MinimumColumnWidth, the grid will introduce a /// horizontal scrollbar /// [DefaultValue (MINIMUM_COLUMN_WIDTH_DEFAULT)] public int MinimumColumnWidth {get {return minimumColumnWidth;.} set {if (minimumColumnWidth = value!) {minimumColumnWidth = value; PerformLayout (this, "MinimumColumnWidth" ); Onminimumcolumnwidthchanged (evenetargs.empty);}}}

///

/// event handler for when the MinimumColumnWidth changes /// public event EventHandler MinimumColumnWidthChanged {add {Events.AddHandler (EventMinimumColumnWidthChanged, value);} remove {Events.RemoveHandler (EventMinimumColumnWidthChanged, value) }}

///

/////////// Protected Override Void Dispose (Disposing) {ix {This.navigate - = new navigate);} base.dispose (Disposing);

///

/// checks to see if there is an existing tableStyle for the /// given CurrencyManager, creating one if it does not exist yet. /// private void EnsureTableStyleExists (object dataSource, string DataMember) {

// Requesting The BindingContext Below Will Cause US To Renerter // This function, and we Only Want to do this overce. // if (inference) {return;}

INENSURETABLESTYLEXISTS = TRUE; TRE {IF ((DataSource! = NULL) && (BindingContext! = NULL) &&! (DataSource == Convert.dbnull) {

CurrencyManager ListManager = (currencessManager) BindingContext [DataSource, DataMember]; debug.assert (ListManager! = NULL, "BindingContext Didn't Give US A CURRENCYMANAGER?");

IF (ListManager! = null) {string listName = getListName (Datasource, ListManager);

// if we don't have a tablestyle for this list, the create one // and add it to out on i (! TableStyles.contains (listname) {

DataGridTableStyle tableStyle = new DataGridTableStyle (listManager); TableStyles.Add (tableStyle);}}}} finally {inEnsureTableStyleExists = false;}} ///

/// method that will use the current DataSource and DataMember to determine // / what tableStyle the grid is currently displaying. /// private DataGridTableStyle getcurrenttablestyle () {

DataGridTableStyle CurrentTableStyle = NULL;

IF (DataSource! = Null && BindingContext! = null) {string listname = getListName (catasource, (currenufactageManager) BindingContext [DataSource, DataMember]);

IF (TableStyles.Contains) {currenttablestyle = TableStyles [listname];}}

Return CurrentTableStyle;

///

/// Returns the width That Column can take up on this /// Grid with the given tableStyle /// private int getFullWidth (DataGridTablesTyle tableStyle) {

Return Width - 2 * Borderwidth - (VertscrollBar.visible? VertscrollBar.width: 0) - (TableStyle.Rowheadersvisible? TableStyle.Rowheaderwidth: 0);}

///

/// method that duplicates internal code in WinForms.CurrencyManager because /// almost nothing that DataBinding does is publicly exposed ... /// private string GetListName (object dataSource, CurrencyManager listManager) {

String name = null; ilist list = listManager.list;

// if it's a typed-list, the just returnid-list's name // if (list! = null && list is itypedlist) {name = ((iTYPEDLIST) ListManager.listName (null);} else { TYPE FINALTYPE = NULL; Object Templist = DataSource;

// otherwise we have to track down what the CurrencyManager // stores as its "finalType" - another internal to WinForms // concept that we can not access directly // if (tempList is Array) {finalType = dataSource.GetType. (); Templist = (array) Templist;}} {templist = ((ilistsource) Templist) .getlist ();

IF (Templist is ILIST) {if (FinalType == Null) {FinalType = Templist.gettype ();}}

IF (FinalType! = null) {name = FinalType.Name;}}

IF (name == null) {name = string.empty;}

Return name;}

///

/// protected override void OnbindingContextChanged (Eventargs E) {

// if we need to ensure // THAT WE HAVE A TABLETABLESTYLEEXISTS (DataSource, DataMe); Base.OnbindingContextChanged (e);}

///

/// Overridden to /// protected override void onlineout (layoutEventArgs level) {

// first, give the datagrid a chance to lay Things Out // SO We can Tell if a vertical scrollbar is present // base.OnLayout (level);

// Now That The DataGrid IS DONE, WE NEED TO Figure OUT IFTYLESTYLE = GetCurrentTableStyle = getCurrentTableStyle = GetCurrentTableStyle (); if (TableStyle! = null) {

Int fullwidth = getFullWidth; TableStyle;

IF (FullWidth> 0) {

Bool Vertscrollvisible; int sizablecolumncount;

// it's possible that we will begin with both a vertical & horizontal scrollbar // after the initial base.OnLayout call and that resizing the columns to make // the horizontal scrollbar disappear will also force the vertical scrollbar // to disappear too, and we would not want to leave the area where the // vertical scrollbar was as blank client area, so we set this up as a // loop in case we need to lay columns out twice. // do {vertScrollVisible = VertScrollBar.Visible SizableColumnCount = 0; Foreach (DataGridColumnStyle Column in TableStyle.GridColumnStyles) {

// checkbox columns should not change size so we simply // remove the size of that column from the overall width // we're splitting the columns up across // if (column is DataGridBoolColumn) {fullWidth - = column.Width;} Else {sizablecolumncount ;}}

IF (SizableColumnCount> 0) {

INT columnWidth = fullwidth / sizablecolumncount; int remain = fullwidth% sizablecolumncount; int index = 0; bool resize = false;

Foreach (DataGridColumnStyle Column in TableStyle.GridColumnStyles) {

IF (!n) {@ (colorboolcolumn))

Int width = (index

IF (column.width! = width) {colorn.width = width; resized = true;

INDEX ;}}

// if we changed any column widths, we need to give the DataGrid // a chance to lay out again so we can see if scrollbar visiblity // changed before returning // if (resized) {base.OnLayout (levent);} } fullwidth = getFullWidth;

} while (VertscrollVisible! = VERTSCROLLBAR.Visible);}}}

. ///

/// called when MinimumColumnWidth changes for this grid /// protected virtual void OnMinimumColumnWidthChanged (EventArgs e) {EventHandler eh = Events [EventMinimumColumnWidthChanged] as EventHandler; if (! Eh = null) {EH (this, e);}}

///

/// Called WHEN USER Navigates within the grid to a sub-Table /// Private void onnavigate (Object sender, navigate) {

// First, make Sure a TableStyle Exists for this new // DataSource / DataMember // ENSURETABLESTYLEEXISTS (DataSource, DataMember);

// Then SIMPLY FORCE A LAYOUT SO We can REARRANGE COLUMN WIDTHS / / ONLAYOUT (NULL, NULL);}

///

/// obscures WinForms DataGrid method so we can ensure that /// a TableStyle exists before calling the base class version. /// public new void SetDataBinding (object dataSource, string dataMember) {

EnsureTableStyleexists (DataSource, DataMember); Base.setDatabase (DataSource, DataMember);}}}

USAGE:

Private autocolumnsize.grid DataGrid1;

SqlConnection nwindconn = new SqlConnection ("data source = localhost; integrated security = sspi; initial catalog = northwind");

SqlCommand selectCMD = new SqlCommand ( "SELECT CustomerID, CompanyName FROM Customers", nwindConn); selectCMD.CommandTimeout = 30; SqlDataAdapter custDA = new SqlDataAdapter (); custDA.SelectCommand = selectCMD;

nwindconn.open ();

DataSet Custds = New Dataset (); Custda.Fill (Custds, "Customers");

NWINDCONN.CLOSE (); if (Custds.tables.count> 0) {dataGrid1.datasource = Custds.tables [0];}

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

New Post(0)