当前位置:网站首页>WinForm (II) advanced WinForm and use of complex controls
WinForm (II) advanced WinForm and use of complex controls
2022-06-11 05:11:00 【Aaaaan】
One . Composite controls
1. Overview of the use of controls : stay WinForm Controls used in mainly include the following situations
(1) Standard controls : Use it directly winform Built in controls , such as button、textBox etc. . We just need to modify the properties , Add an event .
(2) Composite controls : Combine some standard controls , Realize complex functions . Need to define class YourControl:UserControl{ }
(3) Extended controls : Expand or change the functions of some standard controls . Need to inherit from standard controls ,class YourButton:Button { }
(4) Custom control : Completely customize a control , Defining attributes 、 Method 、 Patterns, etc . Need to inherit from Control(Control Is the base class for all controls ),class YourControl:Control { }
* Be careful : We learned about the use of standard controls , So in this lesson, we will learn how to define and use composite controls , Step by step .
2. Composite controls : Implement a search box control ( Combine text box and picture box )
(1) Definition : Composite controls are also called user controls , It is specially used to combine standard controls , It is inherited from UserControl
(2) Define composite controls :
- Right click solution -> add to User control form (UserControl), Name it SearchBox. It will automatically generate a SearchBox class , Inherited from UserControl
- double-click SearchBox.cs file , You can open the design interface , Design the style that conforms to the component like a window
a. Drag one up textBox Text box as search box
b. Drag a picture box , Set image as search icon
c. Use table layout , Combine the two , And adjust the size and position (Anchor、Dock、 Table scale, etc )
d. After the save , Rebuild the solution , Then click the toolbox in the interface to see our own composite control
(3) Placement and principle of composite control
- You can directly drag and drop the matching control in the interface , And the composite control as a whole also has Size、Location、 Events and so on .
- A composite control is essentially a form ! The components in a composite control are the same as those in a form , Placed on the form during initialization .
1. Composite controls SearchBox Visual design
stay SearchBox.cs Form design interface , Visual style design for composite controls , The steps are as follows :
- Add one TableLayoutPanel Table layout container , Keep one row and two columns . And set its Dock by Fill Fill the entire parent window , Then set the size ratio of the two columns of the table to 7:3.( Buttons for placing text boxes and picture boxes )
- Add one TextBox To the first cell , And set its Anchor Fixed for left and right margins ( You can stretch as the parent window stretches )
- Add one pictureBox To the second cell , And set its Dock by Fill Fill the cells , Add image resources - Search icon
Be careful : Now it's just designed SearchBox The style of , But its property access and event handling have not been designed yet , For example, how to get the value of a text box for a composite control ? How to get / Set the click event of the picture box ? How to use a composite control as a whole ?

2. Property access and event handling of composite controls
3. Composite control access and event handling : Sometimes we need to get the data of the child controls in the composite control 、 Or give a location to the composite control ( picture 、 Button ) Set up events
(1) Set up public Direct access ( The most simple , The most direct , The least commonly used ): Set all child control members in the composite control to public, Just visit directly
- Select each child control in the composite control design interface , Set up Modifiers The attribute is public ( The default is private)
- Then in the source code of the composite control , The related child controls will automatically become public Access decorated , We can use it directly [ Composite controls . Child controls . attribute ] To visit
- to SearchBox Set the click event for the search image :searchBox1.pictureBox1.Click += new EventHandler(searchEvent);
- Get text box search content :MessageBox.Show(" Begin your search ..." + searchBox1.textBox1.Text);
(2) Set events and get data in the composite control , You can use the sub components directly like a window ( Never tried. )
(3) Composite control custom properties
- Add attribute :
a. stay SearchBox In logic code , Add a property accessorpublic string SearchText { get { return this.textBox1.Text; } set { this.textBox1.Text = value; } }b. Rebuild the solution , open Form3 Interface design , stay miscellaneous You can see us Custom properties SearchText. By modifying the value, you can directly modify the internal TextBox. Its essence is to call set、get Method .
- Overridden properties :
a. stay SearchBox In logic code , rewrite UserControl Existing properties , such as Text etc.public override string Text { get { return this.textBox1.Text; } set { this.textBox1.Text = value; } }b. Rebuild the solution , open Form3 Interface design , The original property becomes the property we rewrite .
- C# Attribute characteristic : A feature is a declarative tag that can be recognized by the compiler , Be similar to Java Annotations
a. grammar :[attribute(positional_parameters, name_parameter = value, ...)]
b. Common features :
[Browsable(true)]: Whether the control property is visible in the designer ( The general default is false)
[Category("Appearance")]: Control properties are displayed in which category .Action( Related to available operations )、Appearance( Related to the appearance of the entity )、Behavior( Related to the behavior of entities )、Data( Related to data and data source management )
[DesignerSerializationVisibility()]: Persist the values we set on the control properties into the code , So the next time we check the value of the control is still the last value we set . Indicates whether and how a property is serialized , Its value is an enumeration , There are three types Content,Hidden,Visible.
(4) Composite control custom events
- stay SearchBox In logic code , Add declaration custom event . public event EventHandler SearchEvent;
- After rebuilding the solution , Can be in event - miscellaneous See us in Custom events SearchEvent
- Events can be added in the design interface / Implement the callback method onSearch(), Serve with custom attributes
- In composite components , The click event of the picture link to Custom events , That is, the user-defined event will be triggered when the image is clicked . Writing pictures Click event//PictureBox Click events for -> Trigger custom event SearchEvent The callback method private void onClick(object sender, EventArgs e) { // Call event , Fixed writing if(SearchEvent != null) { SearchEvent.Invoke(this, e); } // Simplify writing SearchEvent?.Invoke(this,e); }* Be careful : A control can also add multiple events , Sequential trigger
(1) Interface design

(2)SearchBox.cs Logic code
namespace WindowsFormsApp_learning
{
public partial class SearchBox : UserControl
{
// Add custom events
public event EventHandler SearchEvent;
public SearchBox()
{
// Initialize control (TextBox+PictureBox)
InitializeComponent();
}
/**
* Add a new custom attribute SearchText
*/
public string SearchText
{
get
{
return this.textBox1.Text;
}
set
{
this.textBox1.Text = value;
}
}
/**
* Overridden properties Text
*/
[Browsable(true)]
public override string Text {
get
{
return this.textBox1.Text;
}
set
{
this.textBox1.Text = value;
}
}
// Picture click event onClick -> Link custom events SearchEvent
// Be careful :SearchEvent Event handling method of , Need to be in Form.cs Just add it in the same way as the event handling of the basic control
private void onClick(object sender, EventArgs e)
{
// Call event , Fixed writing
if(SearchEvent != null)
{
SearchEvent.Invoke(this, e);
}
// Simplify writing SearchEvent?.Invoke(this,e);
}
}
}
(3)Form3.cs Main form logic code
namespace WindowsFormsApp_learning
{
public partial class Form3 : Form
{
public Form3()
{
InitializeComponent();
// Set the composite control Click event of picture (public The way )
//searchBox1.pictureBox1.Click += new EventHandler(searchEvent);
}
//public Method to set the composite control - Child control click event
private void searchEvent(object sender,EventArgs args)
{
// Get and show The content of the text box
MessageBox.Show(" Begin your search ..." + searchBox1.textBox1.Text);
}
//SearchBox Custom event implementation for SearchEvent -> onSearch
private void onSearch(object sender, EventArgs e)
{
// Get and show The content of the text box ( Through custom properties / Overridden properties )
MessageBox.Show(" Begin your search ..." + searchBox1.SearchText);
}
}
}

