Click here to Skip to main content
15,887,676 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
I have 12 text boxes, and I am trying to find a strategy to not permit duplicate entries in the TextBoxes by the user at run-time.

Help me out is these, IF my approach is wrong please suggest me better way with code :

C#
List<string> lstTextBoxes = new List<string>();

private void Textbox1(object sender, EventArgs e)
{
   lstTextBoxes.Add(Textbox1.Text);
}


C#
public bool lstCheck(List<string> lstTextBoxes,string input)
        {
            if(lstTextBoxes.Contains(input))
            {
                return true;
            }
            else
            {
                return false;
            }

        }

        private void Textbox2(object sender, EventArgs e)
        {
            lstTextBoxes.Add(Textbox2.Text);
            if (lstCheck(lstTextBoxes, Textbox2.Text))
            {
                MessageBox.Show("test");
            }
        }

}
Posted
Updated 7-Nov-14 7:14am
v3
Comments
BillWoodruff 7-Nov-14 2:12am    
You posted the same question 13 hours before you posted this duplicate, and received three answers. Why did you post it again ?

You can always edit/revise your original question to include new information. Reposting will get you down-voted and/or reported here.
Gaurav Janjalkar 7-Nov-14 2:30am    
sorry i am new on CP .i don't know how to use it

Instead of List, use System.Collections.Generic.HashSet<T>:
http://msdn.microsoft.com/en-us/library/bb359438%28v=vs.110%29.aspx[^].

[EDIT]

Each time you get a new element of a set of values, add it to the instance of the hash set: http://msdn.microsoft.com/en-us/library/bb353005(v=vs.110).aspx[^].

But, before doing it, you check up of this element is already added, so you need to add it only if it is not yet there. Here is how you check it up: http://msdn.microsoft.com/en-us/library/bb356440(v=vs.110).aspx[^].

Actually, you may need to make some redundancy and add an element anywhere else, for example in a list, if you need to keep the order in which the elements was added (natural historical order). If it does not matter, you can use hash set, because it implements enumeration, through the foreach loop.

[END EDIT]

If would make time complexity for your search for duplicate of O(1) (asymptotically, not depending on the number of data items).
See also:
http://en.wikipedia.org/wiki/Big_O_notation[^],
http://en.wikipedia.org/wiki/Asymptotic_analysis[^],
http://en.wikipedia.org/wiki/Time_complexity[^].

—SA
 
Share this answer
 
v2
Comments
Manas Bhardwaj 6-Nov-14 15:43pm    
Agree +5!
Sergey Alexandrovich Kryukov 6-Nov-14 15:44pm    
Thank you, Manas.
—SA
PIEBALDconsult 6-Nov-14 17:08pm    
HashSet FTW! +5
Sergey Alexandrovich Kryukov 6-Nov-14 17:14pm    
Thank you very much. (I did not understand your acronym. May be because it reads backward pretty well. :-)
—SA
BillWoodruff 7-Nov-14 2:01am    
I know that I would appreciate your adding a brief explanation of how you would USE a HashSet in this case; and, I would hypothesize the OP would also. Note that this post is a re-post of a post made 13 hours before this one.
First of all, Sergey's answer is very good!
Secondly, see our discussion to the Sergey's answer.
Thirdly, my advice is to add common event handler for each textbox. How? Please, see Code: Adding Controls at Run Time (Visual C#)[^]
Fourtly, inside event handler use code:
C#
TextBox tb = (TextBox)sender;
if (!lstTextBoxes.Contains(tb.Text))
{
    lstTextBoxes.Add(tb.Text);
}
else
{
    MessageBox.Show("Is duplicate value!");
}


It should be enough!
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 7-Nov-14 15:08pm    
This is a good idea, but 1) you need to explain what event should be added (and how, in case OP needs it; see next item); 2) ugly code sample doesn't use anonymous handler where the use of named method is totally pointless; 3) it's better to abstract out some Add(string) method, so the detail of adding (what collections to use, etc.) could be decided separately.
—SA
Maciej Los 7-Nov-14 15:18pm    
Thank you, Sergey. In case of OP comments, i'll try to improve my answer.
In the meanwhile i spend a time with my friends watching on tv "Dancing with the Stars" - Polish edition ;)
Sergey Alexandrovich Kryukov 7-Nov-14 15:26pm    
I have a habit to watch the similar show from Ukraine, like them. In particular, their "Танцуют все" is their form of US "So You Think You Can Dance?", maybe the best. I saw people from many countries taking for an honor to come for this show (from what I remember, dancers from Russia, Armenia, Brazil, Great Britain, India, Turkey, Siria, Belasus, Kyrgyzstan...)
Maybe this is so successful due to enormously friendly and open-hearted people, organizers and jury, high qualification and demanding, really challenging requirements...
—SA
Maciej Los 7-Nov-14 15:49pm    
I saw it on youtube ;)
I'm bit sentimental... quite often searching internet sites for Russian-based music, culture, etc. Do you remember Yurii Shatunov and his White Roses ("Bielye Rosy")? My favorite! I'm living in Podlasie region of Poland. We call it: multi-culture region. Here lives: Russians, Belarusians, Juwes, Tatars, and many others.
Sergey Alexandrovich Kryukov 7-Nov-14 16:02pm    
I didn't no your region is special in this respect.
By the way, there is a lot of interesting in Russia, in musics. Enormous revival of so called authentic performance, especially Barocco, collaboration with best European collectives, new folk and world music, and a lot more. And I was especially excited about sings of revival of Russian 7-string guitar. Did you ever listened it? There are new young musicians you can watch on youtube.
By the way, we recently watched Nord-Ost with my daughter, the same very Nord-Ost; do you know what I mean?
—SA
You can try to create a single StackPanel for all of the TextBoxes. For example this way,

