How to populate Combobox in silverlight ?



Hi

Here all process are same as datagrid filling, only we have to do few changes

step1:Configure the combobox like this

<ComboBox Height="23" HorizontalAlignment="Left" Margin="10,10,0,0" Name="comboBox1"
VerticalAlignment="Top" Width="120" >

</ComboBox>

Step2:Create one Silverlight enable WCF and write the code like this

using System;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;

namespace SilverlightApplication16.Web
{
[ServiceContract(Namespace = “”)]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service1
{

SqlConnection con = new SqlConnection(“Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\Database1.mdf;Integrated Security=True;User Instance=True”);
[OperationContract]
public List GetEmpName()
{
List Emps = new List();
//items.Add(new Product() { Name = “Select”, Id = 0 });
Emps.Add(new Emp { EmpName = “Select”, EmpSal = “0”, Id = 0 });

con.Open();
SqlCommand cmd = new SqlCommand(“Select Id,EmpName,EmpSal from tblEmp”, con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Emp emp1 = new Emp();
emp1.Id = Convert.ToInt32(dr[“Id”]);
emp1.EmpName = dr[“EmpName”].ToString();
emp1.EmpSal = dr[“EmpSal”].ToString();
Emps.Add(emp1);
}
con.Close();
return Emps;
}

}
}

Step3: Compile the WCF and Consume the service in silverlight application

step4: Change codebehind file like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using SilverlightApplication1.ServiceReference1;

namespace SilverlightApplication1
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
FillDataGrid();

}

private void FillDataGrid()
{
Service1Client client = new Service1Client();
client.GetAllEmpCompleted += new EventHandler<GetAllEmpCompletedEventArgs>(client_GetAllEmpCompleted);
client.GetAllEmpAsync();

}

void client_GetAllEmpCompleted(object sender, GetAllEmpCompletedEventArgs e)
{
//GridTest.ItemsSource = e.Result;
Combo1.ItemsSource = e.Result;

}
}
}

Now compile the code.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.