Two . Control wrapper
1. Control packaging basic design
1. Control wrapper :
(1) Definition : Control wrapper is a special form of composite control , There is only one control inside
(2) Purpose : Expand and customize the functions of some basic controls , such as TextBox The height and inner margin can be modified after packaging padding etc.
(3) step :
- New wrapper control class AfTextBox, Inherited from UserControl, Only one is placed inside TextBox Components , As a pair of TextBox Packaging expansion
- To achieve modifiable TextBox The effect of height and width , Need to set up TextBox Of Size With the outside Form Change by change -> onLayout()
- To achieve modifiable TextBox padding padding The effect of , Need to set up Form And TextBox Instead of the inner margin of the text -> onLayout()
- To achieve this effect seamlessly , It looks like a TextBox whole , Need to set up TextBox and Form Same background color , And cancel TextBox Frame .
2.Location Attribute interpretation : The upper left corner of the control be relative to The coordinates of the upper left corner of the container , Unit is pixel .
(1) For forms , Is the coordinate of the upper left corner of the window relative to the upper left corner of the screen ;
(2) For general controls , Is the coordinate of the upper left corner of the control relative to the upper left corner of its container , For example, relative to the form , Picture box, etc .
(3) The upper left corner of the parent container defaults to (0,0)
3. Window position adjustment :
- this.StartPosition = FormStartPosition.Manual; // The position of the form is determined by Location Attribute decision
- this.StartPosition = FormStartPosition.CenterParent; // The form is centered in its parent form
- this.StartPosition = FormStartPosition.CenterScreen; // The form is centered in the currently displayed window , The size is specified in the form size
- this.StartPosition = FormStartPosition.WindowsDefaultBounds; // The form is positioned in windows Default location , The boundary is also defined by windows Default decision ( Default )
- this.StartPosition = FormStartPosition.WindowsDefaultLocation; // The form is positioned in windows Default location , The size is specified in the form size
(1)TextBox Wrap control AfTextBox Logic code
namespace WindowsFormsApp_learning
{
public partial class AfTextBox : UserControl
{
public AfTextBox()
{
// Initialize internal controls
InitializeComponent();
}
// Rewrite the layout implementation
protected override void OnLayout(LayoutEventArgs levent)
{
base.OnLayout(levent);
//1. Get child control
if (this.Controls.Count == 0) return;
Control C = this.Controls[0];
//2. Get parent window parameters
Padding p = this.Padding;// The margin of the parent window Padding
int x = 0, y = 0;// The initial coordinates of the child control relative to the container ( top left corner )
int w = this.Width, h = this.Height;
w -= (p.Left + p.Right);//TextBox Width = Container width - Left and right margins
x += p.Left;//TextBox Relative x = p.Left
//3. Calculate the height of the text box , Make it appear in the middle
// (1)PreferredSize: Gets the size of the rectangular area that can hold the control .
// (2)Size: Get the size of the control
int h2 = C.PreferredSize.Height;
if (h2 > h) h2 = h;
y = (h - h2) / 2;//TextBox Relative y = (h-h2)/2 The height is in the middle
//4. Set the position and size of child controls
C.Location = new Point(x, y);
C.Size = new Size(w, h2);
//5. Why not resize the height : Text box is single line , Height adjustment is invalid . It will only change with the size of the text format !
}
}
}
2. Control packing list file development
2. packing 、 Compound control single file development
(1) Definition : Each creation UserControl Will automatically create a corresponding designer.cs Layout design documents , Develop interface and logic separately . How to combine the two into one file development ?
(2) step :
- 【 Manual 】 establish AfTextBox2 General class class file , And manually inherit UserControl
- Double-click to open AfTextBox2.cs You can enter the design interface , Drag and drop controls . Meeting direct to AfTextBox2.cs Add control layout automatically in ( Will not be added separately )
- Manually implement the constructor , Initialize call layout InitializeComponent()
- Add logic code and events 、 attribute
(3) benefits : In the future, a single control can be directly cs Copy files to other projects for direct use , It doesn't need to be divided into several3. Wrap the custom properties and events of the control : Just like composite controls (AfTextBox2 For example )
(1) add to / Override custom properties Text、BackColor、Front
(2) Add custom events ReturnPressed( Carriage return incident )
(1)AfTextBox2 Wrap control cs Logic code
namespace WindowsFormsApp_learning
{
class AfTextBox2 : UserControl
{
/**
* Automatically generate layout code , Add directly to this document
*/
private TextBox edit;
private void InitializeComponent()
{
this.edit = new System.Windows.Forms.TextBox();
this.SuspendLayout();
//
// edit
//
this.edit.BorderStyle = System.Windows.Forms.BorderStyle.None;
//this.edit.Font = new System.Drawing.Font(" Song style ", 16F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.edit.Location = new System.Drawing.Point(106, 79);
this.edit.Name = "edit";
this.edit.Size = new System.Drawing.Size(263, 37);
this.edit.TabIndex = 0;
this.edit.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.OnPress);
//
// AfTextBox2
//
this.BackColor = System.Drawing.Color.White;
this.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.Controls.Add(this.edit);
this.Name = "AfTextBox2";
this.Size = new System.Drawing.Size(524, 246);
this.ResumeLayout(false);
this.PerformLayout();
}
/**
* Add constructors manually , Initialize layout
*/
public AfTextBox2()
{
InitializeComponent();
}
/**
* Add logic code , Implement component adaptation
*/
protected override void OnLayout(LayoutEventArgs levent)
{
base.OnLayout(levent);
//1. Get child control
if (this.Controls.Count == 0) return;
Control C = this.Controls[0];
//2. Get parent window parameters
Padding p = this.Padding;// The margin of the parent window Padding
int x = 0, y = 0;// The initial coordinates of the child control relative to the container ( top left corner )
int w = this.Width, h = this.Height;
w -= (p.Left + p.Right);//TextBox Width = Container width - Left and right margins
x += p.Left;//TextBox Relative x = p.Left
//3. Calculate the height of the text box , Make it appear in the middle
// (1)PreferredSize: Gets the size of the rectangular area that can hold the control .
// (2)Size: Get the size of the control
int h2 = C.PreferredSize.Height;
if (h2 > h) h2 = h;
y = (h - h2) / 2;//TextBox Relative y = (h-h2)/2 The height is in the middle
//4. Set the position and size of child controls
C.Location = new Point(x, y);
C.Size = new Size(w, h2);
//5. Why not resize the height : Text box is single line , Height adjustment is invalid . It will only change with the size of the text format !
}
/**
* Override custom properties Text
* Browsable:True The attribute is displayed in the design interface and can be modified ,False The attribute is not displayed in the design interface . The default is True
* DesignerSerializationVisibility: Set the serialization mode of the attribute , The default is Visible
*/
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public override string Text {
get
{
return edit.Text;
}
set
{
edit.Text = value;
}
}
// Override custom properties Color
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public override Color BackColor
{
get
{
return edit.BackColor;
}
set
{
// Container and TextBox The color changes as a whole
base.BackColor = value;
edit.BackColor = value;
}
}
/**
* Be careful :Font There are some special settings for , You need to provide an initial default value
* ** This is still unresolved , Can't modify Font typeface **
*/
private Font initFont = new Font(" Song style ", 10f);
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public override Font Font
{
get
{
return initFont;
}
set
{
this.initFont = value;
this.edit.Font = value;
}
}
/**
* Add custom events
*/
public event EventHandler ReturnPressed;
//TextBox Of keyPress -> Trigger ReturnPressed event
private void OnPress(object sender, KeyPressEventArgs e)
{
char ch = e.KeyChar;
if (ch == '\r')// If it is a carriage return symbol
{
// Callback ReturnPressed event
ReturnPressed?.Invoke(this, e);
}
}
}
}
(2)Form Form application

