Click here to Skip to main content
15,887,027 members
Please Sign up or sign in to vote.
2.50/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.

Here's what I'm trying to achieve:

1. While entering values in any Textbox, duplication of a value already entered in any other TextBox is not allowed.

2. Duplication of exclamation mark (!) is allowed.

For Ex : If first textbox contains only 1 exclamation mark(!) then all other textbox can accept duplicate of exclamation mark.

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

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


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

        }

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

}
Posted
Updated 6-Nov-14 8:46am
v5
Comments
Thanks7872 6-Nov-14 2:29am    
This is not a question. Its just list of requirements. We are here to help you with the code you have tried.

I don't know why you expect some one to do something for you? If you do, then first you have to show the efforts you have made so far.
BillWoodruff 6-Nov-14 6:52am    
Well, this is the OP's first post on CP, and the post does have some code now. I think it's more valid than other "questions" we see here.
Thanks7872 6-Nov-14 8:14am    
Than we should report that posts also. Further, if such posts get deleted than OP can post it again without any issue. My point is, they will realise that there was something wrong with his post and will post better version.

If we will start tolerating such questions, believe me after some days this place will be full of just requirements,homeworks,code dumps. If some one is new to CP,then he should go through CP guidelines first. For that, he doesn't need extra efforts,just have a look at right pane while posting a question.

BillWoodruff 6-Nov-14 11:23am    
"if such posts get deleted than OP can post it again without any issue." This remark totally ignores the fact that for brand new users of CP "instant rejection" often is very discouraging, and, as in this case, with a little patience, and some comments, some will clarify the question and/or post code.
[no name] 6-Nov-14 4:12am    
Try and use regular expressions. Google best buddy. :)

You are on the right track - to an extent.
But...I'd build the list when I did the validation each time (otherwise you could include "old" strings in current tests if the user goes back and changes them.)
Multiple textboxes containing just "!" is allowed - so check that when you add them to your list:
C#
List<string> boxes = new List<string>();
foreach (Control c in Controls)
   {
   Textbox tb = c as TextBox;
   if (tb != null)
      {
      if (tb.Text != "!") boxes.Add(tb.Text);
      }
   }
Then, sort the list:
C#
boxes.Sort();
Now, if there are any duplicates, they are side-by-side in the list, so a simple loop through checking against the previous list entry will tell you if there are any duplicates:
C#
string last = "!";     // We know that boxes contains none of these
foreach (string s in boxes)
   {
   if (s == last)
      {
      MessageBox.Show("Duplicate: " + s);
      break;
      }
   last = s;
   }
 
Share this answer
 
Let me show you some ideas for the structure of a solution, and I'd like to see how far you can get writing the required code: I'm going to assume you have 12 TextBoxes, named TextBox1~TextBox12, in a Panel named 'TBPanel.

This uses a Dictionary<TextBox, string> to store the current .Text property of each TextBox.
C#
private const string Exclam = "!";

private TextBox leftTextBox;

private bool tbOneHasExclam = false;

private string leftTextBoxOldContent;

private string leftTextBoxNewContent;

private Dictionary<TextBox, string> dctTBToStr = new Dictionary<TextBox, string>();

private void YourMainForm_Load(object sender, EventArgs e)
{
    foreach (TextBox tb in TBPanel.Controls.OfType<textbox>())
    {
        // connect a 'Leave EventHandler
        tb.Leave += TextBoxes_Leave;

        // add to Dictionary
        dctTBToStr.Add(tb, String.Empty);
    }
}

private void TextBoxes_Leave(object sender, EventArgs e)
{
    leftTextBox = sender as TextBox;

    leftTextBoxOldContent = dctTBToStr[leftTextBox];
    leftTextBoxNewContent = leftTextBox.Text;
    
    // if the content hasn't changed, keep going
    if (leftTextBoxOldContent == leftTextBoxNewContent) return;

    // if the new content is "" then update and keep going
    if(leftTextBoxNewContent == String.Empty)
    {
        dctTBToStr[leftTextBox] = String.Empty;
        return;
    }

    // now the fun begins !
    CheckForDuplicateEntry();
}

private void CheckForDuplicateEntry()
{
    switch (leftTextBox.Name)
    {
        // TextBox1 has changed
        case "TextBox1":
            // update
            dctTBToStr[TextBox1] = leftTextBoxNewContent;

            // test for "!"
            tbOneHasExclam = leftTextBoxNewContent == Exclam;

            // if TextBoxOne is "" or "!"
            // we can keep going
            if (tbOneHasExclam || leftTextBoxNewContent == String.Empty) break;

            // what needs to happen here ?
            // we know that TextBox1 is not "!"
            // we need to find any other TextBoxes with
            // text of "!" and the one possible TextBox
            // where its text == TextBox1.Text

            // build a collection of TextBoxes to be cleared
            // in order to avoid getting a modify collection error:
            // we can't modify a Dictionary value in a 'for or 'foreach loop

            List<textbox> duplicates = null;

            foreach (TextBox tb in dctTBToStr.Keys)
            {
                // ignore what can be skipped over
                if (tb.Text == String.Empty || tb == TextBox1) continue;

                if (tb.Text == leftTextBoxNewContent || tb.Text == Exclam)
                {
                    duplicates.Add(tb);
                }
            }

            if (duplicates != null)
            {
                for (int i = 0; i < duplicates.Count; i++)
                {
                    TextBox duplicate = duplicates[i];
                    duplicate.Clear();
                    dctTBToStr[duplicate] = String.Empty; 
                }
            }
           break;

        // process change in all other TextBoxes
        default:

           // and now ... you write the code
           break;
    }
}
 
Share this answer
 
v2
I have solved this question myself.
// Using control class.
// this code is for 3 textboxes.

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
 
that's code very useful for u try it.

C#
RequiredFieldValidator1.ErrorMessage = "";
        Label9.Text = "";
        string name = TextBox7.Text.ToString();
       // string constr = "data Source=MURALY-PC\\SQLEXPRESS; database=Online; Integrated Security=SSPI";
       // SqlConnection con = new SqlConnection(constring);
        con.Open();
        string query = "select username from EMPP1 where username='" + TextBox7.Text+ "'";
        SqlCommand cmd = new SqlCommand(query, con);
        SqlDataReader dr = cmd.ExecuteReader();
        dr.Read();
        if (dr.HasRows)
        {
            Label11.Text = "user name is already exist";
            TextBox7.Text = "";
            dr.Close();
          
        }
        else
        {
            dr.Close();
            Label11.Text = "";
            Label11.Text = "username is available";
                     
        }
        con.Close();
 
Share this answer
 
v2
Comments
Rajesh waran 6-Nov-14 8:04am    
Hey @MohamedEliyas ,you are checking textbox text with your database values,but here the question is set to get validation to check all the textboxe's text should not have duplicate text.But he notice that similar text with exclamation mark (!) is allowed.So try to make correction in your solution.
MohamedEliyas 6-Nov-14 8:14am    
k k rajesh thnks for your information i will try it....

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