Click here to Skip to main content
15,065,644 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Only Specific word want to allow in c# textBox1 for insert
Button, it will check valid word is available in textbox or not,
if get the valid word then code will run otherwise code will stop

What I have tried:

C#
private void button1_Click(object sender, EventArgs e)
{

    if (textBox1.Text == "In Progress" OR "Resolved")
    {
        //my Code
        label1.Text = textBox1.text;

    }
    else
    {
        label1.Text = "Fill Valid word in Status, eg: In Progress or Resolved,";
        return;
    }
}
Posted
Updated 22-Aug-20 5:35am
v2
Comments
Richard MacCutchan 22-Aug-20 8:26am
   
What is the problem?
PIEBALDconsult 22-Aug-20 11:36am
   
Try a radio button instead.
BillWoodruff 23-Aug-20 0:53am
   
Will there ever be a variable number of "valid words phrases ?
BillWoodruff 23-Aug-20 22:49pm
   
If there are a distinct set of words the user can enter: why use a TextBox ? Use a ComboBox, or, Menu.

You don't use the word "OR" in C#, you use the logical OR operator "||" instead:
C#
private void button1_Click(object sender, EventArgs e)
{

    if (textBox1.Text == "In Progress" || textBox1.Text == "Resolved")
    {
        //my Code
        label1.Text = textBox1.text;

    }
    else
    {
        label1.Text = "Fill Valid word in Status, eg: In Progress or Resolved,";
        return;
    }
}
But a better idea is to do it the other way round:
C#
private void button1_Click(object sender, EventArgs e)
{

    if (textBox1.Text != "In Progress" && textBox1.Text != "Resolved")
    {
        label1.Text = "Fill Valid word in Status, eg: In Progress or Resolved,";
        return;
    }
    // Your  Code
    label1.Text = textBox1.text;
}
That way, you keep your validations at the top of the method where it is easy to see what is required, and the rest of the method isn't further indented.
   
v2
Comments
BillWoodruff 23-Aug-20 0:50am
   
"validations at the top of the method" Amen ! +5
Another approach is:
C#
private void button1_Click(object sender, EventArgs e)
{

    if (textBox1.Text == "In Progress" ) {}
    elseif (textBox1.Text == "Resolved") {}
    elseif (textBox1.Text == "third") {} // third key word
    else
    {
        label1.Text = "Fill Valid word in Status, eg: In Progress or Resolved,";
        return;
    }
    //my Code
    label1.Text = textBox1.text;

}

may be easier to handle more keywords.
   

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