How to use AutoCompleteBox in silverlight Binding data from service


Introduction :

This blog shows how we can display element in AutoCompleteBox in a sorting order in silverlight.

We have one menthod at service side, called GetClientName() here we have clientnames of a client.

Displaying that clientnames in autocompleteBox.

Example :

1. We have one service, Service1.svc.

 [OperationContract]
        public List<string> GetClientName(string str)
        {
            string s = str + "%";
            sqlConnection.Open();
            string query = "select ClientName from Client where ClientName like '" + s + "' order by ClientName";
            sqlCommand = new SqlCommand(query, sqlConnection);
            sqlReader = sqlCommand.ExecuteReader();
            while (sqlReader.Read())
            {
                list.Add(sqlReader[0].ToString());
            }
            sqlConnection.Close();
            return list.ToList();
        }

2.In MainPage.Xaml

<Grid x:Name="LayoutRoot" Background="White">
        <Canvas Height="147" HorizontalAlignment="Left" Margin="72,64,0,0" Name="canvas1" VerticalAlignment="Top" Width="264">
            <Canvas.Background>
                <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                    <GradientStop Color="#FF046FFF" Offset="0.768" />
                    <GradientStop Color="Black" Offset="0.991" />
                </LinearGradientBrush>
            </Canvas.Background>
            <sdk:AutoCompleteBox x:Name="MyautoBox" Canvas.Left="55" Canvas.Top="53" Width="150" ItemContainerStyle="{StaticResource myLBStyle}" />
        </Canvas>
    </Grid>

3. MainPAge.cs

public MainPage()
        {
            InitializeComponent();
   // SearchText is the text which is use for filter items in Autocompletebox.itemsource collection.
            GetClientName(MyautoBox.SearchText);
        }
        public void GetClientName(string cname)
        {
            ServiceReference1.Service1Client service = new ServiceReference1.Service1Client();
            service.GetClientNameCompleted += new EventHandler<ServiceReference1.GetClientNameCompletedEventArgs>(service_GetClientNameCompleted);
            service.GetClientNameAsync(cname);
        }
        void service_GetClientNameCompleted(object sender, ServiceReference1.GetClientNameCompletedEventArgs e)
        {
            MyautoBox.ItemsSource = e.Result;
        }

OutPut :

autobox.JPG
Thanks.
Ebook Download
View all
Learn
View all