Click here to Skip to main content
15,891,674 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
I want to know that when I type a first character in combo box it should display all item which are start that character and the character remains in combo box text edit.

HTML
xmlns:myControl="clr-namespace:Enrollment.Controls"
<myControl:AutoCompleteComboBox Grid.Row="7" Grid.Column="1" SelectedValue="{Binding Path=SelectedCurrentCity}" ItemsSource="{Binding Path=CurrentCityList}">

I have added a control
HTML
<UserControl x:Class="Enrollment.Controls.AutoCompleteComboBox"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  >
    <Canvas>
        <TextBox x:Name="autoTextBox"  Height="25" MinWidth="240" TextWrapping="NoWrap"></TextBox>
        <ComboBox MinWidth="240" x:Name="suggestionListBox" Margin="0,25,0,-25" removed="LightYellow" 
                 Visibility="Collapsed" SelectionChanged="suggestionListBox_SelectionChanged" />
    </Canvas>
</UserControl>

C#
public Windows2()
{
fillCurrentCityList();
}
public fillCurrentCityList ()
{
CurrentCityList = new List<string>();
            string tt1 = CurrStateIDcmb.SelectedValue.ToString();
            string str1 = "Select CityName from mstCity where StateId = (Select StateId from mstState where StateName =@tt1)";
            SqlConnection cn2 = new SqlConnection(@"Data Source=SUMIT\SQLEXPRESS;AttachDbFilename='C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\Enrollment.mdf';Integrated Security=True");

            SqlCommand cmd2 = new SqlCommand(str1, cn2);
            cn2.Open();

       
            cmd2.Parameters.AddWithValue("@tt1", CurrStateIDcmb.SelectedValue.ToString());


            SqlDataReader dm;
            try
            {

                dm = cmd2.ExecuteReader();
                while (dm.Read())
                {
                
                
                    CurrentCityList.Add(dm["CityName"].ToString());


                }

            }

            catch (Exception ex)
            {
               
            }

            finally
            {
                cn2.Close();
            }
}



 public partial class AutoCompleteComboBox : UserControl
    {
        #region Constructor
        public AutoCompleteComboBox()
        {
            InitializeComponent();
            // Attach events to the controls
            autoTextBox.TextChanged +=
                new TextChangedEventHandler(autoTextBox_TextChanged);
            autoTextBox.PreviewKeyDown +=
                new KeyEventHandler(autoTextBox_PreviewKeyDown);
            suggestionListBox.SelectionChanged +=
                new SelectionChangedEventHandler(suggestionListBox_SelectionChanged);
        }
        #endregion
        #region Properties

        /// <summary>
        /// Gets or sets the items source.
        /// </summary>
        /// <value>The items source.</value>
        public IEnumerable<string> ItemsSource
        {
            get 
            { 
                return (IEnumerable<string>)GetValue(ItemsSourceProperty);
            }
            set { SetValue(ItemsSourceProperty, value); }
        }

        // Using a DependencyProperty as the backing store for ItemsSource.  
        // This enables animation, styling, binding, etc...
        public static readonly DependencyProperty ItemsSourceProperty =DependencyProperty.Register("ItemsSource"
                                , typeof(IEnumerable<string>)
                                , typeof(AutoCompleteComboBox)
                                , new UIPropertyMetadata(null));

        /// <summary>
        /// Gets or sets the selected value.
        /// </summary>
        /// <value>The selected value.</value>
        public string SelectedValue
        {
            get { return (string)GetValue(SelectedValueProperty); }
            set { SetValue(SelectedValueProperty, value); }
        }

        // Using a DependencyProperty as the backing store for SelectedValue.  
        // This enables animation, styling, binding, etc...
        public static readonly DependencyProperty SelectedValueProperty =
            DependencyProperty.Register("SelectedValue"
                            , typeof(string)
                            , typeof(AutoCompleteComboBox)
                            , new UIPropertyMetadata(string.Empty));

        #endregion


        #region Methods
        /// <summary>
        /// Handles the TextChanged event of the autoTextBox control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The instance containing the event data.</param>
        void autoTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            // Only autocomplete when there is text
            if (autoTextBox.Text.Length > 0)
            {
                // Use Linq to Query ItemsSource for resultdata
                string condition = string.Format("{0}%", autoTextBox.Text);
                IEnumerable<string> results = ItemsSource.Where(delegate(string s){return s.ToLower().StartsWith(autoTextBox.Text.ToLower());
                }
                );

                if (results.Count() > 0)
                {
                    suggestionListBox.ItemsSource = results;
                    suggestionListBox.Visibility = Visibility.Visible;
                }
                else
                {
                    suggestionListBox.Visibility = Visibility.Collapsed;
                    suggestionListBox.ItemsSource = null;
                }
            }
            else
            {
                suggestionListBox.Visibility = Visibility.Collapsed;
                suggestionListBox.ItemsSource = null;
            }
        }

        /// <summary>
        /// Handles the PreviewKeyDown event of the autoTextBox control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The instance containing the event data.</param>
        void autoTextBox_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Down)
            {
                if (suggestionListBox.SelectedIndex < suggestionListBox.Items.Count)
                {
                    suggestionListBox.SelectedIndex = suggestionListBox.SelectedIndex + 1;
                }
            }
            if (e.Key == Key.Up)
            {
                if (suggestionListBox.SelectedIndex > -1)
                {
                    suggestionListBox.SelectedIndex = suggestionListBox.SelectedIndex - 1;
                }
            }
            if (e.Key == Key.Enter || e.Key == Key.Tab)
            {
                // Commit the selection
                suggestionListBox.Visibility = Visibility.Collapsed;
                e.Handled = (e.Key == Key.Enter);
            }

            if (e.Key == Key.Escape)
            {
                // Cancel the selection
                suggestionListBox.ItemsSource = null;
                suggestionListBox.Visibility = Visibility.Collapsed;
            }
        }

        /// <summary>
        /// Handles the SelectionChanged event of the suggestionListBox control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Controls.SelectionChangedEventArgs"/> instance containing the event data.</param>
        private void suggestionListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (suggestionListBox.ItemsSource != null)
            {
                autoTextBox.TextChanged -= new TextChangedEventHandler(autoTextBox_TextChanged);
                if (suggestionListBox.SelectedIndex != -1)
                {
                    autoTextBox.Text = suggestionListBox.SelectedItem.ToString();
                }
                autoTextBox.TextChanged += new TextChangedEventHandler(autoTextBox_TextChanged);
            }
        }

        #endregion
    }


