是否可以在 c# Web 应用程序的 comobox 中选择数据类型

本文关键字:comobox 选择 数据类型 应用程序 Web 是否 | 更新日期: 2023-09-27 17:56:27

我是一个c#初学者,在Visual Studio-2010中使用Silver Light-5进行Web开发。我在运行我的代码时有我的 GUI,它是由 xaml 创建的 GUI,按钮单击是在 c# 中处理的。

现在我要做的是:(我有2个问题)

(1)第一个是:我正在尝试创建一个 GUI,在其中我使用组合框,其中将包含这样的选项(请参阅此链接) http://prntscr.com/36l58s 在此链接中,我在 5 种给定datatypes(字节、字节、短、整型、长)中选择一种数据类型。之后,我想将此数据类型分配给 c# 代码中的variable,如下所示:(假设我在其中选择了"short")

comboBox1.Items.Add("short");
var itemType = comboBox1.SelectedItem.GetType(); //This "itemType" contains "short" now
itemType variable = 10; //  **THIS LINE GIVES ERROR**

如何在combo box中为这个"vraibale"分配选定的数据类型?

(2)第二个是:当我选择"short"(或任何数据类型)时,它会再次重复在组合框中添加数据类型。例如,当我选择"短"(或任何)时。我得到了这个 http://prntscr.com/36l6om,如果我再次选择"多头",我会选择这个 http://prntscr.com/36l75y

我的xml代码要实现的是这个

    <ComboBox Height="19" HorizontalAlignment="Left" Margin="25,209,0,0" Name="comboBox1" VerticalAlignment="Top" Width="120" SelectionChanged="comboBox1_SelectionChanged" Grid.ColumnSpan="3">
        <ComboBoxItem />
        <ComboBoxItem />
    </ComboBox>

而 c# 代码是:

private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            comboBox1.Items.Add("byte");
            comboBox1.Items.Add("sbyte");
            comboBox1.Items.Add("short");
            comboBox1.Items.Add("int");
            comboBox1.Items.Add("long");
            var itemType = comboBox1.SelectedItem.GetType();   
        }

提前感谢您的帮助。

是否可以在 c# Web 应用程序的 comobox 中选择数据类型

首先,

comboBox1.SelectedItem.GetType();

会给你Type string

一种出路可能是开关盒

private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
        switch( comboBox1.SelectedItem as string  )
        {
            case "byte"://Create  a variable of byte and use it. 
                break;
            case "sbyte"://Create  a variable of sbyte and use it.
                break;
            case "short"://Create  a variable of short and use it.
                break;
            case "int"://Create  a variable of int and use it.
                break;
            case "long"://Create  a variable of long and use it.
            default:
                break;
        }
}

其次,将Items添加到InitializeConstructor方法内的combobox1,而不是 SelectionChanged 事件,这会导致重复添加。