This is a continuation of my previous blog about Silverlight WCF RIA. This time we will add, edit and delete records in our database.
Assuming that we already created our data entity model and the domain class controller as discussed in my previous blog. Let's create a layout for our entry form with a datagrid bind in our domain context and the add, edit, and delete buttons as shown;
To ADD new record;
Just simply type in corresponding data on each text box then double click on the add button. In the code behind, type the following code;
templatetbl2 newTemplate = new templatetbl2
{
TimeOff = Convert.ToDateTime(txbDate.Text),
Cause = txbCause.Text,
Duration = Convert.ToDecimal(txbDuration.Text),
Customer = Convert.ToDecimal(txbCustomer.Text),
TotalOutrage = Convert.ToDecimal(txbTotal.Text),
UtilityName = txbUtility.Text
};
var ctx = new DomainService1();
ctx.templatetbl2s.Add(newTemplate);
ctx.SubmitChanges(createop =>
{
Uri target = new Uri("/Page4 ", UriKind.Relative);
NavigationService.Navigate(target);
}, null);
MessageBox.Show("Successfully saved records!");
To Edit record;
You can just simply click on the selected record to edit. You can bind the data in the entry text box or you can just directly edit the selected cell of the datagrid. In this example, we will just select the the particular cell in the datagrid. After editing the cell contents, double click on the edit button and add the following code;
templatetbl2DomainDataSource.SubmitChanges();
The SubmitChanges command will automatically updates the database base on the edited values of the selected datagrid cells.
To Delete record;
Select the row to be deleted and double click on the delete button. In the code behind, type the following codes;
templatetbl2 ent = (templatetbl2)templatetbl2DomainDataSource.DataView.CurrentItem;
DomainService1 dc = templatetbl2DomainDataSource.DomainContext as DomainService1;
dc.templatetbl2s.Remove(ent);
templatetbl2DomainDataSource.SubmitChanges();
You need to call the SubmitChanges command so that the delete method will be executed in the database. Calling the Remove(entityname) will only mark the data for deletion.
These are a very simple lines of codes but very useful codes to start a Silverlight project.
Happy coding!

No comments:
Post a Comment