本文介绍了如何在组合框中的项目上获取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();

推荐答案

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!


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


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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 20:36