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 ASPNET20241004Controll
{
public partial class Form1_IntroControl : Form
{
public Form1_IntroControl()
{
InitializeComponent();
//載入下拉選單
comboBox1.Items.Add("Item1");
comboBox1.Items.Add("Item2");
comboBox1.Items.Add("Item3");
comboBox1.SelectedIndex = 0;
}
private void button1_Click(object sender, EventArgs e)
{
//DateTimePicker dateTimePicker = new DateTimePicker();
//textBox1.Controls.Add(dateTimePicker);
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
// 取得下拉選單的選項文字
string selectedItem = comboBox1.SelectedItem.ToString();
// 將選擇的文字內容加入至 label1
label1.Text = selectedItem;
}
}
}
要在 label1
中顯示選擇的城市的縮寫,你可以在 comboBox1_SelectedIndexChanged
方法中添加一些邏輯,將選擇的城市轉換為對應的縮寫,然後將縮寫顯示在 label1
上。以下是如何達成的步驟:
label1
:當用戶在下拉選單中選擇不同的城市時,根據選擇的城市更新 label1
的文本。以下是你原本的代碼,添加了在 label1
中顯示縮寫的邏輯:
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 ASPNET20241004Controll
{
public partial class Form1_IntroControl : Form
{
// 創建一個字典來存儲城市與縮寫的對應關係
private Dictionary<string, string> cityAbbreviations = new Dictionary<string, string>
{
{ "台北", "TPE" },
{ "台中", "TCE" },
{ "高雄", "KHH" }
};
public Form1_IntroControl()
{
InitializeComponent();
//載入下拉選單
comboBox1.Items.Add("台北");
comboBox1.Items.Add("台中");
comboBox1.Items.Add("高雄");
comboBox1.SelectedIndex = 0;
}
private void button1_Click(object sender, EventArgs e)
{
DateTime DT = DateTime.Now;
textBox1.Text = DT.ToLongDateString();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
// 此處可根據需要添加邏輯
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
// 取得下拉選單的選項文字
string selectedItem = comboBox1.SelectedItem.ToString();
// 將選擇的文字內容加入至 label2
label2.Text = selectedItem;
// 根據選擇的城市更新 label1
if (cityAbbreviations.TryGetValue(selectedItem, out string abbreviation))
{
label1.Text = abbreviation;
}
}
private void label1_Click(object sender, EventArgs e)
{
// 此處的邏輯不再需要,因為已在 comboBox1_SelectedIndexChanged 中處理
}
}
}
cityAbbreviations
的字典,將城市名稱與其縮寫對應起來。label1
:在 comboBox1_SelectedIndexChanged
方法中,當用戶選擇不同的城市時,我們使用 TryGetValue
方法獲取對應的縮寫並顯示在 label1
中。這樣一來,當用戶選擇不同的城市時,label1
會自動顯示相應的縮寫。