Reputation: 97
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;
This is the code for my Combobox
. How do I make it fetch the ID
of the SelectedItem
?
Upvotes: 4
Views: 24710
Reputation: 11
I know this is an old question, but here is another way to take information form the db to the comboBox.
private void userControl_Load(object sender, EventArgs e)
{
scon.Open(); //--DB Connection
string query = "SELECT * FROM AssetTypes"; //Query
SqlDataReader row;
SqlCommand scmd = new SqlCommand(query,scon);
row = scmd.ExecuteReader();
if (row.HasRows)
{
while (row.Read())
{
AssetTypeComboBox.Items.Add(row["AssetTypesName"].ToString());
}
}
scon.Close();
}
to get the ID:
int itemID = AssetTypeComboBox.SelectedIndex + 1; //returns the ID number in the DB. provided the ;list was not sorted.
worked like a charm for me, maybe it can help others in future if they are struggling and do not understand much.
Upvotes: 0
Reputation: 1
Get ID of item selected in WPF ComboBox
Country & State are your model classes.
code =>
Country country_selected = (Country)DDCountry.SelectedValue;
State state_selected = (State)DDState.SelectedValue;
int country_id = country_selected.country_id;
int state_id = state_selected.state_id;
Upvotes: 0
Reputation: 2294
Here is what I got done:
comboBoxPickupLoc.DataSource = pickupLocationRepo.GetPickupLocations();
comboBoxPickupLoc.DisplayMember = "LocationName";
comboBoxPickupLoc.ValueMember = "Id";
comboBoxPickupLoc.SelectedIndex = -1;
and then you can get the Id value as shown below
object value = comboBoxPickupLoc.SelectedValue;
MessageBox.Show(value.ToString());
Thanks.
Upvotes: 1
Reputation: 168
When ever I am grabbing the SelectedIndex
value, I am doing so to place the id
into another DataBase
for various reasons. I have used the TryParse to do this task but the line below is about as simple as it gets by pulling it as a string rather than parcing to an int.
string id = combobox.SelectedValue.ToString();
Upvotes: 0
Reputation: 39956
You need to use SelectedValue
and int.TryParse
method. Like this:
int id;
bool result = int.TryParse(cbbilar.SelectedValue.ToString(), out id);
Upvotes: 3