using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data.SqlClient;

public partial class DeptList : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            setDept();
        }
    }
    SqlConnection con = new SqlConnection(ConfigurationSettings.AppSettings.Get("con"));

    private void setDept()
    {
        if (con.State == ConnectionState.Closed) con.Open();
        SqlDataAdapter da = new SqlDataAdapter("select * from dept", con);
        DataSet ds = new DataSet();
        da.Fill(ds, "dept");
        DataGrid1.DataSource = ds.Tables[0];
        DataGrid1.DataBind();
    }
    protected void DataGrid1_CancelCommand(object source, DataGridCommandEventArgs e)
    {
        DataGrid1.EditItemIndex = -1;
        setDept();
    }
    protected void DataGrid1_DeleteCommand(object source, DataGridCommandEventArgs e)
    {
        if (con.State == ConnectionState.Closed) con.Open();
        try
        {
            SqlCommand cmd = new SqlCommand("delete from dept where deptno='" + e.Item.Cells[0].Text + "'", con);
            cmd.ExecuteNonQuery();
            con.Close();
            DataGrid1.EditItemIndex = -1;
            setDept();
        }
        catch (Exception ex)
        {
            lbltext.Text = "Conflict occured in the database";
        }
    }
    protected void DataGrid1_EditCommand(object source, DataGridCommandEventArgs e)
    {
        DataGrid1.EditItemIndex = e.Item.ItemIndex;
        setDept();
    }
    protected void DataGrid1_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
    {

        DataGrid1.CurrentPageIndex = e.NewPageIndex;
        setDept();
    }
    protected void DataGrid1_UpdateCommand(object source, DataGridCommandEventArgs e)
    {
        if (con.State == ConnectionState.Closed) con.Open();
        String t1, t2, t3;
        t1 = ((TextBox)e.Item.Cells[1].Controls[0]).Text;
        t2 = ((TextBox)e.Item.Cells[2].Controls[0]).Text;
        t3 = e.Item.Cells[3].Text;
        SqlCommand cmd = new SqlCommand("update dept set deptname='" + t1 + "',phno='" + t2 + "',branchno='" + t3 + "' where deptno='" + e.Item.Cells[0].Text + "'", con);
        cmd.ExecuteNonQuery();
        con.Close();
        lbltext.Text = "One Record Modified";
        DataGrid1.EditItemIndex = -1;
        setDept();
    }
    protected void DataGrid1_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
}
