Click here to Skip to main content
15,896,063 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello,

I have a combo box in WPF project page. I have several items in it and one of the items is '(None)'.
Since my combo box is a compulsory field I would like to force validation on the combo box and wish to throw new Validation error if '(None)' is selected which gives red border around the combo box, just like on text box validation.

Your guidance will be of great help as I am very new to WPF.

Thank you.
Posted
Updated 1-Dec-12 2:25am
v2

C#
private void button1_Click(object sender, RoutedEventArgs e)
      {
          foreach (ComboBoxItem i in comboBox1.Items)
          {
              if (i.IsSelected)
              {
                  // perform you desired your operations
              }
              else
              {
                  // throw validation messages
              }
          }
      }
 
Share this answer
 
Comments
xrndMember 1-Dec-12 7:20am    
How to throw validation error message for combo box,that is new ValidationError..
I have written
ValidationError validationError = new ValidationError(new ComboBoxError(),
mytext.GetBindingExpression(ComboBoxItem.ContentProperty), "Field Empty", null);
Validation.MarkInvalid(mytext.GetBindingExpression(ComboBoxItem.ContentProperty), validationError);

which doesnt work as desired.
Hi dear,
Read this message.

if(comboBox1.SelectedValue == null)
{
 // Validation message. 
 //errorProvider1.SetError(comboBox1, "comboBox value is required.");
}
else
{
 // Continue you desire work.
}
 
Share this answer
 
v4
C#
if(combobox1.selectedindex==0)
{
     //Validation error
}
else
{
    //True condition...
}


Thanks & regard
Sham:)
 
Share this answer
 
v3
Hey hi ,
I have finally found the solution.

I was supposed to bind my ComboBox text property with The validation error..
And then I provided the Buizness rule by simply creating the class in c#.
Yeah the Validation wasn't meant to be done when Cursor leavs the combobox but when I impose FORCE VALIDATION on my control..

Code in Page.Resources

<cod>
XML
<ControlTemplate x:Key="ComboBoxValidationErrorTamplate">
            <DockPanel>
                <Border BorderBrush="Red" BorderThickness="2">
                    <AdornedElementPlaceholder />
                </Border>
            </DockPanel>
        </ControlTemplate>




Code For Control (ComboBox)
XML
<combobox grid.row="2" height="23" horizontalalignment="Left" margin="6">
                  x:Name="cmbType" VerticalAlignment="Top" Width="168" Grid.Column="3"
                  Validation.ErrorTemplate="{StaticResource ComboBoxValidationErrorTamplate}"  Validation.Error="NumberError">
            <combobox.text>
                <binding path="Type" notifyonvalidationerror="True" mode="OneWayToSource">
                    <binding.validationrules>
                        <exceptionvalidationrule />
                    </binding.validationrules>
                </binding>
            </combobox.text>
            
            <comboboxitem content="(None)" />
            <comboboxitem content="Electrical" />
           
        </combobox>


Code in .cs file

        private void NumberError(object sender, ValidationErrorEventArgs e)
        {
            if (e.Action == ValidationErrorEventAction.Added)
            {
                ((System.Windows.Controls.Control)sender).ToolTip =         e.Error.ErrorContent.ToString();
            }
            else
            {
                ((System.Windows.Controls.Control)sender).ToolTip = "";
            }
        }

//Code for Force validation

 private void errorCheckComboBox(System.Windows.Controls.Control controlName)
        {
            var mytext1 = controlName as System.Windows.Controls.ComboBox;
            ComboBoxItem mytext = (ComboBoxItem)mytext1.SelectedItem;
            if (mytext.Content.ToString().Trim().Equals("(None)"))
            {
            new ValidationResult(false, "Selection is invalid.");
            ValidationError validationError =
   new ValidationError(new ComboBoxError(),
  controlName.GetBindingExpression(System.Windows.Controls.ComboBox.TextProperty), "Field Empty", null);
   validationError.ErrorContent = "Please Select Valid Option";
            Validation.MarkInvalid(
           controlName.GetBindingExpression(System.Windows.Controls.ComboBox.TextProperty),
               validationError);
                ErrorExists = true;
             }         }


//Combobox ValidationError 

public class ComboBoxError: ValidationRule
        {
       public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
            {
                if (value is ComboBoxItem)
                {
                    if (value.ToString().Equals("(None)"))
                    {
                        return new ValidationResult(false, "Selection is invalid.");

                    }
                    
                }
                else
                {
                    return new ValidationResult(true, null);
                }

                return new ValidationResult(true, null);
            }
        }

// Code to call Validation 
  errorCheckComboBox(cmbType);




This works abs fine nw!!
 
Share this answer
 

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