在组合框中选择正确的记录 [英] Select the correct record in a combobox

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

问题描述

在下面的代码中,我在一个组合框中加载一个记录列表。现在我想基于字段label.text更改SelectedValue的静态代码如何实现此代码?



SelectedValue = label.text



In the code below I load a list of records in a combo box. Now I want to change my static code for the SelectedValue based on a field label.text How do I implement this code?

SelectedValue = label.text

private void Land()
       {
          string queryBLand = "SELECT * FROM Landen";
          string BLand = CB_BezoekLand.Text;

           using (connection = new SqlConnection(connectionstring))
           using (SqlCommand command = new SqlCommand(queryBLand, connection))
           using (SqlDataAdapter adapter = new SqlDataAdapter(command))
           {
               try
               {
                   connection.Open();
                   DataTable Bland = new DataTable();
                   adapter.Fill(Bland);
                   CB_BezoekLand.DisplayMember = "Land";
                   CB_BezoekLand.ValueMember = "ID";
                   CB_BezoekLand.DataSource = Bland;
          //HELP   CB_BezoekLand.SelectedValue = "161";

                   CB_FactuurLand.DisplayMember = "Land";
                   CB_FactuurLand.ValueMember = "ID";
                   CB_FactuurLand.DataSource = Bland;
               }
               catch (Exception)
               {
                   CB_BezoekLand.Text = ("-");
                   MessageBox.Show("Er is een onbekende fout opgetreden. De door u ingevulde gegevens zijn niet verwerkt.", "*** | Error - E111", MessageBoxButtons.OK, MessageBoxIcon.Hand);
               }

           }

       }

推荐答案

只要您将现有值(源自ID字段)设置为SelectedValue,数据来自何处无关紧要。因此,如果label.text包含正确的值(例如161),则应从组合框中选择正确的项目。



如果ID为数值,例如int,您可以将文本转换为int并处理异常或使用 Int32 .TryParse方法(String,Int32)(系统) [ ^ ]。如果它是一些其他数字数据类型,如十进制,双倍等,同样适用。



所以请试试

As long as you set an existing value (originating from the ID field) to the SelectedValue, it doesn't matter where the data comes from. So if the label.text contains a proper value (e.g. 161) the correct item should be selected from the combo box.

If the value if the ID is numeric, for example int, you can cast the text to int and handle exceptions or use Int32.TryParse Method (String, Int32) (System)[^]. The same applies if it's some other numeric data type like decimal, double etc.

So have a try with
CB_BezoekLand.SelectedValue = (int)label.Text;



或更好


or better yet

int idValue;
if (int.TryParse(label.Text, out idValue)) {
   CB_BezoekLand.SelectedValue = idValue;
}


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

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