2016-09-28 16 views
-2

ListBoxに追加する前に、入力可能な値をチェックしたいと思います。ListBoxに値がすでに存在するかどうかを確認するにはどうすればよいですか?

可能なエントリ値を含むTextBoxがあります。

ListBoxに既に値が含まれているかどうかを確認します。

  • この値が既に挿入されている場合:を追加しないでください。
  • もしそうでない場合は、それを追加してください。
+1

は、あなたが検索さや何かをしようとしたことがあり、助け?これはあなたの質問に追加するのが普通です。 – JTIM

+0

リストボックスで検索を実行するか、リストボックス内の項目をループして比較しようとしましたか? –

+0

私はプログラミングの新人だから、 'C#'のコードについてよくわからない –

答えて

2
if (!listBoxInstance.Items.Contains("some text")) // case sensitive is not important 
      listBoxInstance.Items.Add("some text"); 
if (!listBoxInstance.Items.Contains("some text".ToLower())) // case sensitive is important 
      listBoxInstance.Items.Add("some text".ToLower()); 
+0

これは役に立ちました: –

+0

yw!がんばろう!! –

0

ちょうどあなたが探している値を一覧表示します内の項目を比較します。アイテムをStringにキャストできます。

if (this.listBox1.Items.Contains("123")) 
{ 
    //Do something 
} 

//Or if you have to compare complex values (regex) 
foreach (String item in this.listBox1.Items) 
{ 
    if(item == "123") 
    { 
     //Do something... 
     break; 
    } 
} 
0

あなたはLINQを使用することができ、

bool a = listBox1.Items.Cast<string>().Any(x => x == "some text"); // If any of listbox1 items contains some text it will return true. 
if (a) // then here we can decide if we should add it or inform user 
{ 
    MessageBox.Show("Already have it"); // inform 
} 
else 
{ 
    listBox1.Items.Add("some text"); // add to listbox 
} 

ホープ

関連する問題