[WinForm Detailed Tutorial 2] ComboBox, CheckedListBox, DateTimePicker, MonthCalender, and MaskedTextBox controls in WinForm

1.ComboBox

  • ComboBox is a drop-down box (combo box) control.
  • Only allow the user to select one option.

Common properties

  • Name: Subject name
  • DropDownStyle: Drop-down style (DropDown, DropDownList, Simple)
  • Items: Collection of selections
  • DataSource: Number source
  • DisplayMember: Displayed data field
  • ValueMember: Data field of actual value

Items method

  • Similar to ListBox, addition, deletion and clearing operations can be performed.

** event**

  • SelectedIndexChanged: Triggered when the selected item changes.

data binding

  • Use DataSource, DisplayMember Sum ValueMember Define the number of rows.

Simple case

Create a Person class:

public class UserInfo
{
    public string Name { get; set; }
    public int ID { get; set; }
}

Here's an example of how to use this class to populate a ComboBox.

code

public partial class frmComboBox : Form
{
    public frmComboBox()
    {
        InitializeComponent();
        List<UserInfo> list = new List<UserInfo>();
        list.Add(new UserInfo
                 {
                     Name = "智能建造小硕",
                     ID = 0
                 });
        list.Add(new UserInfo()
                 {
                     ID = 1,
                     Name = "admin"
                 });
        list.Add(new UserInfo()
                 {
                     ID = 2,
                     Name = "lycchun"
                 });
        list.Add(new UserInfo()
                 {
                     ID = 3,
                     Name = "lwb"
                 });
        list.Add(new UserInfo()
                 {
                     ID = 4,
                     Name = "Eleven"
                 });
        list.Add(new UserInfo()
                 {
                     ID = 5,
                     Name = "Jason"
                 });

        cobName.DataSource = list;
        cobName.ValueMember = "ID";
        cobName.DisplayMember = "Name";

        //注册事件
        cobName.SelectedIndexChanged += comboBox1_SelectedIndexChanged;
    }

    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
       MessageBox.Show("选中了:" + (cobName.SelectedItem as UserInfo).Name, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
}

Show results

Insert image description here

2.CheckedListBox

  • CheckedListBox is a control used to display a list of items, similar to ListBox.
  • The difference is that each item has a checkbox in front of it and the user can select multiple items.
  • This is very useful for scenarios that require multiple selection operations.

Attributes:

  • CheckOnClick: This is a Boolean property that, if set to True, causes the checkbox to immediately toggle its checked state when the user clicks on the item. If set to False, the user needs to click on the checkbox to change the selected state.

Methods and properties:

  • Items:

    The Items property of the CheckedListBox control is used to manage the items in it.

    • Add method: You can use the Add method to add items to the CheckedListBox.
    • DataSource: If you have a data source, you can assign it to the DataSource property so that the CheckedListBox is dynamically populated.
    • DisplayMember: When using a data source, the DisplayMember property defines the text field that displays in the item.
    • ValueMember: If you need to store the value associated with each item, you can use the ValueMember attribute to specify the associated value field.

event:

  • SelectedIndexChanged: The SelectedIndexChanged event is triggered when the user selects a different item. This is a commonly used event that can be used in response to user selection actions.
  • ItemCheck: The ItemCheck event is fired when the item's selected state changes (not necessarily triggered by the user). This can be used to perform some custom logic before changes occur.

Simple case

  public partial class frmCheckedListBox : Form
  {
      public frmCheckedListBox()
      {
          InitializeComponent();
      }

