How to insert data in to database using Silverlight 5 enabled WCF service?
Silverlight5 is a latest version of silverlight which gives rich look and feel to the application.
You can use this code to insert dynamic data in to database.
I hope this article will be useful for you all.
Description: As we can not use ADO.net directly in silverlight5, we have to create Silverlight enabled WCF service.
To create Silverlight enabled WCF service, go to silverlight web project-> Add -> New Item -> Silverlight enabled WCF service.It will create Service1.svc file by default.
Now place the following code in .svc file.
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System;
namespace your_project_namespace.Web
{
[ServiceContract(Namespace = "")]
[SilverlightFaultBehavior]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class InsertFunctionality
{
static string connectionString = "Data Source=your_server_name\\your_SQLserver_instance_name;Initial Catalog=your_databasename;Integrated Security=True;";
[OperationContract]
public void DataInsertIntoDb(int _columnname1 , int _columnname2)
{
SqlConnection sqlConnection = new SqlConnection(connectionString);
DataSet Myobj = new DataSet();
SqlCommand sqlCommand = new SqlCommand();
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandText = "INSERT INTO your_tablename (columnname1, columnname2) VALUES (" + _columnname1 + "," + _columnname2 + ")";
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter();
sqlDataAdapter.SelectCommand = sqlCommand;
sqlDataAdapter.Fill(Myobj);
}
}
}
You have to add service reference of this .svc file in to your application so that you can create object of that .svc file and use this insert functionality in your xaml file.
ServiceReference1.InsertFunctionalityClient ifc = new ServiceReference1.InsertFunctionalityClient();
ifc.InsertDataAsync(txt_for_column1_input.text , txt_for_column2_input.text);
You can put success or failure message after calling this method as well so that if data is properly saved in the database then it will show success message to user else failure.