namespace WindowsFormsApp_learning
{
public partial class Form4 : Form
{
public Form4()
{
InitializeComponent();
}
// Wrapping the control ReturnPressed Carriage return triggers events
private void OnEnterPress(object sender, EventArgs e)
{
MessageBox.Show(" Retrieving ..." + afTextBox21.Font);
}
}
}
3、 ... and . Dialog box
1. Basic concepts of dialog box
1. Dialog box
(1) structure : The dialog box is still a Form forms , It is only displayed in the form of a dialog box . So the construction of the dialog box can refer to the design of the form
(2) Use : Create a new dialog box MyDiglog , Display the dialog box in the click event ShowDialog()
MyDialog dialog = new MyDialog(); // New form
dialog.ShowDialog(); // As a dialog box, it pops up in the current interface . Notice if it is Show() Is the display form , Non dialog
dialog.Dispose(); // Destroy form , Release resources
(3) Operation process :
- Calling ShowDialog After the method , Meeting [ Blocking ] Parent window process , No further execution . It shows that the child window can be active , But the parent window can't
- The dialog box blocks until the user closes the dialog box , The parent window process continues to execute downward
- perform Dispose Method to release dialog resources
(4) Dialog properties ( And forms Form Same property ):
- Text: The upper left corner of the form displays text
- MaximizeBox: Maximize button (True Show ,Flase No display )
- MinimizeBox: Minimize button (True Show ,Flase No display )、
- ShowInTaskBar: Whether to display... In the taskbar
- StartPosition: Form display position WindowsDefaultLocation Default window location 、CenterSceen In the middle of the window 、CenterParent The center of the parent window, etc
- FormBorderStyle: Border style Sizable Modifiable 、FixedDialog Fixed dialog size 、FixedSignle Fixed form
(5) Dialog box return value and data transfer
- The dialog box contains properties DialogResult
DialogResult.OK : Set up DialogResult by OK, The form closes immediately , And back to DialogResult.OK value
DialogResult.Cancel: Set up DialogResult by Cancel, The form closes immediately , And back to DialogResult.Cancel value
- Data transfer : You can set the pass data component to public, stay After closing the window Dispose Before call dialog.xxx To get the property value
(1) Dialog interface design

(2) Dialog logic code (MyDialog.cs)
namespace WindowsFormsApp_learning
{
public partial class MyDialog : Form
{
public MyDialog()
{
InitializeComponent();
}
// Dialog box confirmation button
private void OnClickOk(object sender, EventArgs e)
{
// Close the current dialog box , And back to OK
this.DialogResult = DialogResult.OK;
}
// Dialog cancel button
private void OnClickCancel(object sender, EventArgs e)
{
// Close the current dialog box , And back to Cancel
this.DialogResult = DialogResult.Cancel;
}
}
}
(3)Form Form logic code
1. Two functions :
- By clicking the button , Create and present dialog boxes
- Get the dialog box return value , And displayed on the main window interface

namespace WindowsFormsApp_learning
{
public partial class Form5 : Form
{
public Form5()
{
InitializeComponent();
}
// Click button , Trigger dialog display event
private void show_Dialog(object sender, EventArgs e)
{
MyDialog dialog = new MyDialog(); // New form
DialogResult res = dialog.ShowDialog(); // As a dialog box, it pops up in the current interface
// Block the current process , Until the user closes the dialog
if(res == DialogResult.OK)// Indicates that the window closed by clicking the OK button
{
// get data , Displayed in the parent interface
this.textPanel.Text += (dialog.dlg_text.Text + "\r\n");
}
dialog.Dispose(); // Destroy form , Release resources
}
}
}
2. shortcuts + Default behavior :
- Dialog button quick close : The button has a DialogResult attribute :OK、Cancel And so on can be set . The effect is the same as handwritten code , Close the dialog box and return the value
- Dialog box AcceptButton attribute : When you click... In the dialog box enter Button that will be triggered when , The default is None
- Dialog box CancelButton attribute : When you click... In the dialog box ESC Button that will be triggered when , The default is None
2. Dialog box exercises : Font setter
It is required to implement a text input device , You can click the button to pop up the font setting dialog box , To select the appropriate font and size . After confirmation, change the text input of the main window to the corresponding font style .
(1) Main window interface design

(2) Dialog interface design

(3) Dialog logic code StyleDialog.cs
namespace WindowsFormsApp_Demo2
{
public partial class StyleDialog : Form
{
public StyleDialog()
{
InitializeComponent();
}
// Get the selected font type public
public string FontType
{
get
{
return (string)this.dlg_wordType.SelectedItem;
}
set
{
this.dlg_wordType.SelectedItem = value;
}
}
// Get the selected font size public
public int FontSize
{
get
{
return (int)this.dlg_wordSize.Value;
}
set
{
this.dlg_wordSize.Value = value;
}
}
// Button click event : Return value
private void onClickOk(object sender, EventArgs e)
{
this.DialogResult = DialogResult.OK;
}
private void onClickCancel(object sender, EventArgs e)
{
this.DialogResult = DialogResult.Cancel;
}
}
}
(4) Main form logic code Form1.cs
namespace WindowsFormsApp_Demo2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
// Set button click event : Pop-up dialog box , And get the return value
private void onClickStyle(object sender, EventArgs e)
{
StyleDialog dlg = new StyleDialog();
DialogResult res = dlg.ShowDialog();
if(res == DialogResult.OK)
{
// Get the return value , Sets the current font style
string fontType = dlg.FontType;
int fontSize = dlg.FontSize;
this.text_panel.Font = new Font(fontType, fontSize);
}
dlg.Dispose();
}
}
}
Four . System dialog
1. System dialog :WinForm Provides many built-in system dialog boxes , Such as file browsing 、 preservation , Color 、 Font selection, etc .
(1)OpenFileDialog : File open dialog
- new OpenFileDialog(): New dialog
- InitialDirectory: Set the initial display path for opening
- DefaultExt: Gets or sets the default displayed file extension .
- Filter: Gets or sets the current file name filter string . The format for " Custom string labels | Type list "
a. Single file type : picture |*.jpg,*.png,*.gif
b. Multiple file types : picture |*.jpg,*.png,*.gif| Text |*.txt,*.doc| all |*.*
- FileName: Gets or sets the file name string selected in the dialog box
- FileNames: Gets or sets the list of all selected file name strings in the dialog box
(2)SaveFileDialog : File Save dialog ( Follow OpenFileDialog almost )
(3)FolderBrowserDialog: Folder selection dialog
- new FolderBrowserDialog(): New dialog
- InitialDirectory: Gets or sets the initial path to open
- SelectedPath: Gets or sets the selected folder path
(4)ColorDialog: Color selection dialog
(5)FontDialog: Font selection dialog box
1. The system dialog function uses
To show the functions of the system dialog box , A file browsing window is designed here , Be able to choose 、 Save file or folder , And the selected file / The directory path name is displayed in the text box of the main interface .
(1) Interface design

(2)Form.cs Logic code
namespace WindowsFormsApp_learning
{
public partial class Form6 : Form
{
public Form6()
{
InitializeComponent();
}
// Select the file button Click event
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog fileDialog = new OpenFileDialog(); // New file dialog box
fileDialog.InitialDirectory = "D:\\ Daily materials \\ Learning materials \\WinForm\\ Chapter 12 System dialog \\12.1 System dialog \\ Project source code \\FormApp1201\\FormApp1201"; // Set the initial path
//fileDialog.SelectedPath = Path.GetFullPath(".");
fileDialog.DefaultExt = ".cs"; // Screening display .cs Suffix file
fileDialog.Filter = " Code |*.cs;*.config"; // Set file selector
if (fileDialog.ShowDialog() == DialogResult.OK)
{
// Get and set the file path name to the main form
string fileName = fileDialog.FileName;
this.textBox1.Text = fileName;
}
}
// Save file button Click event
private void button2_Click(object sender, EventArgs e)
{
SaveFileDialog dlg = new SaveFileDialog();
dlg.FileName = " New text file ";
dlg.DefaultExt = ".txt";
dlg.Filter = " Text |*.txt;*.doc";
if (dlg.ShowDialog() == DialogResult.OK)
{
string fileName = dlg.FileName;
this.textBox1.Text = fileName;
}
}
// Select the folder button Click event
private void button3_Click(object sender, EventArgs e)
{
FolderBrowserDialog dlg = new FolderBrowserDialog();
dlg.SelectedPath = Path.GetFullPath(".");// Returns the absolute path string of the current folder
if (dlg.ShowDialog() == DialogResult.OK)
{
string path = dlg.SelectedPath;
this.textBox1.Text = path;
}
}
}
}