      private void frmCheckedListBox_Load(object sender, EventArgs e)
      {
          直接添加项
          //cklLList.Items.Clear();
          //cklLList.Items.Add(1);
          //cklLList.Items.Add("aaa");
          //cklLList.Items.AddRange(new string[] { "aaa", "bbb", "ccc" });
          //cklLList.Items.Insert(2, "ddd");
          //cklLList.Items.Remove("ddd");
          //cklLList.Items.RemoveAt(2);//移除第3项

          List<UserInfo> list = new List<UserInfo>();
          list.Add(new UserInfo()
          {
              ID = 1,
              Name = "admin"
          });
          list.Add(new UserInfo()
          {
              ID = 2,
              Name = "lycchun"
          });
          list.Add(new UserInfo()
          {
              ID = 3,
              Name = "lwb"
          });
          list.Add(new UserInfo()
          {
              ID = 4,
              Name = "Eleven"
          });
          list.Add(new UserInfo()
          {
              ID = 5,
              Name = "Jason"
          });
          //当指定 了DataSource,是不可以修改Items集合的
          cklLList.DataSource = list;
          cklLList.DisplayMember = "Name";
          cklLList.ValueMember = "Id";
          //cklLList.Items.RemoveAt(4);
          //勾选或选择项的获取
          //cklLList.CheckedIndices
          //cklLList.CheckedItems
          //cklLList.SelectedIndices
          //cklLList.SelectedItems
          //cklLList.SelectedIndex
      }
  }

Show results
Insert image description here

3.DateTimePicker and MonthCalender controls

3.1DateTimePicker

DateTimePicker is a control used to select a date and/or time. It allows the user to select a date from a calendar or a time from a drop-down list, depending on its settings.

Attributes:

  • Value: This is the date and time value currently selected by the datetime control. You can use this property to get or set the value of a control.
  • Text: The Text property is used to get or set the text displayed on the date and time control. Normally it displays the date and time in the Value property.
  • Format: The Format property is used to specify the display format of the date and time control. It has several options:
    • Custom: To use a custom date and time format, you need to configure the CustomFormat attribute.
    • Long: Displays the complete date and time.
    • Short: Displays a shorter date and time.
  • CustomFormat: When the Format property is set to Custom, the CustomFormat property is used to specify a custom date and time format. For example, you can set it to "yyyy-MM-dd HH:mm:ss" to display the year, month, day, hour, minutes, and seconds.
  • ShowCheckBox: This is a Boolean property that, if set to True, displays a checkbox next to the datetime control. Users can use checkboxes to enable or disable datetime selection.
  • ShowUpDown: This is also a Boolean property. If set to True, up and down arrow buttons are displayed next to the date and time control. The user can use these buttons to increase or decrease the date and time. value.

event:

  • ValueChanged: When the user changes the value of the date and time control, the ValueChanged event is triggered. This is a commonly used event, usually used to perform some action after a value has changed.

3.2 MonthCalender

The monthly calendar control (MonthCalendar) is a control used to select dates, usually displaying dates in the form of a calendar for the entire month. Users can select dates by clicking on them.

Attributes:

  • FirstDayOfWeek: This is an enumeration property that specifies the first day of the week. By default, it's usually set to Sunday, but you can change it to Monday or any other option that works for you.
  • MaxSelectionCount: This is an integer property that limits the number of dates the user can select. You can set it to 1 to ensure the user can only select a single date, or set it to a value greater than 1 to allow multiple dates to be selected.
  • ShowWeekNumbers: This is a Boolean property that, if set to True, displays the week numbers in the monthly calendar control.
  • ShowToday: This is a Boolean property that, if set to True, highlights today's date in the monthly calendar control.

event:

  • DateChanged: When the date or date range selected by the user changes, the DateChanged event will be triggered. This is a commonly used event, usually used to perform some action when the user selects a date.

3.3 Case

code example

public partial class frmTime : Form
{
    public frmTime()
    {
        InitializeComponent();
    }
    private void frmTime_Load(object sender, EventArgs e)
    {
        // 设置日期时间控件的显示格式为长日期
        dateTimePicker1.Format = DateTimePickerFormat.Long;
        // 启用复选框,允许用户禁用日期时间选择
        dateTimePicker1.ShowCheckBox = true;
        // 不显示上下箭头按钮
        dateTimePicker1.ShowUpDown = false;

        // 设置每周的第一天为周一
        monthCalendar1.FirstDayOfWeek = Day.Monday;
        // 设置允许选择多个日期
        monthCalendar1.MaxSelectionCount = 10;
        // 显示每周的周数
        monthCalendar1.ShowWeekNumbers = true;
        // 突出显示当天的日期
        monthCalendar1.ShowToday = true;
    }
    private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
    {
        // 当日期时间控件的值更改时,将新值显示在Label中
        label2.Text = "选择的日期时间是:" + dateTimePicker1.Value.ToString();
    }
    private void monthCalendar1_DateChanged(object sender, DateRangeEventArgs e)
    {
        // 当用户选择的日期范围发生改变时,将新的日期范围显示在Label中
        label1.Text = "选择的日期范围是:" + e.Start.ToShortDateString() + " 到 " + e.End.ToShortDateString();
    }
}

Effect

Insert image description here

4.MaskedTextBox

MaskedTextBoxControls validate and format user input based on masks. A mask is a string in which each character represents a specific input requirement. Here are some common mask codes and their meanings:

