How to display data in gridview using WCF

Here , simple way to display the users list in gridview using WCF
For this  you have to create a database with Users table which contains4 fields that is, Username,fullname,desgination,company
After the completion of creating the database you have to create WCF service.

For this,First open the Visual studio 2008

Next,select a New website in the Templates dialouge box select a webservice and press ok

Next,open the IService.cs page and write the following code

public interface IService
{
    [OperationContract]
    Users[] getAllUsersLists(); 
}
add composite types to service operations.
[DataContract]
public class Emp
{
    [DataMember]
    public string UserName { get; set; }
    [DataMember]
    public string FullName { get; set; }
    [DataMember]
    public string Desgination { get; set; }
    [DataMember]
    public string company { get; set; }
}
Next,save the page and now open the Service.cs file

and write the following code :
#region IService Members

Users[] IService.getAllUsersLists()
{

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["SAMPLE_2"].ToString());

SqlCommand com = new SqlCommand("select UserName,FullName,Desgination,company from Users", con);

        SqlDataAdapter da = new SqlDataAdapter(com);
        DataTable dt = new DataTable();
        da.Fill(dt);
        int RCount = dt.Rows.Count;
        Users[] arrEmp = new Users[RCount];
        int i = 0;
        foreach (DataRow dr in dt.Rows)
        {
            arrEmp[i] = new Users();           
            arrEmp[i].UserName = dr["UserName"].ToString();
            arrEmp[i].FullName = dr["FullName"].ToString();
            arrEmp[i].Desgination = dr["Desgination"].ToString();
            arrEmp[i].company = dr["company"].ToString();
            i++;

        }
        return arrEmp;

    }


    #endregion
Next,save the build the solution and copy the url in the address bar of the browser

Next,Select a new website and right click on the project in the solution explorer and select a addservice reference

In the address, bar paste the url which was copied before and press Go

After the namespace appears(Ex : ServiceReference1) then press ok

next,open the Design page of Default.aspx and drag and drop one gridview from the toolbox

next,open the code page that is,Default.aspx.cs and write the following code
 protected void Page_Load(object sender, EventArgs e)
    {
        ServiceReference1.ServiceClient obj = new ServiceReference1.ServiceClient();
        GridView1.DataSource = obj.getAllUsersLists();
        GridView1.DataBind();
    }
finally,Execute it....That's it
developercode
About the Author
Sayyad is a Software Engineer, Blogger and Founder of Developers Code from India.His articles mainly focus on .Net (Web and Windows based applications), Mobile Technologies (Android,IPhone,BlackBerry) and SEO.

Facebook Rss Twitter

Get Weekly News letter of Updates!