2016-09-28 4 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으로 캐스트 할 수 있습니다.

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 
} 

희망 도움이

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를 사용할 수는

관련 문제