簡體   English   中英

如何在C#中的組合框中檢查用戶輸入

[英]How to check user input in combobox in c#

我有一個從名為class1的類填充的ComboBox,然后從該類創建了名為obj的對象,我使用SqlDataReader

combobox1.DataSource = obj.Myfunction();
combobox1.ValueMember = "ID";
combobox1.DisplayMember = "Name";

並且用戶還可以在ComboBox中寫我要檢查用戶輸入是否在ComboBox項中

if( comboBox1.Items.Contains(comboBox1.Text) )
   //do something
else
{
  MessageBox.Show("The comboBox1 contains new value");
}

但結果錯誤

我不想使用其他方法,例如SqlDataAdapter

謝謝先進

更新

作為臨時解決方案,我使用了這段代碼

int m = combobox1.SelectedIndex;
if (((class1)combobox1.Items[m]).Name.ToString() == combobox1.Text)
{
}
else
{
 MessageBox.Show("The comboBox1 contains new value");
}

再次感謝你

我的解決方案有點冗長,但這可以解決您的問題

        int count = 0;
        for (int i = 0; i < comboBox1.Items.Count; i++)
        {
            string value = comboBox1.GetItemText(comboBox1.Items[i]);
            if (value.Contains(comboBox1.Text))
            {
                count++;
                break;
            }
        }

        if (count > 0)
        {
            //do something
        }
        else
        {
            MessageBox.Show("The comboBox1 contains new value");
        }

這段代碼非常簡單易懂,但是您可以使用LINQ來縮短代碼。

我猜這里,但我想從

obj.Myfunction();

(您要設置為數據源的)不是List<string> ,因此,當檢查combobox的內部集合是否包含string (從comboBox1.Text返回)時,它不包含字符串,而是一個對象。 因為這兩個總是不同的( objectstring ),所以它總是錯誤的。

您是否嘗試過將數據源設置為字符串列表?

Items是ItemCollection,而不是字符串列表。 在您的情況下,它是ComboboxItem的集合,您需要檢查其Content屬性。

comboboxId.Items.Cast<ComboBoxItem>().Any(com=> com.Content.Equals("Your string"));

我假設您正在使用您的類類型的列表綁定到組合。

您應針對組合框的來源進行驗證,例如-

        List<ClassType> cboSource = comboBox1.DataSource as List<ClassType>;
        var itemAlreadyThere = cboSource.Any(a => a.Name == comboBox1.Text);

        if (itemAlreadyThere)
        {
            MessageBox.Show("The comboBox1 contains old value");
        }
        //do something
        else
        {
            MessageBox.Show("The comboBox1 contains new value");
        }

作為建議,不要強制轉換組合數據源,而應使用私有變量,然后將其填充並用於綁定到組合和進行驗證

幾個月前,我有這種行為。

我用類數據填充了一個組合框

class MyValue
{
  public string ID { get; set; }
  public string prop1 { get; set; }
  public string prop2 { get; set; }
  public int Value { get; set; }

  public static List<MyValue> Get()
  { 
    //create a list of MyValues and return it
    return new List<MyValue>();
  }
}

在GUI中:

mycombo.ValueMember = "ID";
mycombo.DisplayMember = "prop1";
mycombo.DataSource = MyValue.Get();

之后,我將selectedvalue作為屬性:

public MyValue SelectedValue
{
  get
  {
    if(mycombo.SelectedValue is MyValue)
      return (MyValue)mycombo.SelectedValue);
    else
    {
      MessageBox.Show(string.Format("{0} as new value", mycombo.SelectedText));
      return new MyValue{prop1 = mycombo.SelectedText};
    }
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM