Here you can see how to work with ADO.NET Entity Framework and hand-coded access to data.
This code is implemented in the code-behind of the page, and associated to the buttons added to create a new element, edit n existing, save, cancel and delete.
For simplicity I am supposing that data entered in text boxes is correct, otherwise you can control using validation controls associated to the text boxes.
Saving a New or Edited existing: (Associated to Save Button)
using (TheClubBDEntities myEntities = new TheClubBDEntities())
{
RaceType aRaceType;
if (_Id == -1) //Save new
{
aRaceType = new RaceType();
myEntities.RaceTypes.AddObject(aRaceType);
}
else
{ //Update existing
aRaceType = (from r in myEntities.RaceTypes
where r.Id == _Id
select r).Single();
}
aRaceType.Name = txbxNombre.Text;
aRaceType.PuntosPart = Int32.Parse(txbxPuntos.Text);
aRaceType.Memo = txbxMemo.Text;
LastPos = _Id; // Used to control position in the data base.
myEntities.SaveChanges();
GridView1.DataBind(); // To refresh data into GridView
setNormalMode(); //Disable save button and put textboxes in readonly mode.
}
Deleting existing:
using (TheClubBDEntities myEntities = new TheClubBDEntities())
{
var aRaceType = (from r in myEntities.RaceTypes
where r.Id == _Id
select r).Single();
myEntities.RaceTypes.DeleteObject(aRaceType);
myEntities.SaveChanges();
}
GridView1.DataBind();
setNormalMode();
Cancel editing or adding a new:
using (TheClubBDEntities myEnt = new TheClubBDEntities())
{
var aRaceType = (from rt in myEnt.RaceTypes
orderby rt.Name ascending
where rt.Id == LastPos
select rt).SingleOrDefault();
if (aRaceType == null)
{
_Id = -1;
LastPos = -1;
}
else
{
_Id = aRaceType.Id;
txbxNombre.Text = aRaceType.Name;
txbxPuntos.Text = aRaceType.PuntosPart.ToString();
txbxMemo.Text = aRaceType.Memo;
}
setNormalMode();
}
Selecting from the GridView and putting data into textboxes:
_Id = Int32.Parse(GridView1.SelectedRow.Cells[1].Text);
LastPos = _Id;
txbxNombre.Text = GridView1.SelectedRow.Cells[2].Text;
txbxPuntos.Text = GridView1.SelectedRow.Cells[3].Text;
txbxMemo.Text = GridView1.SelectedRow.Cells[4].Text;
setNormalMode();
Moving to first:
using (TheClubBDEntities myEnt = new TheClubBDEntities())
{
var aRaceType = (from rt in myEnt.RaceTypes
orderby rt.Name ascending
select rt).FirstOrDefault();
if (aRaceType == null)
_Id = -1;
else
{
_Id = aRaceType.Id;
LastPos = _Id;
txbxNombre.Text = aRaceType.Name;
txbxPuntos.Text = aRaceType.PuntosPart.ToString();
txbxMemo.Text = aRaceType.Memo;
}
}
Loading the page:
using (TheClubBDEntities myEnt = new TheClubBDEntities())
{
if (!Page.IsPostBack)
{
var aRaceType = (from rt in myEnt.RaceTypes
select rt).FirstOrDefault();
if (aRaceType == null)
{
_Id = -1;
LastPos = -1;
}
else
{
_Id = aRaceType.Id;
LastPos = _Id;
txbxNombre.Text = aRaceType.Name;
txbxPuntos.Text = aRaceType.PuntosPart.ToString();
txbxMemo.Text = aRaceType.Memo;
}
}
}
No hay comentarios:
Publicar un comentario