Click here to Skip to main content
15,892,927 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have four texboxes on click of add button the data in the textboxes should be added into a listbox,next time when i add the data, validation has to be done with respect to one textbox whether same data is present in listbox("No database involved in this")??


thanks in advance,
Posted
Updated 22-Mar-11 22:29pm
v2

You can use listbox.Items.Add ( http://msdn.microsoft.com/en-us/library/system.windows.controls.itemcollection.add.aspx[^] ) to add a new item to the list.

To test the existence you can use for example a simple LINQ query to check if the text already exists in the colection, something like (modify according to your needs):
C#
var AmIThere = from item in listbox.Items
               where item.ToString() == "SomeText" //most likely some variable here
               select item;

if (AmIThere.Count() = 0) {
...
 
Share this answer
 
add this code on the add button click event.
assuming your textbox's name is textBox1 and the listbox's name is listBox1.
C#
string[] contents = new string[4]
{
    textBox1.Text,
    textBox2.Text,
    textBox3.Text,
    textBox4.Text
};


foreach (string content in contents)
{

    bool isValid = true;
    foreach (string item in listBox1.Items)
    {
        if (item == content)
        {
            MessageBox.Show("Already in the list.");
            isValid = false;
        }
    }

    if (isValid)
        listBox1.Items.Add(content);
}
 
Share this answer
 
v2
Comments
girish sp 23-Mar-11 4:38am    
i want to compare only textbox1 contents,if it exists in the list or not,others may repeat...there exists the prob..i thought of splitting each content and then add into array,and when i click the add button next time it should check for textbox1 contents with the listbox..can this be done
girish sp 23-Mar-11 4:38am    
thanks for ur reply..
Micha3ldg 24-Mar-11 2:44am    
yes that can be done. I'm not clear about what you want to do. as for my understanding, only the contents in textbox1 should be validated if it exist in listbox or not? and the textbox from 2,3,4 can be add without validation.I am correct? if so. try to use this code

listBox1.Items.Add(textBox2.Text);
listBox1.Items.Add(textBox3.Text);
listBox1.Items.Add(textBox4.Text);

string content = textBox1.Text
bool isValid = true;
foreach (string item in listBox1.Items)
{
if (item == content)
{
MessageBox.Show("Already in the list.");
isValid = false;
}
}

if (isValid)
listBox1.Items.Add(content);

or play with those codes.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900