WPF C# - Combobox数据到数据库的编号

时间:2014-11-15 22:38:30

标签: c# wpf database combobox

我在c#代码中设置了组合框数据,我想用数字而不是组合框中的文本写入数据库;比如我想:

1 - 仅查看= 1

2 - 基本用户= 2

3 - 主管= 3

4 - 管理员= 4

5 - 超级用户= 5

我不知道该怎么做。以下是我到目前为止所做的事情。

private void ComboBox_Loaded(object sender, RoutedEventArgs e)
{
    // ... A List.
    List<string> data = new List<string>();
    data.Add("1 - View Only");
    data.Add("2 - Basic User");
    data.Add("3 - Supervisor");
    data.Add("4 - Administrator");
    data.Add("5 - Super User");

    // ... Get the ComboBox reference.
    var comboBox = sender as ComboBox;

    // ... Assign the ItemsSource to the List.
    comboBox.ItemsSource = data;

    // ... Make the first item selected.
    comboBox.SelectedIndex = 0;
}

private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    // ... Get the ComboBox.
    var comboBox = sender as ComboBox;

    // ... Set SelectedItem as Window Title.
    string value = comboBox.SelectedItem as string;
    this.Title = "Selected: " + value;
}

总结一下我的理想结果 - 当有人从组合框中选择“1 - 仅查看”时,它会将数据库中的用户级别设置为1.

谢谢

1 个答案:

答案 0 :(得分:0)

对于简单化的东西,您可以使用comboBox.SelectedIndex + 1,但如果您的商品订单以某种方式发生变化,这将会失效。

对于更精细的内容,您可以执行以下操作:

namespace ComboBoxExampleWPF
{
    class UserLevel
    {
        public UserLevel(int level, string description)
        {
            Level = level;
            Description = description;
        }

        public int Level { get; private set; }
        public string Description { get; private set; }

        // This controls how it shows up in the comboBox
        public override string ToString()
        {
            return Level.ToString() + " - " + Description;
        }
    }

    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            List<UserLevel> list = new List<UserLevel>()
            {
                new UserLevel(1, "View Only"),
                new UserLevel(2, "Basic User"),
                new UserLevel(3, "Supervisor"),
                new UserLevel(4, "Administrator"),
                new UserLevel(5, "Super User")
            };

            comboBox1.ItemsSource = list;
            comboBox1.SelectionChanged += comboBox1_SelectionChanged;
        }

        void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // ... Get the ComboBox.
            var comboBox = sender as ComboBox;

            // ... Set SelectedItem as Window Title.
            UserLevel value = comboBox.SelectedItem as UserLevel;
            this.Title = "Selected: " + value.ToString();

            SetUserLevel(value);
        }

        private void SetUserLevel(UserLevel ul)
        {
            // _myDatabase.SetUserLevel(ul.Level);
        }
    }
}