Tuesday, August 30, 2011

GridView Insert, Edit, Update, Delete, Sorting

This demo describes the basic way to do INSERT, EDIT, UPDATE ,DELETE and SORTING data in ASPNET GridView Control using the ADO.NET way.

STEP  1: Creating  a DataBase Table.


Create a database names neeraj containing a table named Login.
Following must be the design of the table Login


Column           Datatype
    

User_ID    nvarchar(5)
User_Name    nvarchar(50)
Password    nvarchar(50)




STEP 2: Setting Up the Connection String

   <connectionStrings>
    <add name="DBConnection" connectionString="Data Source=GDC-DELL-PC17\SQLEXPRESS;Initial Catalog=neeraj;Integrated Security=True"/>
  </connectionStrings>
 


STEP 3: Creating GridView

<asp:Label ID="lblSortDirection" runat="server"></asp:Label>
    <asp:GridView ID="GridView1"
                  runat="server"
                  AutoGenerateColumns="False
                  AutoGenerateEditButton="True
                  onrowcancelingedit="GridView1_RowCancelingEdit
                  onrowediting="GridView1_RowEditing
                  onrowupdating="GridView1_RowUpdating
                  ShowFooter="True
                  AutoGenerateDeleteButton="True
                  onrowdeleting="GridView1_RowDeleting
                  
            AllowSorting="True" onsorting="GridView1_Sorting" AllowPaging="True" 
           PageSize="3" onpageindexchanging="GridView1_PageIndexChanging1"   
             >
        <PagerSettings PageButtonCount="1" />
        <Columns>
            <asp:TemplateField HeaderText="User_ID" SortExpression="User_ID">
                <ItemTemplate>
                    <asp:Label ID="lblUserId" runat="server" Text='<%# Eval("User_ID") %>'></asp:Label>
                </ItemTemplate>
                
                <FooterTemplate>
                    <asp:TextBox ID="txtInsertUserId" runat="server"></asp:TextBox>
                </FooterTemplate>
                <FooterStyle VerticalAlign="Top" />
            </asp:TemplateField>
            <asp:TemplateField HeaderText="User_Name" SortExpression="User_Name">
                <ItemTemplate>
                    <asp:Label ID="lblUserName" runat="server" Text='<%# Eval("User_Name") %>'></asp:Label>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:TextBox ID="txtEditUserName" runat="server" Text='<%# Bind("User_Name") %>' ></asp:TextBox>
                </EditItemTemplate>
                <FooterTemplate>
                    <asp:TextBox ID="txtInsertUserName" runat="server"></asp:TextBox>
                </FooterTemplate>
                <FooterStyle VerticalAlign="Top" />
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Password" SortExpression="Password">
                <ItemTemplate>
                    <asp:Label ID="lblPassword" runat="server" Text='<%# Eval("Password") %>'></asp:Label>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:TextBox ID="txtEditPassword" runat="server" Text='<%# Bind("Password") %>'></asp:TextBox>
                </EditItemTemplate>
                <FooterTemplate>
                    <asp:TextBox ID="txtInsertPassword" runat="server"></asp:TextBox>
                    <br />
                    <asp:Button ID="btnInsert" runat="server" onclick="btnInsert_Click" 
                        Text="Insert" />
                    <asp:Button ID="btnCancel" runat="server" Text="Cancel" OnClick="btnCancel_Click" />
                </FooterTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>



STEP 4: Binding GridView with Data



public partial class _Default : System.Web.UI.Page
{
    string strSortExpression;


    protected void Page_Load(object sender, EventArgs e)
    {
    }


    private string GetConnectionString()
    {
        return System.Configuration.ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
    }