2. System dialog exercise - Picture viewer
Design a picture viewer window , You can select the browse directory path in the main form , After selection, load all the picture names in this directory into the list bar on the left side of the main window , By clicking the picture name in the list bar, the user can switch to display the corresponding picture in the picture display area on the right side of the main window .
(1) Interface design
A custom text box is used in the main form AfTextBox, You can stretch freely . At the same time, a browse button is placed on the right side , You can open the file directory browsing window . The main form also includes a list box , Used to display a list of picture names ; In addition, there is a picture box , Used to display the specified path picture .

(2) Custom dialog AfTextBox Single file development
namespace WindowsFormsApp_Demo
{
class AfTextBox:UserControl
{
private TextBox edit;
private void InitializeComponent()
{
this.edit = new System.Windows.Forms.TextBox();
this.SuspendLayout();
//
// edit
//
this.edit.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.edit.Font = new System.Drawing.Font(" Song style ", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.edit.Location = new System.Drawing.Point(52, 52);
this.edit.Name = "edit";
this.edit.Size = new System.Drawing.Size(89, 19);
this.edit.TabIndex = 0;
this.edit.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.onTextPressed);
//
// AfTextBox
//
this.BackColor = System.Drawing.Color.White;
this.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.Controls.Add(this.edit);
this.Name = "AfTextBox";
this.Size = new System.Drawing.Size(199, 105);
this.ResumeLayout(false);
this.PerformLayout();
}
public AfTextBox()
{
InitializeComponent();
}
protected override void OnLayout(LayoutEventArgs e)
{
base.OnLayout(e);
if (this.Controls.Count == 0) return;
Control c = this.Controls[0];
int w = this.Width, h = this.Height;
int x = 0, y = 0;
int left = this.Padding.Left, right = this.Padding.Right;
w -= (left + right);
x += left;
//PreferredSize Get the size of the control rectangle container box
// The reason is that the text box is single line input , Can't adjust the height ! But the outer rectangular container can
int h2 = c.PreferredSize.Height;
if (h2 > h) h2 = h;
y += (h - h2) / 2;
c.Location = new Point(x, y);
c.Size = new Size(w, h2);
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public override string Text {
set
{
this.edit.Text = value;
}
get
{
return this.edit.Text;
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public override Color BackColor
{
get
{
return this.edit.BackColor;
}
set
{
this.edit.BackColor = value;
// Here is base!!!! No this!!!
base.BackColor = value;
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public override Color ForeColor
{
get
{
return edit.ForeColor;
}
set
{
edit.ForeColor = value;
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public bool ReadOnly
{
get
{
return this.edit.ReadOnly;
}
set
{
this.edit.ReadOnly = value;
}
}
public event EventHandler ReturnPressed;
private void onTextPressed(object sender, KeyPressEventArgs e)
{
char ch = e.KeyChar;
if (ch == '\r')
{
ReturnPressed?.Invoke(this, e);
}
}
}
}(3) Main form Form.cs Logic code
namespace WindowsFormsApp_Demo
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
// Browse button Click event
private void onScanClick(object sender, EventArgs e)
{
FolderBrowserDialog dlg = new FolderBrowserDialog();
if(dlg.ShowDialog() == DialogResult.OK)
{
string path = dlg.SelectedPath;
this.afTextbox.Text = path;
// Load picture list
ShowPictureList(path);
}
}
private void ShowPictureList(string dir)
{
// Clear display
listFile.Items.Clear();
// Traverse all the files , Check the file name suffix
string[] files = Directory.GetFiles(dir);
foreach(string f in files)
{
if (f.EndsWith(".jpg") || f.EndsWith(".png") || f.EndsWith(".jpeg"))
{
// Get the file name
PictureListItem item = new PictureListItem();
item.name = Path.GetFileName(f);
item.filePath = f;
//Console.WriteLine("name:" + f + ",path:" + item.filePath);
// Add to the list box to display
this.listFile.Items.Add(item);
}
}
// By default, the first file is opened to display ( Manual SetSelect It will also trigger IndexChanged event )
if (listFile.Items.Count > 0)
listFile.SetSelected(0, true);
}
private void listFile_SelectedIndexChanged(object sender, EventArgs e)
{
PictureListItem item = (PictureListItem)listFile.SelectedItem;
if (item == null) return;
// Loading pictures
pathPic.Load(item.filePath);
}
}
// Document item
class PictureListItem
{
public string name;
public string filePath;
public override string ToString()
{
return name;
}
}
}5、 ... and . Menu bar and toolbar
1. menu bar MenuStrip: Dock the menu bar at the top of the window
(1) Use : Visual design of design interface , You can add menu items 、 A drop-down box 、 Split line 、 Text
(2) attribute : Every Item All can be set ID、Text、Image( Icon )、 Click event Click
2. The toolbar ToolStrip: Docked toolbar at the top of the window , It is usually located below the menu bar ( Icon bar )
(1) Use : Visual design of design interface , You can add tool buttons 、 Dividing line, etc . The first row above the general window is the menu bar , The second row is the toolbar , The two correspond
(2) attribute : Every Item All can be set ID、Image( Icon )、 Click event Click etc.
(3) Development skills : Toolbars and menu bars generally have corresponding relationships , Each menu has a corresponding tool icon button , Both click callback events can be shared . Click the drop-down arrow in the event -> Select the event set in the menu bar
3. Right-click menu ( Context menu ): ContextMenuStrip
(1) Definition : In different parts of the window Right click to display The menu bar should have different options , Menu bars and toolbars in general projects may not have , But the right-click menu must have !
(2) Use :
- Add... To the design interface ContextMenuStrip Context menu , And add menu items . But at this time, only the context menu is defined and declared , Right click can not display
- Set the mouse click event of the interface or control MouseUp/MouseDown, Show menu in event ContextMenuStrip.show( Show controls , Show location )
- further , We hope that listBox in , Right click item Show edit and delete , And the blank position of the right button only shows add , Just in line with our logic ( Different logic shows different right-click menu contents )
- Set menu item click event
(1) Interface design

(2)Form.cs Logic code
namespace WindowsFormsApp_learning
{
public partial class Form5 : Form
{
public Form5()
{
InitializeComponent();
}
// The toolbar Item Click event
private void open ToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show(" Click to open ...");
}
//listBox List control Click event
private void listBox1_MouseDown(object sender, MouseEventArgs e)
{
// If you right-click , Right click menu is triggered
if(e.Button == MouseButtons.Right)
{
//IndexFromPoint: Returns the first... From the specified location Item Indexes
//e.Location: Where the mouse clicks Point
int index = listBox1.IndexFromPoint(e.Location);
// If index>=0, It means that you right clicked a Item Item instead of a blank space
if (index >= 0)
{
// To display the / Allow to choose edit / Delete the item
listBox1.SetSelected(index, true);// Select the
Item_Edit.Enabled = true;// The right-click menu item setting allows you to click
Item_Del.Enabled = true;
}
else
{
// Clear selection , No display / Disable editing / Delete
listBox1.ClearSelected();// Empty
Item_Edit.Enabled = false;// Ban
Item_Del.Enabled = false;
//Item_Edit.Visible = false;// Do not display this item directly
//Item_Del.Visible = false;
}
this.contextMenu.Show(listBox1, e.Location);// Show the right-click menu
}
}
// Right click menu item [ add to ] Click event
private void Item_Add_Click(object sender, EventArgs e)
{
MessageBox.Show(" Context menu : Add selected ...");
}
}
}6、 ... and . List view control ListView
1.ListView Basic use
1. List control ListView: Upgraded version ListBox, The display is similar to windows Folder view of
(1) characteristic : The list display mode can be switched ( details 、 Large icon 、 Small icons ), Multiple fields can be displayed , You can set the icon 、 Tags can be edited , Each column can be sorted , You can customize the design
(2) Control basic properties :View( display mode )、Columns( aggregate , Column header name )、Items( aggregate , Items in the list )、Items.SubTetms( aggregate , Children of each item in the list - Data displayed in other columns )、LabelEdit( Whether to allow users to edit labels in place )、LargeImageList( Large icon list )、SmallImageList( Small icon list )、Sorting( sort order ) etc.
(3) Simple steps :
- In the design interface ListView Drag in , And set up Dock Is full ( Next, you can perform visual design in the design interface , You can also add design data items through code )
- Code design ListView( recommend ):
a. Set display mode
b. Set column name
c. Add data items
d. Set the sub item data of each data item
- The reason why it is recommended to add data in code mode : Many times we don't know how many items to traverse , So we can't design it in advance . Can only be added dynamically through code
(1)ListView Basic usage shows
The interface design is very simple , Is to drag in a ListView Control , And set up Dock by Fill Fill the parent container , No other controls , The design interface will not be shown here . The basic usage mainly shows how to ListView Add column names in code mode 、 Data items, etc .
namespace WindowsFormsApp_learning2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
// initialization ListView Control
InitializeListView();
}
private void InitializeListView()
{
//1. Set the display mode to detail mode : Show icons + The main item + All children
listView1.View = View.Details;
// Set the entire line to check ( When selecting an item, select the whole line , Not just the main item )
listView1.FullRowSelect = true;
//2. Set column name Add( Name , Width [ Pixel values ], Alignment mode )
// Width value -2 Indicates automatic width adjustment
listView1.Columns.Add(" file name ",-2,HorizontalAlignment.Left);
listView1.Columns.Add(" Revision period ", 150, HorizontalAlignment.Left);
listView1.Columns.Add(" type ", 100, HorizontalAlignment.Left);
listView1.Columns.Add(" size ", -2, HorizontalAlignment.Left);
//3. Add data items ListViewItem( Data name , Icon subscript )
ListViewItem item1 = new ListViewItem("Java Learning Guide .pdf", 0);
//4. Set sub item data ( Data corresponding to each column )
item1.SubItems.Add("2020-2-20 12:10");
item1.SubItems.Add("PDF");
item1.SubItems.Add("192 KB");
listView1.Items.Add(item1);
}
}
}

(2)ListView Basic use of small exercises : The list of local file directories is displayed
2.ListView Control advanced use : Local file visualization
(1) In the design interface , take ListView Control drag in , And set up Dock For filling Fill
(2) Add image resources of data item icons to Resources
(3) Initialize in code ListView Basic configuration , Include column names 、 display mode 、 Icon list, etc . InitListView()
namespace WindowsFormsApp_learning2
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
// initialization ListView Control
InitListView();
// Load add file data item
LoadDir(new DirectoryInfo("D:\\"));
}
//1. initialization ListView Control
private void InitListView()
{
// Set the display mode to detail mode
listView1.View = View.Details;
// Set the entire line to check
listView1.FullRowSelect = true;
// Set column name
listView1.Columns.Add(" name ", -2, HorizontalAlignment.Left);
listView1.Columns.Add(" Modification time ", 150, HorizontalAlignment.Left);
listView1.Columns.Add(" type ", 100, HorizontalAlignment.Left);
listView1.Columns.Add(" size ", -2, HorizontalAlignment.Left);
// establish ImageList( Provide some ways , To manage some list classes of image resources ), And add 2 A little icon
ImageList imgList = new ImageList();
imgList.ImageSize = new Size(16, 16);// Set the size of the pictures in the list
imgList.Images.Add(Properties.Resources.Icon_file);// Added in advance to Resources The icon
imgList.Images.Add(Properties.Resources.Icon_folder);
// Set up SmallImageList Used to display small icons ( For small icons 、 details 、 List mode displays icons )
// Set up LargeImageList Used to display large icons ( Suitable for displaying icons in large icon mode )
listView1.SmallImageList = imgList;
}
//2. Traverse local resources , Get a file or directory
private void LoadDir(DirectoryInfo dir)
{
// Load optimization :BeginUpdate()+EndUpdate(), This method indicates that a general update is performed only after all internal programs are executed , Not every Add Update every item .( Avoid frequent refreshes )
// listView1.BeginUpdate();
// obtain [ subdirectories ] list
DirectoryInfo[] subDirs = dir.GetDirectories();
foreach (DirectoryInfo d in subDirs)
{
// If the directory is hidden , Then skip
if ((d.Attributes & FileAttributes.Hidden) > 0) continue;
// Otherwise, add it to ListVie It shows that ( Directory name , Last modified , Data item type , file size )
AddListItem(d.Name, d.LastWriteTime, " Folder ", -1);
}
// obtain [ Sub file ] list
FileInfo[] subFiles = dir.GetFiles();
foreach (FileInfo f in subFiles)
{
// If the file is hidden , Then skip
if ((f.Attributes & FileAttributes.Hidden) > 0) continue;
string ext = f.Extension.ToUpper(); // Get the file extension suffix (.zip、.png、.doc etc. )
// Otherwise, add it to ListVie It shows that ( File name , Last modified , File suffix type , file size )
AddListItem(f.Name, f.LastWriteTime, ext, f.Length);
}
// listView1.EndUpdate();
}
//3, Add files and directories to... According to different types ListView Data item
private void AddListItem(string label, DateTime time, string type, long size)
{
// Determine whether it is a file or a folder , Use different icons
int imageIndex = 0;
if (!type.Equals(" Folder ")) imageIndex = 1;
ListViewItem item = new ListViewItem(label, imageIndex);//imageIndex Will go to listView Under the SmallImageList Find Icon
// Add child - Time
item.SubItems.Add(time.ToString("yyyy-MM-dd HH:mm"));
// Add child - type
item.SubItems.Add(type);
// Add child - file size
string sizeStr = "";
if (size < 0)
sizeStr = ""; // Folder does not display size
else if (size < 1000)
sizeStr = "" + size;
else if (size < 1000000)
sizeStr = size / 1000 + " KB";
else if (size < 1000000000)
sizeStr = size / 1000000 + " MB";
else
sizeStr = size / 1000000000 + " GB";
item.SubItems.Add(sizeStr);
listView1.Items.Add(item);
}
}
}