C#
// create a stackpanel
StackPanel panel = new StackPanel();
panel.Name = "myPanel";
// run a loop 12 times
for (int i = 0; i < 13; i++ ) {
  // creates a new textBox
  TextBox textBox = new TextBox();
  // adds it to the StackPanel
  panel.Children.Add(textBox);
}


You can also use the XAML for doing this type of job, if you like so.

You can then use the Children property of the MainWindow's grid, make sure that you've given that grid a name, for example

XML
<Grid name="mainGrid">


The program logic would be something like,

C#
foreach (StackPanel childPanel in mainGrid.Children.OfType<stackpanel>()) {
  // might run once, or multiple times depending on your need.
  if(childPanel.Name == "myPanel") {
    // we want our panel to work on
    int index = 0;
    int index2 = 0;
    foreach (TextBox box in childPanel.Children.OfType<textbox>()) {
      // inside that panel, for each of the TextBox
      // check the value against each textbox

      // this is the first child
      index++;
      foreach (TextBox aBox in childPanel.Children.OfType<textbox>()) {
        // increment the second index
        index2++;
        if(index != index2) {
          // 2 different controls, check their values
          if(box.Text == aBox.Text) {
            // there was a duplicate found,
            MessageBox.Show("Found a duplicate.");
            // break the loop, no need for more execution.
            break;
          }
        }
      }
    }
  }
}


A lot of headache, isn't it?
 
Share this answer
 
v3
// I have solved this same problem using this code .. And its working Properly.
// I used "contol" class.
// This code is for 3 textboxes.



C#
public partial class Form2 : Form
    {
        int totalCtrl = 3;
        public Form2()
        {
            InitializeComponent();
        }

        private void HCFA_21_Diag1_Leave(object sender, EventArgs e)
        {
            if (IsDuplicate("1")) 
            MessageBox.Show("Is duplicate value!");
        }

        private bool IsDuplicate(string keyedID)
        {

            bool isDuplicate = false;
            string fieldName =  "HCFA_21_Diag";
            Control ctrl = this.Controls[fieldName + keyedID];

            if (ctrl.Text != "!" && ctrl.Text != string.Empty)
            {
                for (int i = 1; i <= totalCtrl; i++)
                {
                    Control allCtrl = this.Controls[fieldName + i.ToString()];

                    if (ctrl.Text == allCtrl.Text && ctrl.Name != allCtrl.Name)
                    {
                        isDuplicate = true;
                        break;
                    }
                }
            }


            return isDuplicate;

        
        }

        private void HCFA_21_Diag2_Leave(object sender, EventArgs e)
        {
            if (IsDuplicate("2")) 
            MessageBox.Show("Is duplicate value!");
        }

        private void HCFA_21_Diag3_Leave(object sender, EventArgs e)
        {
             if (IsDuplicate("3")) 
            MessageBox.Show("Is duplicate value!");
        }


    }
}
 
Share this answer
 
v3

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