Windows Forms Tips Tricks by jdo47785

VIEWS: 84 PAGES: 27

									Mark Strawmyer
Microsoft MVP

WINFORMS TIPS & TRICKS
AGENDA

 Data Binding Optimization
 Control Population

 PropertyGrid Control

 Threaded UI

 ClickOnce

 User Input Validation

 Report Enable Your Apps
DATA BINDING OPTIMIZATION
   Data binding allows data to be automatically processed and
    displayed in controls

   Changing the .ValueMember property causes most controls to
    repopulate

   Set the DataSource last on controls such as ComboBox and
    ListBox so your control is not populated multiple times

       comboBox1.ValueMember = “ Name” ;
       comboBox1.DisplayMember = “  Name”;
       comboBox1.DataSource = test;
CONTROL POPULATION
   Loading items into controls such as ListView and
    TreeView causes a repainting after each change

   BeginUpdate and EndUpdate allow bulk operations
    without excessive repainting

      listView1.BeginUpdate();
      for(int i = 0; i < 10000; i++)
      {
        ListViewItem listItem = new ListViewItem("Item"+i.ToString() );
        listView1.Items.Add(listItem);
      }
      listView1.EndUpdate();
CONTROL POPULATION
   Use AddRange
     Add  array of pre-created items
     Calls BeginUpdate and EndUpdate automatically
     Performs other optimizations internally


       ListViewItem[] list = new ListViewItem[10000];
       for (int i = 0; i < 10000; i++)
       {
          list[i] = new ListViewItem("Item" + i.ToString());
       }
       listView1.Items.AddRange(list);
CONTROL POPULATION

 Avoid   Items.Clear() with non-databound lists

 Encapsulate    with BeginUpdate and EndUpdate

 Traverse   the list and add, edit, or remove

 Prevents   unnecessary painting and UI delay
PROPERTYGRID CONTROL
   Simple model for displaying property settings
   Can use a serializable object with properties to display,
    save, and load state

    PropertyGrid optionsPropertyGrid = new PropertyGrid();
    optionsPropertyGrid.Size = new Size(300, 250);

    this.Controls.Add(optionsPropertyGrid);
    this.Text = "Options Dialog";

    // Create the class and display in PropertyGrid.
    AppSettings appset = new AppSettings();
    optionsPropertyGrid.SelectedObject = appset;
THREADED UI

 Usingthreads to perform processing increases
  responsiveness and perceived performance
 Especially useful for long running operations


     System.Threading.Thread thread = new
       System.Threading.Thread(
       new System.Threading.ThreadStart(this.GoToSleep));
     thread.Start();
THREADED UI EXAMPLE
CLICKONCE
 Mechanism to combine rich and reach
 Application manifest
     Assemblies, dependencies, files, permissions, and
      update location
   Deployment manifest
     Application   version and location of application manifest
 Launched or installed mode
 Deploy to web site, UNC folder, or CD / DVD
 Updates on startup or after
 Force an update to be mandatory
CLICKONCE

 Publishing wizard
 Mage and MageUI

 Don’ t change deployment type (debug or
  release) as it breaks compatibility with the
  manifest
       d
 GAC’ items aren’   t automatically included in
  the deployment
CLICKONCE EXAMPLE
USER INPUT VALIDATION

 User input validation is the process of ensuring
  data is accurate before processing or storage

 Typically   included in the UI

 Improve  performance by reducing network
  round trips
USER INPUT VALIDATION
   Validation enforced at the control level

   Control has a CausesValidation property that
    dictates whether or not that control fires validation
    when losing focus

   [ControlName]_Validating event is fired as control is
    losing focus

   ErrorProvider controls error messages and display
USER INPUT VALIDATION
 void txtName_Validating(object sender, CancelEventArgs e)
 {
   // Name is required
   if( txtName.Text.Trim().Length == 0 )
   {
     errorProvider.SetError(txtName "Name is required");
     e.Cancel = true;
     return;
   }
   else
   {
     // Name is valid
                                     ”
     errorProvider.SetError(txtName “);
   }
 }
USER INPUT VALIDATION
   Possible one or more controls have not had focus
   Enumerate all form controls and fire Validating event for each
    control

    void btnOK_Click(object sender, System.EventArgs e)
    {
       foreach( Control control in Controls )
       {
         control.Focus();

            // Validate causes the control's Validating event to be fired
            // if .CausesValidation property is true
            if( !this.Validate() )
            {
                       DialogResult = DialogResult.None;
                       return;
            }
        }
    }
PROGRAMMATIC VALIDATION EXAMPLE
USER INPUT VALIDATION
   User input is more difficult than it needs to be
        Winforms use a code intensive approach (programmatic)
        ASP.NET has a control focused approach (declarative)

   Create user controls for validation that match ASP.NET
        Base
        Required field
        Regular expression
        Compare
        Range
        Custom

   http://msdn.microsoft.com/library/default.asp?url=/library/en-
    us/dnforms/html/winforms03162004.asp
DECLARATIVE VALIDATION EXAMPLE
COMPOSITE UI APPLICATION BLOCK

   This is a
    sample call
    center app
   The outer form
    is a shell, which
    hosts
    SmartParts
    (user controls
    similar to
    WebParts)
   Each part can
    stand by itself,
    but also can
    cooperate with
    other parts
REPORT ENABLE YOUR APP

 SQLServer 2005 Reporting Services reports
 can be embedded in windows apps using a
 report viewer

 Multiple   connection modes
   Remote mode
   Local mode
REMOTE PROCESSING MODE

 Report hosted from remote server
 Report rendered in output format
LOCAL PROCESSING MODE

 No  report server involved
 Data source defined in advance

 Data from ADO.NET Table or enumerable
  collection
EMBEDDED REPORT EXAMPLE
PRINT TO EXCEL
string mimeType = null;
string encoding = null;
string fileNameExtension = null;
string[] streams = null;
Microsoft.Reporting.WinForms.Warning[] warnings = null;
string deviceInfo = "<DeviceInfo><SimplePageHeaders>True</SimplePageHeaders></DeviceInfo>";

Microsoft.Reporting.WinForms.LocalReport localReport = new Microsoft.Reporting.WinForms.LocalReport();
localReport.ReportPath = @"..\..\Local Report Store Information.rdlc";

this.Adventure.EnforceConstraints = false;
                                                                              Sales“GetData()));
localReport.DataSources.Add(new Microsoft.Reporting.WinForms.ReportDataSource(“    ,

byte[] bytes = reportViewer1.LocalReport.Render("Excel", deviceInfo, out mimeType, out encoding, out
     fileNameExtension, out streams, out warnings);
System.IO.FileStream fileStream = new System.IO.FileStream(@"c:\ExcelExportSample.xls",
     System.IO.FileMode.Create);

fileStream.Write(bytes, 0, bytes.Length);
fileStream.Close();
PRINT TO EXCEL EXAMPLE
MORE INFORMATION
   Extending Windows Forms with a Custom Validation Component
    Library
    http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnforms/html/winforms03162004.asp


   Practical Tips for Boosting The Performance of Windows Forms Apps
    http://msdn.microsoft.com/msdnmag/issues/06/03/WindowsFormsPerformance/


   MSDN ReportViewer
    http://msdn2.microsoft.com/en-US/library/ms251671.aspx


   ClickOnce Extends Windows Forms Application into Smart Client
    Applications
    http://www.codeguru.com/columns/dotnet/article.php/c12465/

   SQL Server 2005 Reporting Services in Action
    http://www.manning.com/updegraff/

								
To top