2.ListView Mode switch
3.ListView Control : Mode switch ( Switch details 、 list 、 Large icon 、 Small icon mode displays )
(1) The design requirements : On the basis of the case shown in the content file directory in the previous section , Realize the right-click menu to switch the display mode
(2) Development process :
- In the design interface , Drag in ListView Control , And set up Dock Full of Fill
- Initialize in code ListView Control column name 、[ Large icon list ]、[ Small icon list ] etc. ( because Two sets of icons are required for large icon mode and small icon mode )
- Load traversal files and directories , And add data items Item
- Drag in the design interface ContextMenu Control , And set up ListView Of MouseUp Click event , Show the right-click menu
- Right click menu to switch mode
namespace WindowsFormsApp_learning2
{
public partial class Form3 : Form
{
public Form3()
{
InitializeComponent();
//1. initialization ListView Control
InitListView();
//2. Load files and directories
LoadDir(new DirectoryInfo("D:\\"));
}
//1. initialization ListView Control
private void InitListView()
{
listView1.View = View.Details;
listView1.FullRowSelect = true;
// Set column name
listView1.Columns.Add(" name ", -2, HorizontalAlignment.Left);
listView1.Columns.Add(" Modification time ", 150, HorizontalAlignment.Left);
listView1.Columns.Add(" type ", 100, HorizontalAlignment.Left);
listView1.Columns.Add(" size ", -2, HorizontalAlignment.Left);
//* establish SmallImageList Small icon list ( be used for Detail、SmallIcon And so on )
ImageList smallImgList = new ImageList();
smallImgList.ImageSize = new Size(16, 16);// Set the size of the pictures in the list
smallImgList.Images.Add(Properties.Resources.Icon_file);
smallImgList.Images.Add(Properties.Resources.Icon_folder);
listView1.SmallImageList = smallImgList;
//* establish LargeImageList Large icon list ( be used for LargeIcon Display large icon in mode )
ImageList largeImgList = new ImageList();
largeImgList.ImageSize = new Size(64, 64);// Set the size of the pictures in the list
largeImgList.Images.Add(Properties.Resources.Icon_file2);
largeImgList.Images.Add(Properties.Resources.Icon_folder2);
listView1.LargeImageList = largeImgList;
}
//2. Load data items : Traverse files and directories , Add data items according to different types Item And its children
private void LoadDir(DirectoryInfo dir)
{
listView1.BeginUpdate();
// obtain [ subdirectories ] list
DirectoryInfo[] subDirs = dir.GetDirectories();
foreach (DirectoryInfo d in subDirs)
{
if ((d.Attributes & FileAttributes.Hidden) > 0) continue;
AddListItem(d.Name, d.LastWriteTime, " Folder ", -1);
}
// obtain [ Sub file ] list
FileInfo[] subFiles = dir.GetFiles();
foreach (FileInfo f in subFiles)
{
if ((f.Attributes & FileAttributes.Hidden) > 0) continue;
string ext = f.Extension.ToUpper();// File suffix
AddListItem(f.Name, f.LastWriteTime, ext, f.Length);
}
listView1.EndUpdate();
}
//3, Add files and directories to... According to different types ListView Data item
private void AddListItem(string label, DateTime time, string type, long size)
{
// Determine whether it is a file or a folder , Use different icons
int imageIndex = 0;
if (!type.Equals(" Folder ")) imageIndex = 1;
ListViewItem item = new ListViewItem(label, imageIndex);
// Add child - Time
item.SubItems.Add(time.ToString("yyyy-MM-dd HH:mm"));
// Add child - type
item.SubItems.Add(type);
// Add child - file size
string sizeStr = "";
if (size < 0)
sizeStr = ""; // Folder does not display size
else if (size < 1000)
sizeStr = "" + size;
else if (size < 1000000)
sizeStr = size / 1000 + " KB";
else if (size < 1000000000)
sizeStr = size / 1000000 + " MB";
else
sizeStr = size / 1000000000 + " GB";
item.SubItems.Add(sizeStr);
listView1.Items.Add(item);
}
//4.ListView add to MouseUp Click event : Show the right-click menu ( The current display mode is selected by default in the menu )
private void listView1_MouseUp(object sender, MouseEventArgs e)
{
if(e.Button == MouseButtons.Right)
{
View view = listView1.View;
// According to the display mode , Set the selected item in the right-click menu
menuDetail_Item.Checked = (view == View.Details);
menuList_Item.Checked = (view == View.List);
menuLarge_Item.Checked = (view == View.LargeIcon);
menuSmall_Item.Checked = (view == View.SmallIcon);
// Show the right-click menu ( At the right mouse button position e.Location)
contextMenuStrip.Show(listView1, e.Location);
}
}
//5. Set the click event of the right-click menu : Switch display mode
private void menuDetail_Item_Click(object sender, EventArgs e)
{
listView1.View = View.Details;
}
private void menuList_Item_Click(object sender, EventArgs e)
{
listView1.View = View.List;
}
private void menuLarge_Item_Click(object sender, EventArgs e)
{
listView1.View = View.LargeIcon;
}
private void menuSmall_Item_Click(object sender, EventArgs e)
{
listView1.View = View.SmallIcon;
}
}
}


