Introduction
Updating data in a DataList is a very easy task in ASP.NET. I have use the Entity Framework to insert, update and delete data from a DataList.
Background
I have used templates to store data in the DataList, like label, TextBox and a button for raising events.
The DataList in my page is like the following.
Using the code
Drag one DataList Control from the Toolbox and Declare its ItemTemplet like this given below:
On the page event bind your DataList with Database, I have used The Entity Framework to bind the database to the code; it is given below:
- protected void Page_Load(object sender, EventArgs e)
- {
- if (!IsPostBack)
- {
- if (Request.QueryString["id"]== null)
- {
- using (OCSEntities ocs = new OCSEntities())
- {
- ocs.Connection.Open();
- DataList1.DataSource = ocs.Addresses.Where(item => item.UID == SessionManager.Current.CurrentUser.ID).ToList();
- DataList1.DataBind();
- }
- }
- else
- {
- DataList1.Visible = false;
- pnlnew.Visible = true;
- }
- }
Use the ItemCommand Event to specify the Edit item index of the DataList.
For example:
- protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
- {
- if (e.CommandName == "Edit")
- {
- DataList1.EditItemIndex = 0;
- }
- }
Again rebind your DataList to the databse table in the editcommand event of the DataList control; see:
- protected void DataList1_EditCommand(object source, DataListCommandEventArgs e)
- {
-
- using (OCSEntities ocs = new OCSEntities())
- {
- ocs.Connection.Open();
- DataList1.DataSource = ocs.Addresses.Where(item => item.UID == SessionManager.Current.CurrentUser.ID).ToList();
- DataList1.DataBind();
- }
- }
Use the updatecommand event to update your database as in the following:
- protected void DataList1_UpdateCommand(object source, DataListCommandEventArgs e)
- {
- if (e.Item.ItemType == ListItemType.EditItem)
- {
- using (OCSEntities ocs = new OCSEntities())
- {
- ocs.Connection.Open();
- OCSModel.Address ad = ocs.Addresses.Where(item => item.UID == SessionManager.Current.CurrentUser.ID).First();
- ad.Address1 = ((TextBox)e.Item.FindControl("txtAdd1")).Text;
- ad.Address2 = ((TextBox)e.Item.FindControl("txtAdd2")).Text;
- ad.City = ((TextBox)e.Item.FindControl("txtCity")).Text;
- ad.State = ((TextBox)e.Item.FindControl("txtState")).Text;
- ad.PIN = ((TextBox)e.Item.FindControl("txtPin")).Text;
- ocs.SaveChanges();
- ocs.AcceptAllChanges();
- }
- DataList1.EditItemIndex = -1;
- using (OCSEntities ocs = new OCSEntities())
- {
- ocs.Connection.Open();
- DataList1.DataSource = ocs.Addresses.Where(item => item.UID == SessionManager.Current.CurrentUser.ID).ToList();
- DataList1.DataBind();
- }
- }
- }
Points of Interest
Did you learn anything interesting/fun/annoying while writing the code? Did you do anything particularly clever or wild or zany?
History
Keep a running update of any changes or improvements you've made here.