1. Form and interface design-Form Control Technology

Source: Internet
Author: User

This section describes how to dynamically create a form, add prompt information before the form is closed, and control the movement of any form. These technologies are widely used in actual development.

044 add confirmation dialog box before closing the window

The FormClosing event is triggered before the window is closed. The FormClosing EventArgs e parameter in this event contains the Cancel attribute. If this attribute is set to True, the window will not be closed. Therefore, the event processing code prompts you whether to close the program. If you do not want to close the program, set this parameter to True. You can use the return value of the MessageBox parameter to know the buttons selected by the user.

Create a project. The default form is Form1.

Namespace _ 044_QueryClose {public partial class Form1: Form {public Form1 () {InitializeComponent ();} private void form=formclosing (object sender, FormClosingEventArgs e) {if (MessageBox. show ("the form is to be closed. Continue? "," Ask ", MessageBoxButtons. yesNo) = DialogResult. yes) {e. cancel = false; // The value of the event not canceled} else {e. cancel = true; // event cancellation value }}}}

045 refresh the parent form through the Child form

In this example, when the child form refreshes the parent form, the main application event is used to refresh the main form. When a child form generates an update operation, a method of the child form triggers the corresponding processing event in the main form.

1. Create a project and change the default form to ChildRefurbishParent. Add a Windows form and name it ChildWindow.

2. Add a dview control and a MenuStrip control to the ChildRefurbishParent form. Set MainMenuStrip attribute of ChildRefurbishParent form to menuStrip1, WindowState to Maximized, and IsMdiContainer to True. Add two GroupBox controls, five Label controls, four TextBox controls, one ComboBox control, and three Button controls to the ChildWindow form.

: When performing database-related operations, you must reference the namespace System. Data. SqlClient.

// ChildRefurbishParent Form code namespace _ 045_ChildRefurbishParent {public partial class ChildRefurbishParent: Form {public ChildRefurbishParent () {InitializeComponent ();} /// <summary> // For this instance, set the IsMdiContainer attribute of the main form to true, MainMenuStrip attribute to the added menu bar, WindowState attribute to Maximized, form name to ChildRefurbishParent, and set AllowUserToAddRows. attribute: false /// </summary> # The variable public static bool flag declared by region is false; // identify whether to create a new subform C HildWindow BabyWindow = new ChildWindow (); // instantiate a subform DataSet PubsSet = new DataSet (); // define a DataSet object public static string [] IDArray; // declare a one-dimensional string array public DataTable IDTable; // declare a data table object SqlDataAdapter IDAdapter; // declare a data reader object SqlDataAdapter PubsAdapter; // declare a data reader object SqlConnection ConnPubs; // declare a database connection object SqlCommand PersonalInformation; // declare an object that executes SQL statements # endregion // display data when loading the ChildRefurbishParent form Private void ChildRefurbishParent_Load (object sender, EventArgs e) {// string ConnString = "Data Source = .; dataBase = db_01; integrated security = sspi "; // string ConnString =" server = 55.66.77.88; user id = sa; pwd = 123456; DataBase = db_01 "; // remote database connection string AdapterString = "select userId as number, userName as name, phone number, address as address from tb_01 "; // string IDString = "select userID f Rom tb_01 "; // read the database's user ID string ConnPubs = new SqlConnection (ConnString); // create a database connection PubsAdapter = new SqlDataAdapter (AdapterString, ConnPubs ); // create PubsAdapter data reader IDAdapter = new SqlDataAdapter (IDString, ConnPubs); // read the user ID's reader PubsAdapter. fill (PubsSet, "Authors"); // Fill in the IDAdapter of the PubsSet dataset. fill (PubsSet, "ID"); // Fill in the PubsSet dataset DataTable PubsTable = PubsSet. tables ["Authors"]; // write data to the PubsTable table IDTable = P UbsSet. tables ["ID"]; // write data to ID table IDArray = new string [IDTable. rows. count]; // defines the maximum length for the array. defaultView; // set the data source for dataGridView1 (int I = 0; I <IDTable. rows. count; I ++) // cyclically traverse each row of data in the data table {for (int j = 0; j <IDTable. columns. count; j ++) // cyclically traverse each column of data in the data table {IDArray [I] = IDTable. rows [I] [j]. toString (); // Add data in the data table to a one-dimensional array }}# region click "add and delete" in "Operation Type" to display the subform private Void AddandDelete_Click (object sender, EventArgs e) {if (flag = false) // determine whether to create a form {CreateChildWindow () by determining the value of the identifier (); // create a subform} for (int I = 0; I <this. dataGridView1.Controls. count; I ++) // cyclically traverse the control set {if (this. dataGridView1.Controls [I]. name. equals (BabyWindow. name) // when a child form exists {flag = true; // change the Flag value break; // exit the loop body }}# endregion private void ExitProject_Click (object sender, EventArgs e ){ Application. exit (); // Exit this program} # region creates the CreateChildWindow method of the child form public void CreateChildWindow () {ChildWindow BabyWindow = new ChildWindow (); // instantiate a child form BabyWindow. mdiParent = this; // set the parent form of the child form to the current form this. dataGridView1.Controls. add (BabyWindow); // Add the child form BabyWindow to the DataGridView control. updateDataGridView + = new EventHandler (babywindow_updatedatagridatagri); BabyWindow. show (); // display subforms} // subforms use the BabyWindow_Updat event Update void babywindow_updatedatagri( object sender, EventArgs e) {if (ChildWindow. globalFlag = false) // when you click the delete button {if (ConnPubs. state = ConnectionState. closed) // when the database is disconnected {ConnPubs. open (); // Open the database connection} string AfreshString = "delete tb_01 where userID =" + ChildWindow. deleteID. trim (); // define a data deletion string PersonalInformation = new SqlCommand (AfreshString, ConnPubs); // execute the delete database Field PersonalInformation. executeNonQuery (); // execute the SQL statement and return the affected number of rows ConnPubs. close (); // Close DisplayData (); // display the updated content of the database MessageBox. show ("data deleted successfully! "," Message ", MessageBoxButtons. OK, MessageBoxIcon. asterisk); // The message indicating successful data deletion is displayed.} else {if (ConnPubs. state = ConnectionState. closed) // when the database is Closed {ConnPubs. open (); // Open the database} string InsertString = "insert into tb_01 values ('" + ChildWindow. idContent + "','" + ChildWindow. nameContent + "','" + ChildWindow. phoneContent + "','" + ChildWindow. addressContent + "')"; // defines a string variable for data insertion. The variable PersonalInformation = new SqlCommand (InsertString, ConnPubs); // execute the insert database Field PersonalInformation. executeNonQuery (); // execute the SQL statement and return the affected number of rows ConnPubs. close (); // Close DisplayData (); // display the updated data MessageBox. show ("data added successfully! "," Message ", MessageBoxButtons. OK, MessageBoxIcon. asterisk); // The prompt message indicating successful addition is displayed.} # endregion # When you change the data in the main form, you must display the public void DisplayData () {PubsSet. clear (); // string ConnString = "Data Source = .; dataBase = db_01; integrated security = sspi "; // string ConnString =" server = 55.66.77.88; user id = sa; pwd = 123456; DataBase = db_01 "; // remote database connection string ConnPubs = new SqlConnection (ConnString); // create a database connection string DisplayString = "select userId as number, userName as name, phone number, address as address from tb_01 "; // defines the field SqlDataAdapter PersonalAdapter = new SqlDataAdapter (DisplayString, ConnPubs) for reading database data; // defines a reader PersonalAdapter for reading database data. fill (PubsSet, "DisplayTable"); // Fill the data in the DisplayTable with the data dataGridView1.DataSource = PubsSet. tables ["DisplayTable"]. defaultView; // set the data source of the DataGridView control} # endregion }}
// ChildWindow Form code namespace _ 045_ChildRefurbishParent {public partial class ChildWindow: Form {public ChildWindow () {InitializeComponent ();} /// <summary> /// only one window can be created for this instance, so the close button is disabled here. It does not make sense after maximization, therefore, the attribute value of MaximizeBox is False. /// </summary> # the declaration of the region variable public event EventHandler UpdateDataGridView = null; // define a public static string DeleteID method for processing and updating the contents of the DataGridView control; // define a public static string that represents the deleted data number IdContent; // This variable is used to store the data number public static string nameContent; // This variable is used to store the name public static string phoneContent; // This variable is used to store the public static string addressContent; // This variable is used to store the public static bool GlobalFlag address; // This variable is used to identify whether to create a new subform # endregion // The UpdateData method is used to trigger the Processing Event protected void UpdateData () {if (UpdateDataGridView! = Null) // when the update DataGridView event is triggered {updatedatagri( this, EventArgs. empty); // update the content in the DataGridView control} // identify that the form is already closed in the form close event private void ChildWindow_FormClosing (object sender, FormClosingEventArgs e) {ChildRefurbishParent. flag = false; // if this value is set to false, a new form can be created.} // when the form is loaded, the private void ChildWindow_Load (object sender, eventArgs e) {for (int I = 0; I <ChildRefurbishParent. IDArr Ay. length; I ++) // cyclically traverse every element in the array {comboBox1.Items. add (ChildRefurbishParent. IDArray [I]. toString (); // Add comboBox1.SelectedIndex = 0 to the Combobox control; // set the index of the currently selected item to 0 }}// select the record to be deleted in the ComboBox control and click "delete" to delete the private void deleteButton_Click (object sender, eventArgs e) {GlobalFlag = false; // set the global variable to false if (comboBox1.Items. count> 1) // when no less than two items are left in the ComboBox, {DeleteID = comboBox1.SelectedItem. toString ();/ /Convert the selected item to int type if (comboBox1.Items. Count! = 0) // {comboBox1.Items. remove (comboBox1.SelectedItem); comboBox1.SelectedIndex = 0 ;}} UpdateData (); // update the content in the Combobox control} // when there are too many error messages entered in the text box, click "cancel" to clear all input content private void cancelButton_Click (object sender, EventArgs e) {id. clear (); // Clear the name of the content in the number text box. clear (); // Clear the phone in the name text box. clear (); // Clear the address in the phone number text box. clear (); // Clear the Content id in the residential address text box. focus (); // set the Focus of the current mouse in the numbered text box} // when you enter After the information is displayed, click the submit button to update the data to the main form with the unique private void submitButton_Click (object sender, EventArgs e) {GlobalFlag = true; // set the value of the identifier to true if (! (ComboBox1.Items. equals (idContent) // {comboBox1.Items. add (idContent); // Add a record to the Combobox control} UpdateData ();} // when the content of the text box in the form changes, save the value of the corresponding text box, this facilitates the database to update private void id_TextChanged (object sender, EventArgs e) {idContent = id. text; // Save the number of the newly added record} private void name_TextChanged (object sender, EventArgs e) {nameContent = name. text; // Save the filled name} private void phone_TextChanged (object sender, EventArgs e) {phoneContent = phone. text; // Save the entered phone number} private void address_TextChanged (object sender, EventArgs e) {addressContent = address. text; // Save the entered address information }}}

046 drag a borderless form

This example mainly uses two Windows API functions: ReleaseCapture and SendMessage.

: When calling Windows API functions, you must reference the namespace System. Runtime. InteropServices.

Create a project. The default form is Form1. Add a ContextMenuStrip control on the Form1 form. Set the ContextMenuStrip attribute of Form1 form to contextMenuStrip1.

Namespace _ 046_DragNoFrameWindow {public partial class Form1: Form {public Form1 () {InitializeComponent ();} /// <summary> /// for this instance, set the FormBorderStyle attribute of the form to None, and set the ContextMenuStrip attribute to the currently added instance. /// </summary> /// <param name = "sender"> </param> // <param name = "e"> </param> # API function [DllImport ("user32.dll" )] public static extern bool ReleaseCapture (); // used to release the cursor [DllImport ("user32.dll")] public static extern bool SendMessage (IntPtr hwdn, int wMsg, int mParam, int lParam); // send a Windows message to the specified form # endregion # region the variable public const int WM_SYSCOMMAND to be declared in this program = 0x0112; // This variable indicates the type of message to be sent to Windows: public const int SC _MOVE = 0xF010; // This variable indicates the additional message public const int HTCAPTION = 0x0002; // This variable indicates the additional message for sending the message # endregion private void ExitContext_Click (object sender, EventArgs e) {Application. exit (); // Exit this program} private void form=mousedown (object sender, MouseEventArgs e) {ReleaseCapture (); // used to release the cursor SendMessage (this. handle, WM_SYSCOMMAND, SC _MOVE + HTCAPTION, 0); // send a message to the Windows system to drag the form }}}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.