3.ListView Data item column sorting
4.ListView Column sorting implementation of : Click on each column to achieve ascending order / null ( Here, only the first 0 List as an example )
(1) Coding steps ( Based on the case displayed in the file directory ):
- Add arrow icon resource , Indicates ascending and descending identifiers
- Add icons to SmallImageList, among Images.Add (key, image ) Means to add an image image, And associated with a key value . The following can be based on key Value to get this picture .
- Add data items Tag: Every ListView Can relate to a Tag, It is usually an object . When used for sorting, it is convenient to directly use objects for comparison
- Define comparators MyListItemSorter, Implement binding Tag Custom sorting of objects
- Add the click event of the column :ColumnClick Switch ascending order / Descending
(1) Customize Tag object , Package information
namespace WindowsFormsApp_learning2
{
// Associated with each list item Tag data
class MyListItemTag
{
public int type = 0; // type : Folder 0, file 1
public string path;
public string name;
public DateTime time;
public long size = -1;
public string ext; // Show file suffixes / Folder
public MyListItemTag(int type, string path, string name, DateTime time, long size, string ext)
{
this.type = type;
this.path = path;
this.name = name;
this.time = time;
this.size = size;
this.ext = ext;
}
}
}
(2) Custom comparator , Implement object sorting ( Pass in two Tag object )
namespace WindowsFormsApp_learning2
{
// Inherit IComparer Interface , Implement object comparison methods
public class MyListItemSorter : IComparer
{
public bool asc = true;// Sort in ascending order
public MyListItemSorter(bool asc)
{
this.asc = asc;
}
public int Compare(object x, object y)
{
// When sorting by column , There are two ListViewItem object
ListViewItem item1 = (ListViewItem)x;
ListViewItem item2 = (ListViewItem)y;
// Tag: Each associated data
MyListItemTag tag1 = (MyListItemTag)item1.Tag;
MyListItemTag tag2 = (MyListItemTag)item2.Tag;
// Directory first , File after
if (tag1.type != tag2.type)
return CompareInt(true, tag1.type, tag2.type);
// Compare by name
return CompareStringIgnoreCase(asc, tag1.name, tag2.name);
}
// Two Bool Comparison of values
public int CompareBool(bool asc, bool x, bool y)
{
int xx = x ? 1 : 0;
int yy = y ? 1 : 0;
return CompareInt(asc, xx, yy);
}
// Two Int Comparison of values
public int CompareInt(bool asc, int x, int y)
{
if (asc)
return x - y;
else
return y - x;
}
// Two String Comparison of values
public int CompareString(bool asc, string x, string y)
{
if (asc)
return x.CompareTo(y);
else
return y.CompareTo(x);
}
// Two String Comparison of values ( Case insensitive )
public int CompareStringIgnoreCase(bool asc, string x, string y)
{
return CompareString(asc, x.ToLower(), y.ToLower());
}
}
}
(3) Main form Form.cs Logic code
namespace WindowsFormsApp_learning2
{
public partial class Form4 : Form
{
// Current default sort : Ascending
private bool asc = true;
public Form4()
{
InitializeComponent();
InitListView();
LoadDir(new DirectoryInfo("D:\\"));
}
//1. initialization ListView Control
private void InitListView()
{
listView1.View = View.Details;
listView1.FullRowSelect = true;
// Set column name
listView1.Columns.Add(" name ", -2, HorizontalAlignment.Left);
listView1.Columns.Add(" Modification time ", 150, HorizontalAlignment.Left);
listView1.Columns.Add(" type ", 100, HorizontalAlignment.Left);
listView1.Columns.Add(" size ", -2, HorizontalAlignment.Left);
// establish smallImageList, Add small icon resources
ImageList imgList = new ImageList();
imgList.ImageSize = new Size(16, 16);// Set the size of the pictures in the list
imgList.Images.Add(Properties.Resources.Icon_file);
imgList.Images.Add(Properties.Resources.Icon_folder);
listView1.SmallImageList = imgList;
// When you click on a column header , Icon indicating sorting
// Add Icon resources to SmallImageList in , For column header display
imgList.Images.Add("Sort_ASC", Properties.Resources.up);
imgList.Images.Add("Sort_DESC", Properties.Resources.down);
//ListView The icon in the first column is displayed as key=""Sort_ASC"
listView1.Columns[0].ImageKey = "Sort_ASC";
}
//2. Traverse local resources , Get a file or directory
private void LoadDir(DirectoryInfo dir)
{
listView1.BeginUpdate();
// obtain [ subdirectories ] list
DirectoryInfo[] subDirs = dir.GetDirectories();
foreach (DirectoryInfo d in subDirs)
{
if ((d.Attributes & FileAttributes.Hidden) > 0) continue;
//** Package the data as Tag Object to add
MyListItemTag tag = new MyListItemTag(0,d.FullName,d.Name,d.LastWriteTime,-1," Folder ");
AddListItem(tag);
}
// obtain [ Sub file ] list
FileInfo[] subFiles = dir.GetFiles();
foreach (FileInfo f in subFiles)
{
if ((f.Attributes & FileAttributes.Hidden) > 0) continue;
//** Package the data as Tag Object to add
MyListItemTag tag = new MyListItemTag(1, f.FullName, f.Name, f.LastWriteTime, f.Length, f.Extension.ToUpper());
AddListItem(tag);
}
listView1.EndUpdate();
}
//3, Add files and directories to... According to different types ListView Data item
private void AddListItem(MyListItemTag tag)
{
// Determine whether it is a file or a folder , Use different icons
int imageIndex = 0;
if (!tag.type.Equals(" Folder ")) imageIndex = 1;
ListViewItem item = new ListViewItem(tag.name, imageIndex);
// **Item relation Tag Data objects ( It's convenient for us to get from Item Get data in 、 Sort, etc )
item.Tag = tag;
// Event children
item.SubItems.Add(tag.time.ToString("yyyy-MM-dd HH:mm"));
// Suffix name children
item.SubItems.Add(tag.ext);
// Big and small items
long size = tag.size;
string sizeStr = "";
if (size < 0)
sizeStr = ""; // Folder does not display size
else if (size < 1000)
sizeStr = "" + size;
else if (size < 1000000)
sizeStr = size / 1000 + " KB";
else if (size < 1000000000)
sizeStr = size / 1000000 + " MB";
else
sizeStr = size / 1000000000 + " GB";
item.SubItems.Add(sizeStr);
listView1.Items.Add(item);
}
//4.ListView Column click event : Switch ascending order / Descending ( Only for section 0 Column )
private void listView1_ColumnClick(object sender, ColumnClickEventArgs e)
{
if (e.Column == 0)// If you click on the 0 Column , Event triggered
{
// Toggles the current sort
this.asc = !asc;
if (asc)
{
// Set the sorter
listView1.ListViewItemSorter = new MyListItemSorter(true);
listView1.Sort();// Sort
listView1.Columns[0].ImageKey = "Sort_ASC";// Toggle icon
}
else
{
listView1.ListViewItemSorter = new MyListItemSorter(false);
listView1.Sort();
listView1.Columns[0].ImageKey = "Sort_DESC";
}
}
}
}
}

