簡體   English   中英

為什么我的下拉列表在 C# 中不起作用?

[英]Why my drop down list did not working C#?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            comboBox1.Items.Add("Sunday");
            comboBox1.Items.Add("Monday");
            comboBox1.Items.Add("Tuesday");
            comboBox1.Items.Add("Wednesday");
            comboBox1.Items.Add("Thursday");
            comboBox1.Items.Add("Friday");
            comboBox1.Items.Add("Saturday");
            comboBox1.SelectedIndex = comboBox1.FindStringExact("Sunday");

        }

        private void button1_Click(object sender, EventArgs e)
        {
            string var;
            var = comboBox1.Text;
            MessageBox.Show(var);
        }
    }
}

這是代碼,但是當我嘗試運行它時,它很好,但我的下拉列表沒有顯示任何值。 我還是 C# 語言的新手,如果我沒有意識到代碼中有任何錯誤,請原諒我。 有人,請幫助並向我解釋什么是錯誤及其解決方案。 我真的需要它。 非常感謝。

首先,您不需要在“表單加載”事件中加載項目,您可以在InitializeComponent()之后在Form1()本身中加載項目,其次您可以嘗試使用 List 和 ItemsSource:

public Form1()
{
    InitializeComponent();
    List<string> items = new List<string> { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
    comboBox1.ItemsSource = items;
    comboBox1.SelectedIndex = 0;       //since you know "Sunday" is at index 0
}

編輯:正如約翰評論的那樣,您提供的代碼已經有效,我的回答仍然是縮短和簡化代碼的建議。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM