当我输入第一个字母时,如何在组合框中搜索 [英] how to search in combo box when I type first letter

查看:65
本文介绍了当我输入第一个字母时,如何在组合框中搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道当我在组合框中输入第一个字符时,它应该显示所有开始该字符的项目,并且字符保留在组合框文本编辑中。



 xmlns:myControl =clr-namespace:Enrollment.Controls
< myControl:AutoCompleteComboBox Grid.Row = 7 网格。列 = 1 SelectedValue = {Binding Path = SelectedCurrentCity} ItemsSource = < span class =code-keyword> {Binding Path = CurrentCityList} >



我添加了一个控件

 <   UserControl     x:Class   =  Enrollment.Controls.AutoCompleteComboBox  

xmlns = http://schemas.microsoft.com/winfx/2006/xaml/presentation

xmlns:x = http://schemas.microsoft.com/winfx/2006/xaml

>
< 画布 >
< < span class =code-leadattribute> TextBox x:名称 = autoTextBox 高度 = 25 MinWidth = 240 TextWrapping = NoWrap > < span class =code-keyword>< / TextBox >
< ComboBox MinWidth = 240 x:名称 = suggestionListBox 保证金 = 0,25,0,-25 已移除 = LightYellow

< span class =code-attribute> 可见性 = 折叠 SelectionChanged = suggestionListBox_SelectionChanged / >
< / Canvas >
< / UserControl > ;



  public  Windows2()
{
fillCurrentCityList();
}
public fillCurrentCityList()
{
CurrentCityList = new List< string>();
string tt1 = CurrStateIDcmb.SelectedValue.ToString();
string str1 = 从mstCity中选择CityName其中StateId =(从mstState中选择StateId,其中StateName = @ tt1);
SqlConnection cn2 = new SqlConnection( @ 数据源= 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;
尝试
{

dm = cmd2.ExecuteReader();
while (dm.Read())
{


CurrentCityList.Add(dm [< span class =code-string> CityName]。ToString());


}

}

catch (例外情况)
{

}

最后
{
cn2.Close() ;
}
}



public partial class AutoCompleteComboBox:UserControl
{
#region构造函数
public AutoCompleteComboBox()
{
InitializeComponent();
// 将事件附加到控件
autoTextBox.TextChanged + =
new TextChangedEventHandler(autoTextBox_TextChanged);
autoTextBox.PreviewKeyDown + =
new KeyEventHandler(autoTextBox_PreviewKeyDown);
suggestionListBox.SelectionChanged + =
new SelectionChangedEventHandler(suggestionListBox_SelectionChanged);
}
#endregion
#region属性

/// < ; 摘要 >
/// 获取或设置项目来源。
/// < / summary >
/// < value < span class =code-summarycomment>> 项目来源。< / value >
public IEnumerable< string> ItemsSource
{
get
{
return ( IEnumerable的<串GT)的GetValue(ItemsSourceProperty);
}
set {SetValue(ItemsSourceProperty, value ); }
}

// 使用DependencyProperty作为ItemsSource的后备存储。
// 这可以实现动画,样式,装订等......
public static readonly DependencyProperty ItemsSourceProperty = DependencyProperty.Register( ItemsSource
typeof (IEnumerable< string>)
typeof (AutoCompleteComboBox)
new UIPropertyMetadata( null ));

/// < 摘要 >
/// 获取或设置选定的值。
/// < / summary >
/// < value < span class =code-summarycomment>> 所选值。< / value >
public string SelectedValue
{
get { return )的GetValue(SelectedValueProperty); }
set {SetValue(SelectedValueProperty, value ); }
}

// 使用DependencyProperty作为SelectedValue的后备存储。
// 这可以实现动画,样式,装订等......
public static readonly DependencyProperty SelectedValueProperty =
DependencyProperty.Register( SelectedValue
typeof string
typeof (AutoCompleteComboBox )
new UIPropertyMetadata( string .Empty));

#endregion


#region方法
/// < 摘要 >
/// 处理autoTextBox控件的TextChanged事件。
/// < / summary >
/// < param < span class =code-summarycomment> name =sender > 来源事件。< / param >
/// < param name =e > 包含事件数据的实例。< / param >
void autoTextBox_TextChanged( object sender,TextChangedEventArgs e)
{
// 仅限有文本时自动填写
如果(autoTextBox.Text.Length > 0
{
// 使用Linq查询itemsSource以获取resultdata
字符串 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 ;
}
}

/// < 摘要 >
/// 处理autoTextBox控件的PreviewKeyDown事件。
/// < / summary >
/// < param < span class =code-summarycomment> name =sender > 来源事件。< / param >
/// < param name =e > 包含事件数据的实例。< / param >
void autoTextBox_PreviewKeyDown( object sender,KeyEventArgs e)
{
if (e.Key == Key.Down)
{
if (suggestionListBox.SelectedIndex < suggestionListBox.Items.Count)
{
suggestionListBox.SelectedIndex = suggestionListBox.SelectedIndex + 1 ;
}
}
如果(e.Key == Key.Up)
{
if (suggestionListBox.SelectedIndex > -1)
{
suggestionListBox.SelectedIndex = suggestionListBox .SelectedIndex - 1 ;
}
}
if (e.Key == Key.Enter || e.Key == Key.Tab)
{
// 提交选择
suggestionListBox.Visibility = Visibility .Collapsed;
e.Handled =(e.Key == Key.Enter);
}

if (e.Key == Key.Escape)
{
// 取消选择
suggestionListBox.ItemsSource = null < /跨度>;
suggestionListBox.Visibility = Visibility.Collapsed;
}
}

/// < 摘要 >
/// 处理suggestionListBox控件的SelectionChanged事件。
/// < / summary >
/// < param < span class =code-summarycomment> name =sender > 来源事件。< / param >
/// < param name =e > < 参见 cref =System.Windows.Controls.SelectionChangedEventArgs/ > 包含事件数据的实例。< / 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
}





autoTextBox_TextChanged中的异常

ItemsSource显示为null

http://screencast.com/t/ObdoUxAmW [ ^ ]

解决方案

请看这些例子:



1. 自动过滤WPF中的ComboBox [ ^ ]



2. 可重复使用的WPF自动完成文本框 [ ^ ]


  public  fillCurrentCityList()
{
CurrentCityList = new List< string>();
string tt1 = CurrStateIDcmb.SelectedValue.ToString();
string str1 = 从mstCity中选择CityName其中StateId =(从mstState中选择StateId,其中StateName = @ tt1);
SqlConnection cn2 = new SqlConnection( @ 数据源= 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 ; // 这是解决方案
SqlDataReader dm;
尝试
{

dm = cmd2.ExecuteReader();
while (dm.Read())
{


CurrentCityList.Add(dm [< span class =code-string> CityName]。ToString());


}

}

catch (例外情况)
{

}

最后
{
cn2.Close() ;
}
} < / string >


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.

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

<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>


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[^]

解决方案

Please see these examples:

1. Automatically Filtering a ComboBox in WPF [^]

2. A Reusable WPF Autocomplete TextBox [^]


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>


这篇关于当我输入第一个字母时,如何在组合框中搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