获取在组合框中选择的项目的ID [英] Get ID of item selected in ComboBox

查看:52
本文介绍了获取在组合框中选择的项目的ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 ComboBox ,其中充满了数据库中的项目.我正在尝试获取在 ComboBox 中选择的项目的 ID ,但是我尝试过的任何方法似乎都无法正常工作.

I have a ComboBox that gets filled with items from my database. I'm trying to get the ID of the item that is selected in the ComboBox, but nothing I've tried seems to be working.

int id = cbbilar.SelectedIndex + 1;

这就是我现在的方式,它效率很低,如果删除了数据库中的第一项,它将停止工作

This is how I have it right now, it's very inefficient and stops working if the first items in the database are removed

var cars = (from z in db.Bilar 
            select new { Value = z.Id, Names = z.Marke.Namn + " "  + z.Namn }).ToList();
cbbilar.DataSource = cars;
cbbilar.DisplayMember = "Names";
cbbilar.ValueMember = "Value";
cbbilar.SelectedIndex = 0;

这是我的 Combobox 的代码.如何使其获取 SelectedItem ID ?

This is the code for my Combobox. How do I make it fetch the ID of the SelectedItem?

推荐答案

您需要使用 SelectedValue

You need to use SelectedValue and int.TryParse method. Like this:

int id;
bool result = int.TryParse(cbbilar.SelectedValue.ToString(), out id);

这篇关于获取在组合框中选择的项目的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