  • 0: Represents any number between 0 and 9 (use * as a placeholder).
  • 9: Indicates numbers or spaces.
  • #: Indicates a number, plus sign or minus sign.
  • L: Represents ASCII letters (use * as placeholder).
  • &: represents any character.
  • C: Indicates characters.
  • A: Indicates letters.

Insert image description here

Attributes:

  • Name: The name of the control.
  • BeepOnError: If set to true, a beep will sound when input does not match the mask rules.
  • Mask: Mask string, used to specify the input format.
  • PasswordChar: Specify a character to be used to replace the entered character, such as for password input.
  • PromptChar: Specify placeholder characters in the mask.
  • RejectInputOnFirstFailure: If set to true, input will be rejected when the first character entered does not match the mask rules.
  • Text: The text displayed in the control.
  • TextMaskFormat: Specify the display format of the control text.
  • CutCopyMaskFormat: Specify the format for cut and copy operations.

event:

  • MaskChanged: Event triggered when the mask changes.
  • MaskInputRejected: Event triggered when user input is rejected.

Usage example:

Use the MaskedTextBox control to enter the phone number, using the (###) ###-#### format. Here's an example:

 public partial class FrmMaskedTextBox : Form
 {
     public FrmMaskedTextBox()
     {
         InitializeComponent();
     }
     private void FrmMaskedTextBox_Load(object sender, EventArgs e)
     {
         maskedTextBox1.BeepOnError = true;//输入错误提示音
         // 设置掩码为电话号码格式
         maskedTextBox1.Mask = "(999) 000-0000";
         // 设置 PromptChar 为一个空格,以便在用户输入时自动填充占位符
         maskedTextBox1.PromptChar = ' ';
     }
     private void maskedTextBox1_MaskInputRejected(object sender, MaskInputRejectedEventArgs e)
     {
         if (e.Position < 0)
         {
             MessageBox.Show("输入不足以满足格式要求", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
         }
         else
         {
             MessageBox.Show("无效字符位于 " + e.Position + " 位置", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
         }
     }
 }

Effect
Insert image description here

[WinForm Detailed Tutorial] How to obtain the source code:
Insert image description here
Excellent recommendations:
[C# Advanced 1] Array (Array) in C#, Collections (ArrayList, Queue, Stack, HashList), List
[C# Advanced 8] Serialization and Under deserialization (binary serialization, XML serialization and JSON serialization)

[Advanced C#] Summary of some common knowledge points in C# syntax
[WinForm detailed tutorial 1] Form, Label, TextBox and Button controls, RadioButton and CheckBox, ListBox
[WinForm detailed tutorial three] NumericUpDown, PictureBox, RichTextBox and three Timer controls in WinForm
[WinForm detailed tutorial four] ProgressBar and ImageList in WinForm and ListView control
[WinForm detailed tutorial five] MenuStrip, ContextMenuStrip, ToolStrip, StatusStrip control in WinForm
[WinForm detailed tutorial six] GroupBox and Panel in WinForm , TabControl, SplitContainer control
[C# Advanced] Delegates, events, callback functions, anonymous functions and lambda expressions in C#

If you are interested in the intelligent construction major, or are a student, teacher or practitioner in a related field, you are welcome to join us through the WeChat public account [Intelligent Construction Xiaoshuo]!

Insert image description here
Hope it helps, and welcome to follow us. More related content will be updated later!

Guess you like

Origin blog.csdn.net/QH2107/article/details/134044020