Exception in autoTextBox_TextChanged
ItemsSource shows null
http://screencast.com/t/ObdoUxAmW[^]
Posted
Updated 10-Apr-13 3:38am
v7
Comments
Prasad Khandekar 10-Apr-13 1:25am    
Isn't this the sarandard behavior of the ComboBox.

 
Share this answer
 
C#
public fillCurrentCityList ()
{
CurrentCityList = new List<string>();
            string tt1 = CurrStateIDcmb.SelectedValue.ToString();
            string str1 = "Select CityName from mstCity where StateId = (Select StateId from mstState where StateName =@tt1)";
            SqlConnection cn2 = new SqlConnection(@"Data Source=SUMIT\SQLEXPRESS;AttachDbFilename='C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\Enrollment.mdf';Integrated Security=True");
 
            SqlCommand cmd2 = new SqlCommand(str1, cn2);
            cn2.Open();
 
       
            cmd2.Parameters.AddWithValue("@tt1", CurrStateIDcmb.SelectedValue.ToString());
 
this.DataContext = this;  //this is the solution
            SqlDataReader dm;
            try
            {
 
                dm = cmd2.ExecuteReader();
                while (dm.Read())
                {
                
                
                    CurrentCityList.Add(dm["CityName"].ToString());
 

                }
 
            }
 
            catch (Exception ex)
            {
               
            }
 
            finally
            {
                cn2.Close();
            }
}</string>
 
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