 protected void fillgrid()
    {
        SqlConnection conn = new SqlConnection(GetConnectionString());
        DataTable dt = new DataTable();


        try
        {
            
            conn.Open();
            string query = "select * from Login";
            SqlCommand cmd = new SqlCommand(query, conn);
            SqlDataAdapter adp = new SqlDataAdapter(cmd);
            adp.Fill(dt);
            if (dt.Rows.Count &gt; 0)
            {
                GridView1.DataSource = dt;
                GridView1.DataBind();
            }
            else
            {
                GridView1.Visible = false;
                Response.Write("No data to display!!!");
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
        finally
        {
            conn.Close();
        }
    }


STEP 5: InsertNew Data in GridView



 protected void btnInsert_Click(object sender, EventArgs e)
    {


        SqlConnection conn = new SqlConnection(GetConnectionString());
        try
        {
            conn.Open();


            string user_name = ((TextBox)GridView1.FooterRow.FindControl("txtInsertUserName")).Text;
            string pwd = ((TextBox)GridView1.FooterRow.FindControl("txtInsertPassword")).Text;
            string id = ((TextBox)GridView1.FooterRow.FindControl("txtInsertUserId")).Text;


            Response.Write(user_name);
            Response.Write(pwd);
            Response.Write(id);


            if (user_name != "" &amp;&amp; pwd != "" &amp;&amp; id != "")
            {
                SqlCommand cmd = new SqlCommand("STP_insertLogin", conn);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add("@user_name", SqlDbType.VarChar).Value = user_name;
                cmd.Parameters.Add("@user_id", SqlDbType.VarChar).Value = id;
                cmd.Parameters.Add("@pwd", SqlDbType.VarChar).Value = pwd;
                cmd.ExecuteNonQuery();
                conn.Close();
                fillgrid();
                clear();
            }
            else
            {
                Response.Write("Please insert proper values");
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
        finally
        {
            conn.Close();
        }
    }




protected void btnCancel_Click(object sender, EventArgs e)
    {
        clear();
    }


    protected void clear()
    {
        ((TextBox)GridView1.FooterRow.FindControl("txtInsertUserName")).Text = "";
        ((TextBox)GridView1.FooterRow.FindControl("txtInsertPassword")).Text = "";
        ((TextBox)GridView1.FooterRow.FindControl("txtInsertUserId")).Text = "";
    }




STEP 6: Edit and Update Records In GridView



 protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        fillgrid();
    }


    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        fillgrid();
    }


    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        SqlConnection conn = new SqlConnection(GetConnectionString());
        try
        {
            conn.Open();


            string user_name = ((TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0].FindControl("txtEditUserName")).Text;
            string pwd = ((TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[0].FindControl("txtEditPassword")).Text;
            string id = ((Label)GridView1.Rows[e.RowIndex].Cells[0].Controls[0].FindControl("lblUserId")).Text;


            SqlCommand cmd = new SqlCommand("usp_UpdateUserMaster", conn);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add("@User_Name", SqlDbType.VarChar).Value = user_name;
            cmd.Parameters.Add("@Password", SqlDbType.VarChar).Value = pwd;
            cmd.Parameters.Add("@User_ID", SqlDbType.VarChar).Value = id;
            cmd.ExecuteNonQuery();
            conn.Close();
            GridView1.EditIndex = -1;
            fillgrid();
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
        finally
        {
            conn.Close();
        }
    }


STEP 7: Perform Delete in GridView



protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
                
            SqlConnection conn = new SqlConnection(GetConnectionString());
            try
            {
                conn.Open();
                string id = ((Label)GridView1.Rows[e.RowIndex].Cells[0].Controls[0].FindControl("lblUserId")).Text;
                SqlCommand cmd = new SqlCommand("STP_deleteLogin", conn);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add("@user_id", SqlDbType.VarChar).Value = id;
                cmd.ExecuteNonQuery();
                fillgrid();
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
            finally
            {
                conn.Close();
            }
            
    }


STEP 8: Perform Sorting in GridView



 protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {
        strSortExpression = (string)ViewState["SortExpression"];
        DataTable dt = dt_return();
        if (lblSortDirection.Text == " ASC" &amp;&amp; strSortExpression == e.SortExpression)
        {
            lblSortDirection.Text = " DESC";
            ViewState["SortExpression"] = e.SortExpression;
            strSortExpression = (string)ViewState["SortExpression"];
        }
        else
        {
            lblSortDirection.Text = " ASC";
            ViewState["SortExpression"] = e.SortExpression;
             strSortExpression = (string)ViewState["SortExpression"];
        }
        
        dt.DefaultView.Sort = strSortExpression + lblSortDirection.Text;
        GridView1.DataSource = dt.DefaultView;
        GridView1.DataBind();
    }

No comments: