Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c#下拉框默认选中某个值

作者:菠蘿。d海   发布日期:2025-12-04   浏览:46

using System;
using System.Windows.Forms;

namespace ComboBoxExample
{
    public class Form1 : Form
    {
        private ComboBox comboBox1;

        public Form1()
        {
            // 初始化ComboBox控件
            comboBox1 = new ComboBox();
            comboBox1.FormattingEnabled = true;
            comboBox1.Location = new System.Drawing.Point(50, 50);
            comboBox1.Name = "comboBox1";
            comboBox1.Size = new System.Drawing.Size(200, 21);
            comboBox1.TabIndex = 0;

            // 添加项到ComboBox
            comboBox1.Items.Add("选项1");
            comboBox1.Items.Add("选项2");
            comboBox1.Items.Add("选项3");

            // 设置默认选中值
            comboBox1.SelectedItem = "选项2"; // 默认选中"选项2"

            // 将ComboBox添加到窗体
            this.Controls.Add(comboBox1);

            // 设置窗体属性
            this.Text = "ComboBox示例";
            this.Size = new System.Drawing.Size(300, 200);
        }

        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}

解释说明:

  1. 初始化ComboBox控件:创建一个ComboBox对象,并设置其位置、大小等属性。
  2. 添加项到ComboBox:使用Items.Add方法向组合框中添加多个选项。
  3. 设置默认选中值:通过SelectedItem属性设置组合框的默认选中项。在这个例子中,我们将默认选中"选项2"。
  4. 将ComboBox添加到窗体:使用Controls.Add方法将组合框添加到窗体中。
  5. 设置窗体属性:设置窗体的标题和大小。

这样,当程序运行时,组合框会默认选中"选项2"。

上一篇:c#获取路径中的文件名

下一篇:c# foreach跳出循环

大家都在看

c# 二进制

c# datatable group by

c# tcp client

c# type.gettype

c# sqlconnection

c# string.format 小数位数

.net和c#

c#获取系统时间

c#游戏开发

c#网络编程

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站