4.ListView Tag editor
5.ListView: Edit label
(1) Design ListView Show , And add data items
(2) Set in the design interface or code LabelEdit=True, Indicates that editing of data item labels is allowed
(3) How to start label editing :
- Double click the label in the window , Start editing
- Use code , Use... In events ListViewItem.BeginEdit() To start editing ( For example, right click menu - rename event ):
a. Add right click menu , New menu item - rename
b.ListView add to MouseUp Mouse click event , Show the right-click menu , Get the item in the right-click point
c. Right click menu item to add mouse click event , Right click on the menu - rename , Open the tab editing of this item
d. Edit validation : After editing / Before , Verify the label content ( For example, the name cannot be repeated , Cannot contain some characters, etc ), stay ListView Add event BeforeLabelEdit/AfterLabelEdit, Enable edit validation for each data item ( Automatically triggered before and after editing )
(4) Be careful :
- Only right The main item Editing
- By default, label editing does not modify the source data ( For example, the file display will not change the real file name ), To synchronize changes, you can set events
namespace WindowsFormsApp_learning2
{
public partial class Form5 : Form
{
// Items in the current mouse event point
private ListViewItem mouseClickItem;
public Form5()
{
InitializeComponent();
InitListView();
// Initialize and add several items of data
AddListItem(new Student(20201001, "shao", "13810012xxx"));
AddListItem(new Student(20201002, "wang", "18799122xxx"));
AddListItem(new Student(20201003, "li", "13490912xxx"));
}
//1. Design ListView Show , And add data items
private void InitListView()
{
listView1.View = View.Details;
listView1.FullRowSelect = true;
//** Set up LabelEdit, Allow editing of data item labels
listView1.LabelEdit = true;
// Set column name
// Width value -2 Indicates automatic width adjustment
listView1.Columns.Add(" full name ", 150, HorizontalAlignment.Left);
listView1.Columns.Add(" Student number ", 150, HorizontalAlignment.Left);
listView1.Columns.Add(" cell-phone number ", -2, HorizontalAlignment.Left);
}
private void AddListItem(Student stu)
{
ListViewItem item = new ListViewItem(stu.Name, 0);
item.Tag = stu;
item.SubItems.Add(stu.Id + "");
item.SubItems.Add(stu.Phone);
listView1.Items.Add(item);
}
//2. Right click to display the right-click menu
private void listView1_MouseUp(object sender, MouseEventArgs e)
{
if(e.Button == MouseButtons.Right)
{
// obtain Right click ListViewItem Data item
ListViewItem item = listView1.GetItemAt(e.X, e.Y);
this.mouseClickItem = item;
// Determine whether the item can be renamed
renameMenu_Item.Enabled = (item != null);
// Show the location / that item Of Right-click menu
contextMenuStrip1.Show(listView1, e.Location);
}
}
//3. Right-click menu - rename Click event , Open the tab editing of this item
private void renameMenu_Item_Click(object sender, EventArgs e)
{
this.mouseClickItem.BeginEdit();
}
//4. Enable editing of list items Auto trigger event BeforeLabelEdit
private void listView1_BeforeLabelEdit(object sender, LabelEditEventArgs e)
{
}
//5. End editing list items Auto trigger event AfterLabelEdit( Event transmitter sender, Event handler e)
private void listView1_AfterLabelEdit(object sender, LabelEditEventArgs e)
{
// obtain ListView The subscript of the current edit item Index
int index = e.Item;
// Get the newly edited text
string label = e.Label;
// Check for name conflicts
for (int i = 0; i < listView1.Items.Count; i++)
{
if (index == i) continue;
if (label == listView1.Items[i].Text)
{
//CancelEdit=True Cancel the newly edited content , Restore original content
e.CancelEdit = true;
MessageBox.Show(" Repeat the name ", " Tips ");
return;
}
}
// Otherwise, there is no duplicate name , Accept new changes
e.CancelEdit = false;
// Update background data synchronously ( Object is reference data )
Student stu = (Student)listView1.Items[index].Tag;
stu.Name = label;
}
}
}

7、 ... and . Table view control DataGridView
1. Table view basic usage
1. Tabular view DataGridView Basics : Display data and operations in the form of cell tables
(1) In the design interface , Drag in DataGridView Control , And set up Dock To fill Fill
(2) In the design interface or code , Set column name Columns
(3) Add data items to the design interface or code , Recommended code to add ( Dynamic expansion )
* Be careful : Each cell of the table view should be editable !
namespace WindowsFormsApp_learning2
{
public partial class Form6 : Form
{
public Form6()
{
InitializeComponent();
// Initialize table view layout
InitGridView();
// Initialize add data
AddRows(new Student(202101, "wx", "18264886xxx"));
AddRows(new Student(202102, "my", "13012459xxx"));
AddRows(new Student(202103, "tom", "19857138xxx"));
}
//1. Initialize the number of columns 、 Name
private void InitGridView()
{
// Set the number of columns displayed in the table
this.dataGridView1.ColumnCount = 4;
// Set the column header name for each column
dataGridView1.Columns[0].Name = " Student number ";
dataGridView1.Columns[1].Name = " full name ";
dataGridView1.Columns[2].Name = " Gender ";
dataGridView1.Columns[3].Name = " cell-phone number ";
}
//2. Add table data items
private void AddRows(Student stu)
{
// Set up Object Array ! For a row of data
Object[] row =
{
stu.Id,stu.Name," male ",stu.Phone
};
// Add data row
dataGridView1.Rows.Add(row);
}
}
}

