This is a migrated thread and some comments may be shown as answers.

WCF returning observable collection.

1 Answer 136 Views
General Discussions
This is a migrated thread and some comments may be shown as answers.
Henry
Top achievements
Rank 1
Henry asked on 19 Mar 2013, 06:49 PM
Hi,

I want to know how to convert a data table to an ObservableCollection and bind it to RadGrid. I am using a WCF service in my application and it will return the observable collection which is then bound to radgrid. It would be very helpful if someone can give a sample solution.

Any help appreciated,
Henry Gibbs.

1 Answer, 1 is accepted

Sort by
0
Accepted
Shinu
Top achievements
Rank 2
answered on 20 Mar 2013, 05:05 AM
Hi,

I think you want to bind an ObservableCollection returned by a WCF service to a RadGrid. Please have a look into the sample code provided below.

C#:
[ServiceContract]
public interface IDatabaseService
{
    [OperationContract]
    ObservableCollection<Employee> GetNames();
}
 
[DataContract]
public class Employee
{
    [DataMember]
    public int empno
    {
        get;
        set;
    }
 
    [DataMember]
    public string empname
    {
        get;
        set;
    }
}

public ObservableCollection<Employee> GetNames()
{
    ObservableCollection<Employee> employees = new ObservableCollection<Employee>();
    connectString = System.Configuration.ConfigurationManager.ConnectionStrings["myConnectionString"].ToString();
    connectionObject = new SqlConnection(connectString);
    try
    {
        if (connectionObject.State != ConnectionState.Open)
        {
            connectionObject.Open();
        }
        string selQuery = "select empname,empno from Employee";
        SqlCommand comm = new SqlCommand(selQuery, connectionObject);
        SqlDataReader reader = comm.ExecuteReader();
        while (reader.Read())
        {
            Employee em = new Employee();
            em.empno = int.Parse(reader["empno"].ToString());
            em.empname = Convert.ToString(reader["empname"]);
            employees.Add(em);
        }
    }
    catch (Exception ex)
    {
    }
    finally
    {
        if (connectionObject.State != ConnectionState.Closed)
        {
            connectionObject.Close();
        }
    }
    return employees;
}

Then you can bind the Collection to your RadGridView as follows.

C#:
DatabaseServiceClient client = new DatabaseServiceClient();
 
private void Button1_Click(object sender, RoutedEventArgs e)
{
    client.GetNamesCompleted += new EventHandler<GetNamesCompletedEventArgs>(client_GetNamesCompleted);
    client.GetNamesAsync();
}
 
void client_GetNamesCompleted(object sender, GetNamesCompletedEventArgs e)
{
    RadGrid1.ItemsSource = e.Result;          
}

Thanks,
Shinu.
Tags
General Discussions
Asked by
Henry
Top achievements
Rank 1
Answers by
Shinu
Top achievements
Rank 2
Share this question
or