如何在组合框中的项目上获取ID [英] how to get ID on an item in combo box

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

问题描述

您好,我想在c#的组合框中获取所选项目的ID.
我尝试了以下代码并获取了所选项目的值,但没有从数据库中获取ID的任何想法.

hello, i wanted to get ID of an selected item in combo box in c#.
i tried the following code and getting the value of selected item, but haven''t any idea to get ID from database.

int ProductIndex = ProductsComboBox.SelectedIndex;
      string productName = ProductsComboBox.Items[ProductIndex].ToString();

推荐答案

I假设您的ProductsComboBox包含的任何类都覆盖了ToString,以使您可以人工读取值.如果是这样,则只需将对象强制转换为您的类:
I assume that whatever class your ProductsComboBox contains has overridden ToString, to give you the human readable value. If so, then just cast the object to your class:
int ProductIndex = ProductsComboBox.SelectedIndex;
MyClass selected = ProductsComboBox.Items[ProductIndex] as MyClass;
if (selected != null)
   {
   string productName = selected.ProductName;
   ...
   }

或更好:

MyClass selected = ProductsComboBox.SelectedItem as MyClass;
if (selected != null)
   {
   string productName = selected.ProductName;
   ...
   }

大概是您的类已经包含ID!

Presumably, your class contains the ID already!


绑定到组合框时,请使用display member property将名称和valuemember属性显示给ID.

When binding to combobox use display member property to display name and valuemember property to Id.

CmbProduct.DataSource=datatable1;
CmbProduct.DisplayMember="ProductName";
CmbProduct.ValueMember="ProductId;
CmbProduct.DataBind();




然后在组合框中选择的索引已更改,




Then in combobox selected index changed,

int ProductIndex = ProductsComboBox.SelectedIndex;//this will give index
string productName = ProductsComboBox.Text.ToString()//this will give DIsplay name;
int ProductId=ProductsComboBox.SelectedValue.ToString();//this will give product Id


在sqlServer中创建一个具有两列的表.将您的表另存为myTable.一列产品",并将其命名为PRODUCT.另一个用于存储ProductID的列(名为ID)为char.并使用以下代码从数据库中读取.

create a table in sqlServer with two columns. Save your Table as myTable. One column for Product and name it PRODUCT as char. And the other column for storing ProductID named ID as char. And use below code to read from database.

SqlConnection con=new SqlConnection("Connection string");

SqlCommand cmd=new SqlCommand("SELECT ID FROM myTable WHERE PRODUCT='" + ProductsComboBox.Items[ProductIndex].ToString()+"'");

if (con.State == ConnectionState.Closed)
     con.Open();

SqlDataReader rdr = cmd.ExecuteReader();          
while (rdr.Read())
{
     string strID=(string)rdr["ID"];
}



那么strID将是您产品的ID.



then strID will be the ID of your product.


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

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