### VB.NET Example: Custom ToolStrip and MenuStrip Setup Source: https://learn.microsoft.com/en-us/dotnet/desktop/winforms/controls/how-to-set-the-toolstrip-renderer-at-run-time Demonstrates creating and populating ToolStrip and MenuStrip controls, including a button to trigger custom color changes in VB.NET. ```vbnet ' This code example demonstrates how to use a ProfessionalRenderer ' to define custom professional colors at runtime. Class Form2 Inherits Form Public Sub New() ' Create a new ToolStrip control. Dim ts As New ToolStrip() ' Populate the ToolStrip control. ts.Items.Add("Apples") ts.Items.Add("Oranges") ts.Items.Add("Pears") ts.Items.Add("Change Colors", Nothing, New EventHandler(AddressOf ChangeColors_Click)) ' Create a new MenuStrip. Dim ms As New MenuStrip() ' Dock the MenuStrip control to the top of the form. ms.Dock = DockStyle.Top ' Add the top-level menu items. ms.Items.Add("File") ms.Items.Add("Edit") ms.Items.Add("View") ms.Items.Add("Window") ' Add the ToolStrip to Controls collection. Me.Controls.Add(ts) ' Add the MenuStrip control last. ' This is important for correct placement in the z-order. Me.Controls.Add(ms) End Sub ' This event handler is invoked when the "Change colors" ' ToolStripItem is clicked. It assigns the Renderer ' property for the ToolStrip control. Sub ChangeColors_Click(ByVal sender As Object, ByVal e As EventArgs) ToolStripManager.Renderer = New ToolStripProfessionalRenderer(New CustomProfessionalColors()) End Sub End Class ' This class defines the gradient colors for ' the MenuStrip and the ToolStrip. Class CustomProfessionalColors Inherits ProfessionalColorTable Public Overrides ReadOnly Property ToolStripGradientBegin() As Color Get Return Color.BlueViolet End Get End Property Public Overrides ReadOnly Property ToolStripGradientMiddle() As Color Get Return Color.CadetBlue End Get End Property Public Overrides ReadOnly Property ToolStripGradientEnd() As Color Get Return Color.CornflowerBlue End Get End Property Public Overrides ReadOnly Property MenuStripGradientBegin() As Color Get Return Color.Salmon End Get End Property Public Overrides ReadOnly Property MenuStripGradientEnd() Get Return Color.OrangeRed End Get End Property End Class ``` -------------------------------- ### Post Column Creation Setup Source: https://learn.microsoft.com/en-us/dotnet/desktop/winforms/controls/how-to-manipulate-columns-in-the-windows-forms-datagridview-control Performs various setup tasks after DataGridView columns have been created, including adding labels, context menus, and tooltips. ```csharp private void PostColumnCreation() { AddContextLabel(); AddCriteriaLabel(); CustomizeCellsInThirdColumn(); AddContextMenu(); SetDefaultCellInFirstColumn(); ToolTips(); dataGridView.CellMouseEnter += dataGridView_CellMouseEnter; dataGridView.AutoSizeColumnModeChanged += dataGridView_AutoSizeColumnModeChanged; } ``` -------------------------------- ### Show Page Setup Dialog Source: https://learn.microsoft.com/en-us/dotnet/desktop/winforms/controls/how-to-add-web-browser-capabilities-to-a-windows-forms-application This method displays the 'Page Setup' dialog box, enabling users to configure print settings such as paper size, orientation, and margins. ```C# // Displays the Page Setup dialog box. void MenuItemFilePageSetup_Click( System::Object^ /*sender*/, System::EventArgs^ /*e*/ ) { this->WebBrowser1->ShowPageSetupDialog(); } ``` -------------------------------- ### Handle Start Button Click Event Source: https://learn.microsoft.com/en-us/dotnet/desktop/winforms/controls/how-to-apply-attributes-in-windows-forms-controls Initiates the data logging process by starting the timer and reporting the action to the status strip. This is the entry point for activating the performance monitoring. ```C# private void startButton_Click(object sender, EventArgs e) { this.ReportStatus(DateTime.Now + ": Starting"); this.timer1.Start(); } ``` -------------------------------- ### Start Background Download and Wait (C#) Source: https://learn.microsoft.com/en-us/dotnet/desktop/winforms/controls/how-to-download-a-file-in-the-background This C# code starts a background download and then enters a loop to update a progress bar while the download is in progress. It uses Application.DoEvents() to keep the UI responsive. ```csharp private void downloadButton_Click(object sender, EventArgs e) { // Start the download operation in the background. this.backgroundWorker1.RunWorkerAsync(); // Disable the button for the duration of the download. this.downloadButton.Enabled = false; // Once you have started the background thread you // can exit the handler and the application will // wait until the RunWorkerCompleted event is raised. // Or if you want to do something else in the main thread, // such as update a progress bar, you can do so in a loop // while checking IsBusy to see if the background task is // still running. while (this.backgroundWorker1.IsBusy) { progressBar1.Increment(1); // Keep UI messages moving, so the form remains // responsive during the asynchronous operation. Application.DoEvents(); } } ``` -------------------------------- ### Run DataGridViewBandDemo Application Source: https://learn.microsoft.com/en-us/dotnet/desktop/winforms/controls/how-to-manipulate-bands-in-the-windows-forms-datagridview-control Starts the DataGridViewBandDemo application. ```vbnet Public Shared Sub Main() Application.Run(New DataGridViewBandDemo()) End Sub End Class ``` -------------------------------- ### WinForms Directory Searcher Example Source: https://learn.microsoft.com/en-us/dotnet/desktop/winforms/controls/how-to-use-a-background-thread-to-search-for-files This code demonstrates the setup and usage of the DirectorySearcher control in a Windows Forms application. It includes form initialization, button click event handling to start a search, and handling the search completion event. ```VB.NET Option Explicit Option Strict Imports System.Collections Imports System.ComponentModel Imports System.Data Imports System.Drawing Imports System.Windows.Forms Imports Microsoft.Samples.DirectorySearcher Namespace SampleUsage ' ' Summary description for Form1. ' Public Class Form1 Inherits System.Windows.Forms.Form Private WithEvents directorySearcher As DirectorySearcher Private searchText As System.Windows.Forms.TextBox Private searchLabel As System.Windows.Forms.Label Private WithEvents searchButton As System.Windows.Forms.Button Public Sub New() ' ' Required for Windows Forms designer support. ' InitializeComponent() ' ' Add any constructor code after InitializeComponent call here. ' End Sub #Region "Windows Form Designer generated code" ' ' Required method for designer support. Do not modify ' the contents of this method with the code editor. ' Private Sub InitializeComponent() Me.directorySearcher = New Microsoft.Samples.DirectorySearcher.DirectorySearcher() Me.searchButton = New System.Windows.Forms.Button() Me.searchText = New System.Windows.Forms.TextBox() Me.searchLabel = New System.Windows.Forms.Label() Me.directorySearcher.Anchor = System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Left Or System.Windows.Forms.AnchorStyles.Right Me.directorySearcher.Location = New System.Drawing.Point(8, 72) Me.directorySearcher.SearchCriteria = Nothing Me.directorySearcher.Size = New System.Drawing.Size(271, 173) Me.directorySearcher.TabIndex = 2 Me.searchButton.Location = New System.Drawing.Point(8, 16) Me.searchButton.Size = New System.Drawing.Size(88, 40) Me.searchButton.TabIndex = 0 Me.searchButton.Text = "&Search" Me.searchText.Anchor = System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left Or System.Windows.Forms.AnchorStyles.Right Me.searchText.Location = New System.Drawing.Point(104, 24) Me.searchText.Size = New System.Drawing.Size(175, 20) Me.searchText.TabIndex = 1 Me.searchText.Text = "c:\\*.cs" Me.searchLabel.ForeColor = System.Drawing.Color.Red Me.searchLabel.Location = New System.Drawing.Point(104, 48) Me.searchLabel.Size = New System.Drawing.Size(176, 16) Me.searchLabel.TabIndex = 3 Me.ClientSize = New System.Drawing.Size(291, 264) Me.Controls.AddRange(New System.Windows.Forms.Control() {Me.searchLabel, Me.directorySearcher, Me.searchText, Me.searchButton}) Me.Text = "Search Directories" End Sub #End Region ' ' The main entry point for the application. ' _ Shared Sub Main() Application.Run(New Form1()) End Sub Private Sub searchButton_Click(sender As Object, e As System.EventArgs) Handles searchButton.Click directorySearcher.SearchCriteria = searchText.Text searchLabel.Text = "Searching..." directorySearcher.BeginSearch() End Sub Private Sub directorySearcher_SearchComplete(sender As Object, e As System.EventArgs) Handles directorySearcher.SearchComplete searchLabel.Text = String.Empty End Sub End Class End Namespace ``` -------------------------------- ### Implement IHostedService in C# Source: https://learn.microsoft.com/en-us/dotnet/desktop/winforms/advanced/how-to-use-host-builder Implement `IHostedService` to define background services that receive callbacks when the host starts and stops. This example writes to debug output upon starting and stopping. ```csharp public class SampleLifecycleService : IHostedService { public Task StartAsync(CancellationToken cancellationToken) { System.Diagnostics.Debug.WriteLine("SampleLifecycleService: Started."); return Task.CompletedTask; } public Task StopAsync(CancellationToken cancellationToken) { System.Diagnostics.Debug.WriteLine("SampleLifecycleService: Stopped."); return Task.CompletedTask; } } ``` -------------------------------- ### Initialize Form and DataGridView (C++/CLI) Source: https://learn.microsoft.com/en-us/dotnet/desktop/winforms/controls/implementing-virtual-mode-wf-datagridview-control Sets up the main form, initializes the DataGridView control, and prepares the data store. This code is part of the basic setup for virtual mode. ```cpp #using #using #using using namespace System; using namespace System::Windows::Forms; public ref class Customer { private: String^ companyNameValue; String^ contactNameValue; public: Customer() { // Leave fields empty. } Customer( String^ companyName, String^ contactName ) { companyNameValue = companyName; contactNameValue = contactName; } property String^ CompanyName { String^ get() { return companyNameValue; } void set( String^ value ) { companyNameValue = value; } } property String^ ContactName { String^ get() { return contactNameValue; } void set( String^ value ) { contactNameValue = value; } } }; public ref class Form1: public Form { private: DataGridView^ dataGridView1; // Declare an ArrayList to serve as the data store. System::Collections::ArrayList^ customers; // Declare a Customer object to store data for a row being edited. Customer^ customerInEdit; // Declare a variable to store the index of a row being edited. // A value of -1 indicates that there is no row currently in edit. int rowInEdit; // Declare a variable to indicate the commit scope. // Set this value to false to use cell-level commit scope. bool rowScopeCommit; public: static void Main() { Application::Run( gcnew Form1 ); } Form1() { dataGridView1 = gcnew DataGridView; customers = gcnew System::Collections::ArrayList; rowInEdit = -1; rowScopeCommit = true; // Initialize the form. this->dataGridView1->Dock = DockStyle::Fill; this->Controls->Add( this->dataGridView1 ); this->Load += gcnew EventHandler( this, &Form1::Form1_Load ); } private: ``` -------------------------------- ### Form Initialization and Setup Source: https://learn.microsoft.com/en-us/dotnet/desktop/winforms/how-to-implement-the-ilistsource-interface Sets up the main form, including its dimensions, controls, and name. It also handles the layout and initialization of child controls like DataGridView and FlowLayoutPanel. ```C# // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(416, 266); this.Controls.Add(this.dataGridView1); this.Controls.Add(this.flowLayoutPanel1); this.Name = "Form1"; this.Text = "IListSource Sample"; this.flowLayoutPanel1.ResumeLayout(false); this.flowLayoutPanel1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); ``` -------------------------------- ### Enumerate Installed Font Families (VB.NET) Source: https://learn.microsoft.com/en-us/dotnet/desktop/winforms/advanced/how-to-enumerate-installed-fonts This VB.NET snippet achieves the same functionality as the C# example, listing installed font families. It requires the PaintEventArgs 'e' and the System.Drawing.Text namespace. ```vb Dim fontFamily As New FontFamily("Arial") Dim font As New Font( _ fontFamily, _ 8, _ FontStyle.Regular, _ GraphicsUnit.Point) Dim rectF As New RectangleF(10, 10, 500, 500) Dim solidBrush As New SolidBrush(Color.Black) Dim familyName As String Dim familyList As String = "" Dim fontFamilies() As FontFamily Dim installedFontCollection As New InstalledFontCollection() ' Get the array of FontFamily objects. fontFamilies = installedFontCollection.Families ' The loop below creates a large string that is a comma-separated ' list of all font family names. Dim count As Integer = fontFamilies.Length Dim j As Integer While j < count familyName = fontFamilies(j).Name familyList = familyList & familyName familyList = familyList & ", " j += 1 End While ' Draw the large string (list of all families) in a rectangle. e.Graphics.DrawString(familyList, font, solidBrush, rectF) ``` -------------------------------- ### Create and configure a form with ToolStrip and MenuStrip Source: https://learn.microsoft.com/en-us/dotnet/desktop/winforms/controls/how-to-set-the-toolstrip-renderer-for-an-application This C# code example demonstrates how to create a form, add a ToolStrip and a MenuStrip, and set up controls for applying custom renderers. It includes event handling for a button click to apply the renderers. ```C# // This example demonstrates how to apply a // custom professional renderer to an individual // ToolStrip or to the application as a whole. class Form6 : Form { ComboBox targetComboBox = new ComboBox(); public Form6() { // Alter the renderer at the top level. // Create and populate a new ToolStrip control. ToolStrip ts = new ToolStrip(); ts.Name = "ToolStrip"; ts.Items.Add("Apples"); ts.Items.Add("Oranges"); ts.Items.Add("Pears"); // Create a new menustrip with a new window. MenuStrip ms = new MenuStrip(); ms.Name = "MenuStrip"; ms.Dock = DockStyle.Top; // add top level items ToolStripMenuItem fileMenuItem = new ToolStripMenuItem("File"); ms.Items.Add(fileMenuItem); ms.Items.Add("Edit"); ms.Items.Add("View"); ms.Items.Add("Window"); // Add subitems to the "File" menu. fileMenuItem.DropDownItems.Add("Open"); fileMenuItem.DropDownItems.Add("Save"); fileMenuItem.DropDownItems.Add("Save As..."); fileMenuItem.DropDownItems.Add("-"); fileMenuItem.DropDownItems.Add("Exit"); // Add a Button control to apply renderers. Button applyButton = new Button(); applyButton.Text = "Apply Custom Renderer"; applyButton.Click += new EventHandler(applyButton_Click); // Add the ComboBox control for choosing how // to apply the renderers. targetComboBox.Items.Add("All"); targetComboBox.Items.Add("MenuStrip"); targetComboBox.Items.Add("ToolStrip"); targetComboBox.Items.Add("Reset"); // Create and set up a TableLayoutPanel control. TableLayoutPanel tlp = new TableLayoutPanel(); tlp.Dock = DockStyle.Fill; tlp.RowCount = 1; tlp.ColumnCount = 2; tlp.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize)); tlp.ColumnStyles.Add(new ColumnStyle(SizeType.Percent)); tlp.Controls.Add(applyButton); tlp.Controls.Add(targetComboBox); // Create a GroupBox for the TableLayoutPanel control. GroupBox gb = new GroupBox(); gb.Text = "Apply Renderers"; gb.Dock = DockStyle.Fill; gb.Controls.Add(tlp); // Add the GroupBox to the form. this.Controls.Add(gb); // Add the ToolStrip to the form's Controls collection. this.Controls.Add(ts); // Add the MenuStrip control last. // This is important for correct placement in the z-order. this.Controls.Add(ms); } // This event handler is invoked when // the "Apply Renderers" button is clicked. // Depending on the value selected in a ComboBox control, // it applies a custom renderer selectively to // individual MenuStrip or ToolStrip controls, // or it applies a custom renderer to the // application as a whole. void applyButton_Click(object sender, EventArgs e) { ToolStrip ms = ToolStripManager.FindToolStrip("MenuStrip"); ToolStrip ts = ToolStripManager.FindToolStrip("ToolStrip"); ``` -------------------------------- ### Implement IHostedService in VB.NET Source: https://learn.microsoft.com/en-us/dotnet/desktop/winforms/advanced/how-to-use-host-builder Implement `IHostedService` in Visual Basic .NET to define background services that receive callbacks when the host starts and stops. This example writes to debug output upon starting and stopping. ```vbnet Public Class SampleLifecycleService Implements IHostedService Public Function StartAsync(cancellationToken As CancellationToken) As Task Implements IHostedService.StartAsync System.Diagnostics.Debug.WriteLine("SampleLifecycleService: Started.") Return Task.CompletedTask End Function Public Function StopAsync(cancellationToken As CancellationToken) As Task Implements IHostedService.StopAsync System.Diagnostics.Debug.WriteLine("SampleLifecycleService: Stopped.") Return Task.CompletedTask End Function End Class ``` -------------------------------- ### Initialize Form with ToolStrip and MenuStrip Controls Source: https://learn.microsoft.com/en-us/dotnet/desktop/winforms/controls/how-to-set-the-toolstrip-renderer-for-an-application This example demonstrates how to initialize a Windows Form with a ToolStrip, a MenuStrip, and various controls for applying custom renderers. It sets up the basic structure and adds event handlers. ```vbnet ' This example demonstrates how to apply a ' custom professional renderer to an individual ' ToolStrip or to the application as a whole. Class Form6 Inherits Form Private targetComboBox As New ComboBox() Public Sub New() ' Alter the renderer at the top level. ' Create and populate a new ToolStrip control. Dim ts As New ToolStrip() ts.Name = "ToolStrip" ts.Items.Add("Apples") ts.Items.Add("Oranges") ts.Items.Add("Pears") ' Create a new menustrip with a new window. Dim ms As New MenuStrip() ms.Name = "MenuStrip" ms.Dock = DockStyle.Top ' add top level items Dim fileMenuItem As New ToolStripMenuItem("File") ms.Items.Add(fileMenuItem) ms.Items.Add("Edit") ms.Items.Add("View") ms.Items.Add("Window") ' Add subitems to the "File" menu. fileMenuItem.DropDownItems.Add("Open") fileMenuItem.DropDownItems.Add("Save") fileMenuItem.DropDownItems.Add("Save As...") fileMenuItem.DropDownItems.Add("-") fileMenuItem.DropDownItems.Add("Exit") ' Add a Button control to apply renderers. Dim applyButton As New Button() applyButton.Text = "Apply Custom Renderer" AddHandler applyButton.Click, AddressOf applyButton_Click ' Add the ComboBox control for choosing how ' to apply the renderers. targetComboBox.Items.Add("All") targetComboBox.Items.Add("MenuStrip") targetComboBox.Items.Add("ToolStrip") targetComboBox.Items.Add("Reset") ' Create and set up a TableLayoutPanel control. Dim tlp As New TableLayoutPanel() tlp.Dock = DockStyle.Fill tlp.RowCount = 1 tlp.ColumnCount = 2 tlp.ColumnStyles.Add(New ColumnStyle(SizeType.AutoSize)) tlp.ColumnStyles.Add(New ColumnStyle(SizeType.Percent)) tlp.Controls.Add(applyButton) tlp.Controls.Add(targetComboBox) ``` -------------------------------- ### Set LinkArea Property in C++ Source: https://learn.microsoft.com/en-us/dotnet/desktop/winforms/controls/link-to-an-object-or-web-page-with-wf-linklabel-control Sets the LinkArea property to define the clickable portion of the LinkLabel's text. This example sets the link to start at the first character and span eight characters. ```C++ // In this code example, the link area has been set to begin // at the first character and extend for eight characters. // You may need to modify this based on the text entered in Step 1. linkLabel1->LinkArea = LinkArea(0,8); ``` -------------------------------- ### Initialize DataGridView and Add Buttons (C#) Source: https://learn.microsoft.com/en-us/dotnet/desktop/winforms/controls/how-to-manipulate-bands-in-the-windows-forms-datagridview-control Sets up the main form, initializes the DataGridView, and adds various buttons for demonstrating band manipulation. ```csharp using System.Drawing; using System.Windows.Forms; using System; public class DataGridViewBandDemo : Form { #region "form setup" public DataGridViewBandDemo() { InitializeComponent(); AddButton(Button1, "Reset", new EventHandler(Button1_Click)); AddButton(Button2, "Change Column 3 Header", new EventHandler(Button2_Click)); AddButton(Button3, "Change Meatloaf Recipe", new EventHandler(Button3_Click)); AddAdditionalButtons(); InitializeDataGridView(); } DataGridView dataGridView; Button Button1 = new Button(); Button Button2 = new Button(); Button Button3 = new Button(); Button Button4 = new Button(); Button Button5 = new Button(); Button Button6 = new Button(); Button Button7 = new Button(); Button Button8 = new Button(); Button Button9 = new Button(); Button Button10 = new Button(); FlowLayoutPanel FlowLayoutPanel1 = new FlowLayoutPanel(); ``` -------------------------------- ### Set LinkArea Property in C# Source: https://learn.microsoft.com/en-us/dotnet/desktop/winforms/controls/link-to-an-object-or-web-page-with-wf-linklabel-control Sets the LinkArea property to define the clickable portion of the LinkLabel's text. This example sets the link to start at the first character and span eight characters. ```C# // In this code example, the link area has been set to begin // at the first character and extend for eight characters. // You may need to modify this based on the text entered in Step 1. linkLabel1.LinkArea = new LinkArea(0,8); ``` -------------------------------- ### Example app.exe.config File for Application and User Settings Source: https://learn.microsoft.com/en-us/dotnet/desktop/winforms/advanced/application-settings-architecture This XML configuration file demonstrates how to structure both application-scoped and user-scoped settings. It includes sections for application settings and user settings, defining specific settings within each. ```XML
Default False Form1 595, 536 ``` -------------------------------- ### Set LinkArea Property in VB Source: https://learn.microsoft.com/en-us/dotnet/desktop/winforms/controls/link-to-an-object-or-web-page-with-wf-linklabel-control Sets the LinkArea property to define the clickable portion of the LinkLabel's text. This example sets the link to start at the first character and span eight characters. ```VB ' In this code example, the link area has been set to begin ' at the first character and extend for eight characters. ' You may need to modify this based on the text entered in Step 1. LinkLabel1.LinkArea = New LinkArea(0, 8) ``` -------------------------------- ### Windows Forms Application Setup Source: https://learn.microsoft.com/en-us/dotnet/desktop/winforms/controls/how-to-bind-to-a-web-service-using-the-windows-forms-bindingsource Sets up a basic Windows Forms application with controls and initializes the BindingSource. ```vbnet Imports System.Collections.Generic Imports System.ComponentModel Imports System.Drawing Imports System.Windows.Forms Namespace BindToWebService Class Form1 Inherits Form Shared Sub Main() Application.EnableVisualStyles() Application.Run(New Form1()) End Sub Private BindingSource1 As New BindingSource() Private textBox1 As New TextBox() Private textBox2 As New TextBox() Private WithEvents button1 As New Button() Public Sub New() textBox1.Location = New System.Drawing.Point(118, 131) textBox1.ReadOnly = True button1.Location = New System.Drawing.Point(133, 60) button1.Text = "Get zipcode" ClientSize = New System.Drawing.Size(292, 266) Controls.Add(Me.button1) Controls.Add(Me.textBox1) End Sub Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs) _ Handles button1.Click textBox1.Text = "Calling Web service.." Dim resolver As New ZipCodeResolver() BindingSource1.Add(resolver.CorrectedAddressXml("0", "One Microsoft Way", "Redmond", "WA")) End Sub End Class End Namespace ``` -------------------------------- ### Complete Windows Forms DataGridView Data Binding Example Source: https://learn.microsoft.com/en-us/dotnet/desktop/winforms/controls/how-to-bind-data-to-the-windows-forms-datagridview-control This example demonstrates a complete Windows Forms application that binds a DataGridView to data from a SQL Server database. It includes setup for the DataGridView, BindingSource, SqlDataAdapter, and buttons for reloading data and submitting changes. Ensure you replace the placeholder connection string with your actual database connection details. ```vbnet Imports System.Data.SqlClient Imports System.Windows.Forms Public Class Form1 Inherits Form Private dataGridView1 As New DataGridView() Private bindingSource1 As New BindingSource() Private dataAdapter As SqlDataAdapter Private WithEvents ReloadButton As New Button() Private WithEvents SubmitButton As New Button() Public Shared Sub Main() Application.Run(New Form1()) End Sub ' Initialize the form. Public Sub New() dataGridView1.Dock = DockStyle.Fill ReloadButton.Text = "Reload" SubmitButton.Text = "Submit" Dim panel As New FlowLayoutPanel With { .Dock = DockStyle.Top, .AutoSize = True } panel.Controls.AddRange(New Control() {ReloadButton, SubmitButton}) Controls.AddRange(New Control() {dataGridView1, panel}) Text = "DataGridView data binding and updating demo" End Sub Private Sub GetData(ByVal selectCommand As String) Try ' Specify a connection string. ' Replace with the SQL Server for your Northwind sample database. ' Replace "Integrated Security=True" with user login information if necessary. Dim connectionString As String = "Data Source=;Initial Catalog=Northwind;" + "Integrated Security=True;" ' Create a new data adapter based on the specified query. dataAdapter = New SqlDataAdapter(selectCommand, connectionString) ' Create a command builder to generate SQL update, insert, and ' delete commands based on selectCommand. Dim commandBuilder As New SqlCommandBuilder(dataAdapter) ' Populate a new data table and bind it to the BindingSource. Dim table As New DataTable With { .Locale = Globalization.CultureInfo.InvariantCulture } dataAdapter.Fill(table) bindingSource1.DataSource = table ' Resize the DataGridView columns to fit the newly loaded content. dataGridView1.AutoResizeColumns( DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader) Catch ex As SqlException MessageBox.Show("To run this example, replace the value of the " + _ "connectionString variable with a connection string that is " + _ "valid for your system.") End Try End Sub Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) _ Handles Me.Load ' Bind the DataGridView to the BindingSource ' and load the data from the database. dataGridView1.DataSource = bindingSource1 GetData("select * from Customers") End Sub Private Sub ReloadButton_Click(ByVal sender As Object, ByVal e As EventArgs) _ Handles ReloadButton.Click ' Reload the data from the database. GetData(dataAdapter.SelectCommand.CommandText) End Sub Private Sub SubmitButton_Click(ByVal sender As Object, ByVal e As EventArgs) _ Handles SubmitButton.Click ' Update the database with changes. dataAdapter.Update(CType(bindingSource1.DataSource, DataTable)) End Sub End Class ``` -------------------------------- ### Initialize Form and DataGridView (C#) Source: https://learn.microsoft.com/en-us/dotnet/desktop/winforms/controls/implementing-virtual-mode-wf-datagridview-control Sets up the main form, initializes the DataGridView control, and prepares the data store. This code is part of the basic setup for virtual mode. ```csharp using System; using System.Windows.Forms; public class Form1 : Form { private DataGridView dataGridView1 = new DataGridView(); // Declare an ArrayList to serve as the data store. private System.Collections.ArrayList customers = new System.Collections.ArrayList(); // Declare a Customer object to store data for a row being edited. private Customer customerInEdit; // Declare a variable to store the index of a row being edited. // A value of -1 indicates that there is no row currently in edit. private int rowInEdit = -1; // Declare a variable to indicate the commit scope. // Set this value to false to use cell-level commit scope. private bool rowScopeCommit = true; [STAThreadAttribute()] public static void Main() { Application.Run(new Form1()); } public Form1() { // Initialize the form. this.dataGridView1.Dock = DockStyle.Fill; this.Controls.Add(this.dataGridView1); this.Load += new EventHandler(Form1_Load); this.Text = "DataGridView virtual-mode demo (row-level commit scope)"; } ``` -------------------------------- ### C++/CLI Timer Initialization and Event Handling Source: https://learn.microsoft.com/en-us/dotnet/desktop/winforms/controls/run-procedures-at-set-intervals-with-wf-timer-component Initializes a timer to tick every second and updates a label with the current time. Includes logic to start and stop the timer using a button click. This example is for C++/CLI. ```cpp private: void InitializeTimer() { // Run this procedure in an appropriate event. // Set to 1 second. timer1->Interval = 1000; // Enable timer. timer1->Enabled = true; this->timer1->Tick += gcnew System::EventHandler(this, &Form1::timer1_Tick); button1->Text = S"Stop"; this->button1->Click += gcnew System::EventHandler(this, &Form1::button1_Click); } void timer1_Tick(System::Object ^ sender, System::EventArgs ^ e) { // Set the caption to the current time. label1->Text = DateTime::Now.ToString(); } void button1_Click(System::Object ^ sender, System::EventArgs ^ e) { if ( button1->Text == "Stop" ) { button1->Text = "Start"; timer1->Enabled = false; } else { button1->Text = "Stop"; timer1->Enabled = true; } } ``` -------------------------------- ### Initialize DataGridView and Add Buttons (C#) Source: https://learn.microsoft.com/en-us/dotnet/desktop/winforms/controls/how-to-manipulate-rows-in-the-windows-forms-datagridview-control Sets up the main form, including initializing the DataGridView and adding buttons with associated event handlers. This forms the basic structure for the demo. ```C# public DataGridViewRowDemo() { InitializeComponent(); AddButton(Button1, "Reset", new EventHandler(Button1_Click)); AddButton(Button2, "Change Column 3 Header", new EventHandler(Button2_Click)); AddButton(Button3, "Change Meatloaf Recipe", new EventHandler(Button3_Click)); AddAdditionalButtons(); InitializeDataGridView(); } private DataGridView dataGridView; private Button Button1 = new Button(); private Button Button2 = new Button(); private Button Button3 = new Button(); private Button Button4 = new Button(); private Button Button5 = new Button(); private Button Button6 = new Button(); private Button Button7 = new Button(); private Button Button8 = new Button(); private Button Button9 = new Button(); private Button Button10 = new Button(); private FlowLayoutPanel FlowLayoutPanel1 = new FlowLayoutPanel(); private void InitializeComponent() { FlowLayoutPanel1.Location = new Point(454, 0); FlowLayoutPanel1.AutoSize = true; FlowLayoutPanel1.FlowDirection = FlowDirection.TopDown; AutoSize = true; ClientSize = new System.Drawing.Size(614, 360); FlowLayoutPanel1.Name = "flowlayoutpanel"; Controls.Add(this.FlowLayoutPanel1); Text = this.GetType().Name; } ``` -------------------------------- ### Define Diagonal Linear Gradient in C# Source: https://learn.microsoft.com/en-us/dotnet/desktop/winforms/advanced/how-to-create-a-linear-gradient This C# example demonstrates creating a diagonal linear gradient by specifying start and end points for the brush. The color changes gradually along the line defined by these points. ```csharp LinearGradientBrush brush = new LinearGradientBrush(new Point(0, 0), new Point(200, 100), Color.Blue, Color.Green); Pen pen = new Pen(brush, 10); e.Graphics.DrawLine(pen, 0, 0, 200, 100); e.Graphics.FillEllipse(brush, 50, 50, 100, 100); ``` -------------------------------- ### Form Initialization and Virtual Mode Setup Source: https://learn.microsoft.com/en-us/dotnet/desktop/winforms/controls/how-to-implement-virtual-mode-in-the-windows-forms-datagridview-control Initializes the main form, adds a DataGridView control, and enables virtual mode for efficient data handling. ```vbnet Imports System.Windows.Forms Public Class Form1 Inherits Form Private WithEvents dataGridView1 As New DataGridView() ' Declare an ArrayList to serve as the data store. Private customers As New System.Collections.ArrayList() ' Declare a Customer object to store data for a row being edited. Private customerInEdit As Customer ' Declare a variable to store the index of a row being edited. ' A value of -1 indicates that there is no row currently in edit. Private rowInEdit As Integer = -1 ' Declare a variable to indicate the commit scope. ' Set this value to false to use cell-level commit scope. Private rowScopeCommit As Boolean = True _ Public Shared Sub Main() Application.Run(New Form1()) End Sub Public Sub New() ' Initialize the form. Me.dataGridView1.Dock = DockStyle.Fill Me.Controls.Add(Me.dataGridView1) Me.Text = "DataGridView virtual-mode demo (row-level commit scope)" End Sub Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) _ Handles Me.Load ' Enable virtual mode. Me.dataGridView1.VirtualMode = True End Sub End Class ``` -------------------------------- ### Background File Download with BackgroundWorker Source: https://learn.microsoft.com/en-us/dotnet/desktop/winforms/controls/how-to-download-a-file-in-the-background This example demonstrates using a BackgroundWorker to load an XML file from a URL. The download starts when a button is clicked, disabling the button during the operation. A MessageBox shows the file content upon completion. ```C# using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Threading; using System.Windows.Forms; using System.Xml; public class Form1 : Form { private BackgroundWorker backgroundWorker1; private Button downloadButton; private ProgressBar progressBar1; private XmlDocument document = null; public Form1() { InitializeComponent(); // Instantiate BackgroundWorker and attach handlers to its // DoWork and RunWorkerCompleted events. backgroundWorker1 = new System.ComponentModel.BackgroundWorker(); backgroundWorker1.DoWork += new System.ComponentModel.DoWorkEventHandler(this.backgroundWorker1_DoWork); backgroundWorker1.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.backgroundWorker1_RunWorkerCompleted); } private void downloadButton_Click(object sender, EventArgs e) { // Start the download operation in the background. this.backgroundWorker1.RunWorkerAsync(); // Disable the button for the duration of the download. this.downloadButton.Enabled = false; // Once you have started the background thread you // can exit the handler and the application will // wait until the RunWorkerCompleted event is raised. // Or if you want to do something else in the main thread, // such as update a progress bar, you can do so in a loop // while checking IsBusy to see if the background task is // still running. while (this.backgroundWorker1.IsBusy) { progressBar1.Increment(1); // Keep UI messages moving, so the form remains // responsive during the asynchronous operation. Application.DoEvents(); } } private void backgroundWorker1_DoWork( object sender, DoWorkEventArgs e) { document = new XmlDocument(); // Uncomment the following line to // simulate a noticeable latency. //Thread.Sleep(5000); // Replace this file name with a valid file name. document.Load(@"http://www.tailspintoys.com/sample.xml"); } private void backgroundWorker1_RunWorkerCompleted( object sender, RunWorkerCompletedEventArgs e) { // Set progress bar to 100% in case it's not already there. progressBar1.Value = 100; if (e.Error == null) { MessageBox.Show(document.InnerXml, "Download Complete"); } else { MessageBox.Show( "Failed to download file", "Download failed", MessageBoxButtons.OK, MessageBoxIcon.Error); } // Enable the download button and reset the progress bar. this.downloadButton.Enabled = true; progressBar1.Value = 0; } #region Windows Form Designer generated code /// /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } ``` -------------------------------- ### Initialize ListView and Search Box (C++/CLI) Source: https://learn.microsoft.com/en-us/dotnet/desktop/winforms/controls/how-to-add-search-capabilities-to-a-listview-control Initializes a ListView and a TextBox, populates the ListView with items, and sets up event handling for text changes to enable searching. This code is for C++/CLI. ```cpp private: ListView^ textListView; TextBox^ searchBox; private: void InitializeTextSearchListView() { textListView = gcnew ListView(); searchBox = gcnew TextBox(); searchBox->Location = Point(150, 20); textListView->Scrollable = true; textListView->Width = 100; // Set the View to list to use the FindItemWithText method. textListView->View = View::List; // Populate the ListViewWithItems textListView->Items->AddRange(gcnew array{ gcnew ListViewItem("Amy Alberts"), gcnew ListViewItem("Amy Recker"), gcnew ListViewItem("Erin Hagens"), gcnew ListViewItem("Barry Johnson"), gcnew ListViewItem("Jay Hamlin"), gcnew ListViewItem("Brian Valentine"), gcnew ListViewItem("Brian Welker"), gcnew ListViewItem("Daniel Weisman") }); // Handle the TextChanged to get the text for our search. searchBox->TextChanged += gcnew EventHandler(this, &Form1::searchBox_TextChanged); // Add the controls to the form. this->Controls->Add(textListView); this->Controls->Add(searchBox); } private: void searchBox_TextChanged(Object^ sender, EventArgs^ e) { // Call FindItemWithText with the contents of the textbox. ListViewItem^ foundItem = textListView->FindItemWithText(searchBox->Text, false, 0, true); if (foundItem != nullptr) { textListView->TopItem = foundItem; } } ``` -------------------------------- ### C# Timer Initialization and Event Handling Source: https://learn.microsoft.com/en-us/dotnet/desktop/winforms/controls/run-procedures-at-set-intervals-with-wf-timer-component Initializes a timer to tick every second and updates a label with the current time. Includes logic to start and stop the timer using a button click. This example requires a form with Button1, Timer1, and Label1 controls. ```csharp private void InitializeTimer() { // Call this procedure when the application starts. // Set to 1 second. Timer1.Interval = 1000; Timer1.Tick += new EventHandler(Timer1_Tick); // Enable timer. Timer1.Enabled = true; Button1.Text = "Stop"; Button1.Click += new EventHandler(Button1_Click); } private void Timer1_Tick(object Sender, EventArgs e) { // Set the caption to the current time. Label1.Text = DateTime.Now.ToString(); } private void Button1_Click(object sender, EventArgs e) { if ( Button1.Text == "Stop" ) { Button1.Text = "Start"; Timer1.Enabled = false; } else { Button1.Text = "Stop"; Timer1.Enabled = true; } } ``` -------------------------------- ### DataGridView Data Validation Example Source: https://learn.microsoft.com/en-us/dotnet/desktop/winforms/controls/how-to-validate-data-in-the-windows-forms-datagridview-control This VB.NET code demonstrates how to validate data in a DataGridView control. It specifically prevents empty values in the 'CompanyName' column by handling the CellValidating event and displaying an error message. It also includes setup for data binding and database connection. ```vb.net Imports System.Data Imports System.Data.SqlClient Imports System.Windows.Forms Public Class Form1 Inherits System.Windows.Forms.Form Private WithEvents dataGridView1 As New DataGridView() Private bindingSource1 As New BindingSource() Public Sub New() ' Initialize the form. Me.dataGridView1.Dock = DockStyle.Fill Me.Controls.Add(dataGridView1) Me.Text = "DataGridView validation demo (disallows empty CompanyName)" End Sub Private Sub Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Me.Load ' Initialize the BindingSource and bind the DataGridView to it. bindingSource1.DataSource = GetData("select * from Customers") Me.dataGridView1.DataSource = bindingSource1 Me.dataGridView1.AutoResizeColumns( _ DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader) End Sub Private Sub dataGridView1_CellValidating(ByVal sender As Object, _ ByVal e As DataGridViewCellValidatingEventArgs) _ Handles dataGridView1.CellValidating Dim headerText As String = _ dataGridView1.Columns(e.ColumnIndex).HeaderText ' Abort validation if cell is not in the CompanyName column. If Not headerText.Equals("CompanyName") Then Return ' Confirm that the cell is not empty. If (String.IsNullOrEmpty(e.FormattedValue.ToString())) Then dataGridView1.Rows(e.RowIndex).ErrorText = _ "Company Name must not be empty" e.Cancel = True End If End Sub Private Sub dataGridView1_CellEndEdit(ByVal sender As Object, _ ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) _ Handles dataGridView1.CellEndEdit ' Clear the row error in case the user presses ESC. dataGridView1.Rows(e.RowIndex).ErrorText = String.Empty End Sub Private Shared Function GetData(ByVal selectCommand As String) As DataTable Dim connectionString As String = _ "Integrated Security=SSPI;Persist Security Info=False;" + "Initial Catalog=Northwind;Data Source=localhost;Packet Size=4096" ' Connect to the database and fill a data table. Dim adapter As New SqlDataAdapter(selectCommand, connectionString) Dim data As New DataTable() data.Locale = System.Globalization.CultureInfo.InvariantCulture adapter.Fill(data) Return data End Function _ Shared Sub Main() Application.EnableVisualStyles() Application.Run(New Form1()) End Sub End Class ``` -------------------------------- ### Initialize MainForm and Load Data Source: https://learn.microsoft.com/en-us/dotnet/desktop/winforms/controls/how-to-share-bound-data-across-forms-using-the-bindingsource-component Sets up the main form, initializes a BindingSource, creates a DataSet, and populates it with XML data. It then creates a DataView from the DataSet's table. ```vbnet Imports System.Drawing Imports System.Windows.Forms Imports System.Data Public Class MainForm Inherits Form Public Sub New() End Sub Private WithEvents bindingSource1 As BindingSource Private WithEvents button1 As Button Private Sub MainForm_Load(ByVal sender As Object, ByVal e As EventArgs) _ Handles Me.Load InitializeData() End Sub Private Sub InitializeData() bindingSource1 = New System.Windows.Forms.BindingSource() Dim dataset1 As New DataSet() ClientSize = New System.Drawing.Size(292, 266) ' Some xml data to populate the DataSet with. ' Some xml data to populate the DataSet with. Dim musicXml As String = "" & _ "Dave Matthews" & _ "Under the Table and Dreaming" & _ "19943.5" & _ "ColdplayX&Y" & _ "20054" & _ "Dave Matthews" & _ "Live at Red Rocks" & _ "19974" & _ "U2" & _ "Joshua Tree1987" & _ "5" & _ "U2" & _ "How to Dismantle an Atomic Bomb" & _ "20044.5" & _ "Natalie Merchant" & _ "Tigerlily1995" & _ "3.5" & _ "" ' Read the xml. Dim reader As New System.IO.StringReader(musicXml) dataset1.ReadXml(reader) ' Get a DataView of the table contained in the dataset. Dim tables As DataTableCollection = dataset1.Tables Dim view1 As New DataView(tables(0)) ```