2. Table view advanced usage
2. Tabular view DataGridView Basic operation : attribute 、 Additions and deletions
(1)DataGridView Common properties :
- [ miscellaneous ] Columns : Set the number of columns related to columns 、 Name, etc
- [ appearance ] ColumnHeadersVisible : Set whether column headers are visible ( The default is True)
- [ appearance ] RowHeadersVisible : Set whether the row header is visible ( The default is True)
- [ Behavior ] MultiSelect : Whether multiple choices are allowed ( The default is True)
- [ Behavior ] AllowUserToxxx: Whether to allow the user to change the cell Add, delete, modify, check, etc
- [ Behavior ] Column also supports clicking Ascending / Descending Sort ( Automation has been implemented )
(2)DataGridView Common operations :
- Add a row of data :grid.Rows.Add(Object[]) or The interface is added manually ( Need to trigger events , Persist to database )
- Get row data :
a. Index method :grid[col,row] Note that the column index comes first , Row index after
b. Function mode :grid.Rows[i].Cells[j]
- Delete row data :
a. Single row deletion :grid.Rows.RemoveAt(int i): Delete the first i Row data
b. Multi row deletion (ctrl multi-select ):grid.Rows.Remove(DataGridViewRow row): Delete specified row object
3. Tabular view DataGridView Cell edit
(1) Realization way :
- The interface can be edited directly :DataGridView By default, each cell can be edited directly , After editing and modifying, press enter to display the modification in the interface .
- Add event trigger edit : You can also edit by adding a right-click menu or double clicking an event , Or pop up a dialog box to edit .
(2) Related properties :ReadOnly
- Design interface :Columns in , Set a column as ReadOnly=True read-only , Cannot be edited or modified ;ReadOnly=False Editable
- In the code :grid.Columns[0].ReadOnly = True;
(3) Cell edit event steps :
- Set the state of : Set up ReadOnly = False Editable status ( The default is False)
- Start editing : Click the cell in the interface to select , Click again , Then start to enter the editing state
- Validation event after editing : When editing is complete, press enter , Trigger [ The focus of ] CellValidating Occurs when a cell is validated ,CellValidating After execution Trigger CellValidated Occurs after cell validation
(1) Case interface design
Design a case , Realize the basic operation of table view ( Additions and deletions ), And edit event validation .

(2)Form.cs Main form logic code
namespace WindowsFormsApp_learning2
{
public partial class Form7 : Form
{
public Form7()
{
InitializeComponent();
InitGridView();
AddRows(new Student(202101, "wx", "18264886xxx"));
AddRows(new Student(202102, "my", "13012459xxx"));
AddRows(new Student(202103, "tom", "19857138xxx"));
}
//1. Initialize the number of columns 、 Name
private void InitGridView()
{
this.grid.ColumnCount = 4;
grid.Columns[0].Name = " Student number ";
grid.Columns[1].Name = " full name ";
grid.Columns[2].Name = " Gender ";
grid.Columns[3].Name = " cell-phone number ";
}
//2. Add table data items
private void AddRows(Student stu)
{
Object[] row =
{
stu.Id,stu.Name," male ",stu.Phone
};
grid.Rows.Add(row);
}
//3. Add button click event : Add a row of data
private void btn_add_Click(object sender, EventArgs e)
{
Object[] row = new object[4];
row[0] = 202104;
row[1] = "testUser";
row[2] = " Woman ";
row[3] = "1928373838";
grid.Rows.Add(row);
}
//4. Get data button click event : Get row data
private void btn_get_Click(object sender, EventArgs e)
{
// For the first 0 Row data
Object id = grid[0, 0].Value;
Object name = grid[1, 0].Value;
Object sex = grid.Rows[0].Cells[2].Value;
Object phone = grid.Rows[0].Cells[3].Value;
// Displayed in the MessageBox
MessageBox.Show(id + "," + name + "," + sex + "," + phone);
}
//5. Delete button click event : Delete the selected line
private void btn_del_Click(object sender, EventArgs e)
{
// Single row deletion Delete the first 0 That's ok
//grid.Rows.RemoveAt(0);
// Multi row deletion Delete [ Choose ] All of the line
foreach(DataGridViewRow row in grid.SelectedRows)
{
grid.Rows.Remove(row);
}
}
//6. Edit validation : Cell validation Events
private void grid_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
//e.ColumnIndex Express Edit the column index of the cell
if (e.ColumnIndex == 1)
{
// Verify the editing of the name
}else if (e.ColumnIndex == 2)
{
// Verify gender editing
}
else if(e.ColumnIndex == 3)
{
// Verify the editing of the mobile number ( The phone number must be 11 Legal digits )
string str = e.FormattedValue.ToString();
if(str.Length != 11)
{
MessageBox.Show(" The mobile phone number must be 11 position ", "Error");
e.Cancel = true;// Cancel editing event
return;
}
foreach(char ch in str)
{
if(ch < '0' || ch > '9')
{
MessageBox.Show(" Mobile phone number must be numeric ", "Error");
e.Cancel = true;// Cancel editing event
return;
}
}
}
}
//7. The event to execute after the cell validation is completed
private void grid_CellValidated(object sender, DataGridViewCellEventArgs e)
{
}
}
}

8、 ... and . Comprehensive practice : Student information management system
边栏推荐
- AAAI2022-ShiftVIT: When Shift Operation Meets Vision Transformer
- 一大厂95后程序员对部门领导不满,删库跑路被判刑
- Learning summary 01- machine learning
- Cross modal retrieval | visual representation learning
- Preliminary understanding of DFS and BFS
- Simple linear regression of sklearn series
- Lianrui: how to rationally see the independent R & D of domestic CPU and the development of domestic hardware
- 华为设备配置BGP/MPLS IP 虚拟专用网命令
- Solving graph problems with union search set
- [markdown syntax advanced] make your blog more exciting (III: common icon templates)
猜你喜欢

IOU series (IOU, giou, Diou, CIO)

Conversion relationship between coordinate systems (ECEF, LLA, ENU)

Wechat applet uploads the data obtained from database 1 to database 2

Support vector machine -svm+ source code

Topological sorting

White Gaussian noise (WGN)

Tightly coupled laser vision inertial navigation slam system: paper notes_ S2D. 66_ ICRA_ 2021_ LVI-SAM

Titanic rescued - re exploration of data mining (ideas + source code + results)

Zed2 camera calibration -- binocular, IMU, joint calibration

Huawei equipment is configured to access the virtual private network through GRE tunnel
随机推荐
IOU series (IOU, giou, Diou, CIO)
jvm调优五:jvm调优工具和调优实战
Emnlp2021 𞓜 a small number of data relation extraction papers of deepblueai team were hired
Wechat applet uploads the data obtained from database 1 to database 2
Titanic rescued - re exploration of data mining (ideas + source code + results)
2021 iccv paper sharing - occlusion boundary detection
Combien de courant le câblage des PCB peut - il supporter?
Dongmingzhu said that "Gree mobile phones are no worse than apple". Where is the confidence?
Iris dataset - Introduction to machine learning
Network security construction in 5g Era
Preliminary understanding of DFS and BFS
Reverse thinking: making cartoon photos real
Section II: structural composition characteristics of asphalt pavement (1) structural composition
Comparison of gigabit network card chips: who is better, a rising star or a Jianghu elder?
go MPG
jvm调优六:GC日志分析和常量池详解
博途仿真时出现“没有针对此地址组态任何硬件,无法进行修改”解决办法
Topological sorting
New product release: Lianrui launched a dual port 10 Gigabit bypass network card
Anaconda installation and use process