using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AlfredoLotar.Livro.Aspnet.SchoolModel;
using System.Data;

public partial class DeletePerson : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        
    }
    protected void ExcluirAdd_Click(object sender, EventArgs e)
    {
        using (SchoolEntities contexto = new SchoolEntities())
        {
            try
            {
                int id = Convert.ToInt32(GridView1.SelectedDataKey.Value);
                Person p = (from e1 in contexto.Person
                            where e1.PersonID == id
                            select e1).First();

                contexto.Person.DeleteObject(p);
                contexto.SaveChanges();
                Preencher();
                ExcluirAdd.Enabled = true;
            }
            catch (EntitySqlException ex)
            {
                Response.Write("Erro EntitySqlException");
            }
            catch (EntityCommandExecutionException ex)
            {
                Response.Write("Erro EntityCommandExecutionException");
            }
        }
    }

    void Preencher()
    {
        using (SchoolEntities contexto = new SchoolEntities())
        {
            GridView1.DataSource = contexto.ExecuteStoreQuery<Person>
                    ("Select top 20 * from Person order by PersonID DESC");
            GridView1.DataBind();
        }
    }

    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {
        using (SchoolEntities contexto = new SchoolEntities())
        {
            try
            {
                int i = Convert.ToInt32(GridView1.SelectedDataKey.Value);
                IQueryable<Person> p = contexto.Person.Where(t => t.PersonID == i);

                foreach (Person reg in p)
                {
                    txtID.Text = GridView1.SelectedDataKey.Value.ToString();
                    txtNome.Text = reg.FirstName.ToString();
                    txtSobrenome.Text = reg.LastName.ToString();
                }
                ExcluirAdd.Enabled = true;
                btnPreencher.Enabled = false;
            }
            catch (EntitySqlException ex)
            {
                Response.Write(ex.ToString());
            }
        }
    }
    protected void btnPreencher_Click(object sender, EventArgs e)
    {
        Preencher();
    }
}