Tuesday, 29 April 2014

CRUD IN GRIDVIEW - Database operation within Gridview - Insert, Update, Select and Delete with Gridview


In every every dynamic website developers do CRUD with gridview.
Today I am sharing my idea to work with Gridview.
Many developers do this CRUD with more than two pages. They design page
for adding the data to the database. Then the display the data on
another page. Now for editing they open another page. Its a too long
and old fashion for working with database.
.Net provides so many easy method to achieve this goal in simple easy steps.
Gridview has power to do this. I played with it and today I shared my experience.


Insert, Update, Delete and Select
 
Example 1:
Create a table like below with name COUNTRY.

PK
countryID
Bigint

countryName
nvarchar(50)

Create following store procedures.

CREATE PROCEDURE ssp_SelectFetchCountry
as
      SELECT * FROM COUNTRY ORDER BY COUNTRYID DESC



CREATE PROCEDURE isp_InsertCountry
(
@countryName nvarchar(50)
)
as
      begin
            INSERT INTO COUNTRY (countryName) VALUES (@countryName)
      END  


CREATE PROCEDURE dsp_DeleteCountry
(
@countryID bigint
)
as
      BEGIN
      DELETE FROM COUNTRY WHERE countryID = @countryID
      END


CREATE PROCEDURE usp_UpdateCountry
(
@countryID bigint,
@countryName nvarchar(50)
)
as
      BEGIN
            UPDATE COUNTRY SET countryName = @countryName WHERE countryID = @countryID
      END


Put below code into your header part.

<script type="text/javascript">
        function ConfirmationBox(username) {

        var result = confirm('Are you sure you want to delete '+username+' Details?' );
        if (result) {

        return true;
        }
        else {
        return false;
        }
        }
    </script>

Put below code under body portion of your page.

<table border="0" cellpadding="0" cellspacing="0" width="45%">
                    <tr>
                        <td align="center" valign="middle" style="width: 410px">
                            <asp:GridView ID="gvDetails" DataKeyNames="countryID,countryName" runat="server" AutoGenerateColumns="False"
                                CssClass="Gridview" HeaderStyle-BackColor="#61A6F8" ShowFooter="True" HeaderStyle-Font-Bold="true"
                                HeaderStyle-ForeColor="White" OnRowCancelingEdit="gvDetails_RowCancelingEdit"
                                OnRowDeleting="gvDetails_RowDeleting" OnRowEditing="gvDetails_RowEditing" OnRowUpdating="gvDetails_RowUpdating"
                                OnRowDataBound ="gvDetails_RowDataBound" OnRowCommand="gvDetails_RowCommand" Width="75%">
                                <Columns>
                                    <asp:TemplateField HeaderText="Operation">
                                        <EditItemTemplate>
                                            <asp:ImageButton ID="imgbtnUpdate" CommandName="Update" runat="server" ImageUrl="~/images/Images/update.jpg"
                                                ToolTip="Update" Height="20px" Width="20px" ValidationGroup="abc" />
                                            <asp:ImageButton ID="imgbtnCancel" runat="server" CommandName="Cancel" ImageUrl="~/images/Images/Cancel.jpg"
                                                ToolTip="Cancel" Height="20px" Width="20px" />
                                        </EditItemTemplate>
                                        <ItemTemplate>
                                            <asp:ImageButton ID="imgbtnEdit" CommandName="Edit" runat="server" ImageUrl="~/images/Images/Edit.jpg"
                                                ToolTip="Edit" Height="20px" Width="20px" />
                                            <asp:ImageButton ID="imgbtnDelete" CommandName="Delete" runat="server"
                                                ImageUrl="~/images/Images/delete.jpg" ToolTip="Delete" Height="20px" Width="20px" />
                                        </ItemTemplate>
                                        <FooterTemplate>
                                            <asp:ImageButton ID="imgbtnAdd" runat="server" ImageUrl="~/images/Images/AddNewitem.jpg"
                                                CommandName="AddNew" Width="30px" Height="30px" ToolTip="Add new Country" ValidationGroup="validaiton" />
                                        </FooterTemplate>
                                        <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
                                        <FooterStyle HorizontalAlign="Center" VerticalAlign="Middle" />
                                    </asp:TemplateField>
                                    <asp:TemplateField HeaderText="Country Name">
                                        <EditItemTemplate>
                                            <asp:TextBox ID="txt_country" ValidationGroup="abc" MaxLength="35" runat="server" Text='<%#Eval("countryName") %>' />
                                            <asp:RequiredFieldValidator ID="rfvusername11" runat="server" ControlToValidate="txt_country"
                                                Text="*" ValidationGroup="abc" />
                                        </EditItemTemplate>
                                        <ItemTemplate>
                                            <asp:Label ID="lbl_country" runat="server" Text='<%#Eval("countryName") %>' />
                                        </ItemTemplate>
                                        <FooterTemplate>
                                            <asp:TextBox ID="txt_countryEnter" runat="server" MaxLength="35" />
                                            <asp:RequiredFieldValidator ID="rfvusername" runat="server" ControlToValidate="txt_countryEnter"
                                                Text="*" ValidationGroup="validaiton" />
                                        </FooterTemplate>
                                        <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
                                        <FooterStyle HorizontalAlign="Center" VerticalAlign="Middle" />
                                    </asp:TemplateField>
                                </Columns>
                                <HeaderStyle BackColor="#61A6F8" Font-Bold="True" ForeColor="White" />
                            </asp:GridView>
                        </td>
                    </tr>
                    <tr>
                        <td style="padding:5px 0 5px 0; width: 410px;">
                            <asp:Label ID="lbl_msg" runat="server" Font-Bold="true" Font-Italic="true" ></asp:Label>
                        </td>
                    </tr>
                </table>

Create a class named ManageCountry and put below code in it.

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

/// <summary>
/// Summary description for ManageCountry
/// </summary>
public class ManageCountry
{
    string conStr = string.Empty;

    SqlConnection con;
    SqlDataAdapter adp;
    SqlCommand cmd;
    SqlDataReader dr;

      public ManageCountry()
      {
            //
            // TODO: Add constructor logic here
            //
        conStr = System.Configuration.ConfigurationManager.ConnectionStrings["abc"].ConnectionString;
      }

    public DataSet RetiveData()
    {
        try
        {
            con = new SqlConnection(conStr);
            con.Open();
            cmd = new SqlCommand("ssp_SelectFetchCountry", con);
            cmd.CommandType = CommandType.StoredProcedure;
            adp = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            adp.Fill(ds);
            return ds;
        }
        catch
        {
            return null;
        }
        finally
        {
            adp.Dispose();
            con.Close();
        }
    }

    public int InsetCountry(string name)
    {
        try
        {
            con = new SqlConnection(conStr);
            con.Open();
            cmd = new SqlCommand("isp_InsertCountry", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add("@countryName", SqlDbType.VarChar, 50).Value = name;
            cmd.ExecuteNonQuery();
            return 1;
        }
        catch (Exception ex)
        {
            return 0;
        }
        finally
        {
            cmd.Dispose();
            con.Close();
        }
    }

    public int DeleteCountry(int id)
    {
        try
        {
            con = new SqlConnection(conStr);
            con.Open();
            cmd = new SqlCommand("dsp_DeleteCountry", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add("@countryID", SqlDbType.BigInt, 900000000).Value = id;
            cmd.ExecuteNonQuery();
            return 1;
        }
        catch
        {
            return 0;
        }
        finally
        {
            cmd.Dispose();
            con.Close();
        }
    }

    public int UpdateCountry(int id, string name)
    {
        try
        {
            con = new SqlConnection(conStr);
            con.Open();
            cmd = new SqlCommand("usp_UpdateCountry", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add("@countryID", SqlDbType.BigInt, 900000000).Value = id;
            cmd.Parameters.Add("@countryName", SqlDbType.VarChar, 50).Value = name;
            cmd.ExecuteNonQuery();
            return 1;
        }
        catch
        {
            return 0;
        }
        finally
        {
            cmd.Dispose();
            con.Close();
        }
    }
}


Put below code into your code behind file.

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGrid();
        }
    }

protected void BindGrid()
    {
        ManageCountry obj = new ManageCountry();

        DataSet ds = obj.RetiveData();

        if (ds.Tables[0].Rows.Count > 0)
        {
            gvDetails.DataSource = ds;
            gvDetails.DataBind();
        }
        else
        {
            ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
            gvDetails.DataSource = ds;
            gvDetails.DataBind();
            int columncount = gvDetails.Rows[0].Cells.Count;
            gvDetails.Rows[0].Cells.Clear();
            gvDetails.Rows[0].Cells.Add(new TableCell());
            gvDetails.Rows[0].Cells[0].ColumnSpan = columncount;
            gvDetails.Rows[0].Cells[0].Text = "No Records Found";
        }
        obj = null;
    }




    protected void gvDetails_RowEditing(object sender, GridViewEditEventArgs e)
    {
        gvDetails.EditIndex = e.NewEditIndex;
        BindGrid();
    }




    protected void gvDetails_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        int countryid = Convert.ToInt32(gvDetails.DataKeys[e.RowIndex].Value.ToString());
        TextBox txt_name = (TextBox)gvDetails.Rows[e.RowIndex].FindControl("txt_country");

        ManageCountry obj = new ManageCountry();

        if (txt_name.Text.Trim() != "")
        {
            if (obj.UpdateCountry(countryid, txt_name.Text.Trim()) == 1)
            {
                lbl_msg.ForeColor = System.Drawing.Color.Green;
                lbl_msg.Text = "Country name successfully updated !!!";
                gvDetails.EditIndex = -1;
                BindGrid();
            }
            else
            {
                lbl_msg.ForeColor = System.Drawing.Color.Red;
                lbl_msg.Text = "Error in updating, try again !!!";
            }
        }
        else
        {
            lbl_msg.ForeColor = System.Drawing.Color.Red;
            lbl_msg.Text = "Plese enter country name !!!";
        }
        obj = null;
    }




    protected void gvDetails_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        gvDetails.EditIndex = -1;
        BindGrid();
    }




    protected void gvDetails_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int countryid = Convert.ToInt32(gvDetails.DataKeys[e.RowIndex].Values["countryID"].ToString());
        string name = gvDetails.DataKeys[e.RowIndex].Values["countryName"].ToString();
       
        ManageCountry obj = new ManageCountry();

        if (obj.DeleteCountry(countryid) == 1)
        {
            lbl_msg.ForeColor = System.Drawing.Color.Green;
            lbl_msg.Text = name + " deleted successfully !!!";
            BindGrid();
        }
        else
        {
            lbl_msg.ForeColor = System.Drawing.Color.Red;
            lbl_msg.Text = "Error in deleting " + name + "'s information !!!";
        }
        obj = null;
    }




    protected void gvDetails_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            //getting username from particular row
            string username = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "countryName"));
            //identifying the control in gridview
            ImageButton lnkbtnresult = (ImageButton)e.Row.FindControl("imgbtnDelete");
            //raising javascript confirmationbox whenver user clicks on link button
            if (lnkbtnresult != null)
            {
                lnkbtnresult.Attributes.Add("onclick", "javascript:return ConfirmationBox('" + username + "')");
            }

        }
    }




    protected void gvDetails_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("AddNew"))
        {
            TextBox txtCountryname = (TextBox)gvDetails.FooterRow.FindControl("txt_countryEnter");

            if (txtCountryname.Text.Trim() != "")
            {
                ManageCountry obj = new ManageCountry();

                if (obj.InsetCountry(txtCountryname.Text.Trim()) == 1)
                {
                    BindGrid();
                    lbl_msg.Text = txtCountryname.Text.Trim() + " successfully inserted !!!";
                    lbl_msg.ForeColor = System.Drawing.Color.Green;
                    txtCountryname.Text = string.Empty;
                }
                else
                {
                    lbl_msg.ForeColor = System.Drawing.Color.Red;
                    lbl_msg.Text = "Error in insertion, try again !!!";
                }
                obj = null;
            }
            else
            {
                lbl_msg.ForeColor = System.Drawing.Color.Red;
                lbl_msg.Text = "Please enter country name !!!";
            }
        }
    }


Example 2:

For example 2 you must need to do example 1, because both are interconnected with each other. See below:

Create a table like below.

PK
stateId
Bigint
FK
countryID
Bigint

stateName
nvarchar(50)

Create following store procedures.

CREATE PROCEDURE ssp_SelectState
AS
SELECT     Country.countryName, State.stateId, State.stateName
FROM         Country INNER JOIN
                      State ON Country.countryID = State.countryID ORDER BY State.stateId DESC


CREATE PROCEDURE ssp_SELECTCOUNTRY4DDL
AS
SELECT     Country.*
FROM         Country
ORDER BY countryName



CREATE PROCEDURE SSP_FETCHSTATEDDL
(
@COUNTRYID BIGINT
)
AS
      SELECT * FROM STATE WHERE COUNTRYID = @COUNTRYID


CREATE PROCEDURE ISP_INSERTSTATE
(
@countryID bigint,
@stateName NVARCHAR(50)
)
AS
      BEGIN
            INSERT INTO STATE (countryID, stateName) VALUES (@countryID, @stateName)
      END


CREATE PROCEDURE DSP_DELETESTATE
(
@stateId bigint
)
AS
      BEGIN
            DELETE FROM STATE WHERE stateId = @stateId
      END


CREATE PROCEDURE USP_UPDATESTATE
(
@stateId bigint,
@stateName nvarchar(50)
)
AS
      BEGIN
            UPDATE STATE SET stateName = @stateName  WHERE stateId = @stateId
      END



Put below code into your header part.

<script type="text/javascript">
        function ConfirmationBox(username) {

        var result = confirm('Are you sure you want to delete '+username+' Details?' );
        if (result) {

        return true;
        }
        else {
        return false;
        }
        }
    </script>

Put below code under body portion of your page.

<table border="0" cellpadding="0" cellspacing="0" width="50%">
                    <tr>
                        <td align="center" valign="middle">
                            <asp:GridView ID="GridView1" DataKeyNames="stateId,stateName" runat="server" AutoGenerateColumns="False"
                                Width="98%" ShowFooter="True" HeaderStyle-BackColor="#61A6F8" HeaderStyle-Font-Bold="true"
                                HeaderStyle-ForeColor="White" OnRowDataBound="GridView1_RowDataBound" OnRowCommand="GridView1_RowCommand"
                                OnRowEditing="GridView1_RowEditing" OnRowCancelingEdit="GridView1_RowCancelingEdit"
                                OnRowDeleting="GridView1_RowDeleting" OnRowUpdating="GridView1_RowUpdating">
                                <Columns>
                                    <asp:TemplateField HeaderText="Operation">
                                        <EditItemTemplate>
                                            <asp:ImageButton ID="imgbtnUpdate" CommandName="Update" runat="server" ImageUrl="~/images/Images/update.jpg"
                                                ToolTip="Update" Height="20px" Width="20px" ValidationGroup="abc" />
                                            <asp:ImageButton ID="imgbtnCancel" runat="server" CommandName="Cancel" ImageUrl="~/images/Images/Cancel.jpg"
                                                ToolTip="Cancel" Height="20px" Width="20px" />
                                        </EditItemTemplate>
                                        <ItemTemplate>
                                            <asp:ImageButton ID="imgbtnEdit" CommandName="Edit" runat="server" ImageUrl="~/images/Images/Edit.jpg"
                                                ToolTip="Edit" Height="20px" Width="20px" />
                                            <asp:ImageButton ID="imgbtnDelete" CommandName="Delete" runat="server" ImageUrl="~/images/Images/delete.jpg"
                                                ToolTip="Delete" Height="20px" Width="20px" />
                                        </ItemTemplate>
                                        <FooterTemplate>
                                            <asp:ImageButton ID="imgbtnAdd" runat="server" ImageUrl="~/images/Images/AddNewitem.jpg"
                                                CommandName="AddNew" Width="30px" Height="30px" ToolTip="Add new Country" ValidationGroup="validaiton" />
                                        </FooterTemplate>
                                        <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
                                        <FooterStyle HorizontalAlign="Center" VerticalAlign="Middle" />
                                    </asp:TemplateField>
                                    <asp:TemplateField HeaderText="Country Name">
                                        <FooterTemplate>
                                            <asp:DropDownList ID="ddl_country" runat="server">
                                            </asp:DropDownList>
                                            <asp:RequiredFieldValidator ID="rfvusername111" runat="server" ControlToValidate="ddl_country"
                                                Text="*" ValidationGroup="validaiton" InitialValue="Select Country" Display="Dynamic" />
                                        </FooterTemplate>
                                        <ItemStyle HorizontalAlign="Center" VerticalAlign="Top" />
                                        <ItemTemplate>
                                            <asp:Label ID="Label1" runat="server" Text='<%# Eval("countryName") %>'></asp:Label>
                                        </ItemTemplate>
                                        <FooterStyle HorizontalAlign="Center" VerticalAlign="Middle" />
                                    </asp:TemplateField>
                                    <asp:TemplateField HeaderText="State Name">
                                        <EditItemTemplate>
                                            <asp:TextBox ID="txt_state" ValidationGroup="abc" MaxLength="35" runat="server" Text='<%#Eval("stateName") %>' />
                                            <asp:RequiredFieldValidator ID="rfvusername11" runat="server" ControlToValidate="txt_state"
                                                Text="*" ValidationGroup="abc" />
                                        </EditItemTemplate>
                                        <ItemTemplate>
                                            <asp:Label ID="lbl_state" runat="server" Text='<%#Eval("stateName") %>' />
                                        </ItemTemplate>
                                        <FooterTemplate>
                                            <asp:TextBox ID="txt_stateEnter" runat="server" MaxLength="35" />
                                            <asp:RequiredFieldValidator ID="rfvusername" runat="server" ControlToValidate="txt_stateEnter"
                                                Text="*" ValidationGroup="validaiton" />
                                        </FooterTemplate>
                                        <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
                                        <FooterStyle HorizontalAlign="Center" VerticalAlign="Middle" />
                                    </asp:TemplateField>
                                </Columns>
                                <HeaderStyle BackColor="#61A6F8" Font-Bold="True" ForeColor="White" />
                            </asp:GridView>
                        </td>
                    </tr>
                    <tr>
                        <td style="padding: 5px 0 5px 0; width: 410px;">
                            <asp:Label ID="lbl_msg" runat="server" Font-Bold="true" Font-Italic="true"></asp:Label>
                        </td>
                    </tr>
                </table>


Create a class named ManageState and put below code in it.

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

/// <summary>
/// Summary description for ManageState
/// </summary>
public class ManageState
{
    string conStr = string.Empty;

    SqlConnection con;
    SqlDataAdapter adp;
    SqlCommand cmd;
    SqlDataReader dr;

      public ManageState()
      {
            //
            // TODO: Add constructor logic here
            //
        conStr = System.Configuration.ConfigurationManager.ConnectionStrings["abc"].ConnectionString;
      }

    public DataSet RetiveData()
    {
        try
        {
            con = new SqlConnection(conStr);
            con.Open();
            cmd = new SqlCommand("ssp_SelectState", con);
            cmd.CommandType = CommandType.StoredProcedure;
            adp = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            adp.Fill(ds);
            return ds;
        }
        catch
        {
            return null;
        }
        finally
        {
            adp.Dispose();
            con.Close();
        }
    }

    public DataSet RetiveCountry()
    {
        try
        {
            con = new SqlConnection(conStr);
            con.Open();
            cmd = new SqlCommand("ssp_SELECTCOUNTRY4DDL", con);
            cmd.CommandType = CommandType.StoredProcedure;
            adp = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            adp.Fill(ds);
            return ds;
        }
        catch
        {
            return null;
        }
        finally
        {
            adp.Dispose();
            con.Close();
        }
    }

    public DataSet RetiveState(int id)
    {
        try
        {
            con = new SqlConnection(conStr);
            con.Open();
            cmd = new SqlCommand("SSP_FETCHSTATEDDL", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add("@countryID", SqlDbType.BigInt, 900000000).Value = id;
            adp = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            adp.Fill(ds);
            return ds;
        }
        catch
        {
            return null;
        }
        finally
        {
            adp.Dispose();
            con.Close();
        }
    }

    public int InsetState(int id, string name)
    {
        try
        {
            con = new SqlConnection(conStr);
            con.Open();
            cmd = new SqlCommand("ISP_INSERTSTATE", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add("@countryID", SqlDbType.BigInt, 900000000).Value = id;
            cmd.Parameters.Add("@stateName", SqlDbType.NVarChar, 50).Value = name;
            cmd.ExecuteNonQuery();
            return 1;
        }
        catch (Exception ex)
        {
            return 0;
        }
        finally
        {
            cmd.Dispose();
            con.Close();
        }
    }

    public int DeleteState(int id)
    {
        try
        {
            con = new SqlConnection(conStr);
            con.Open();
            cmd = new SqlCommand("DSP_DELETESTATE", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add("@stateId", SqlDbType.BigInt, 900000000).Value = id;
            cmd.ExecuteNonQuery();
            return 1;
        }
        catch
        {
            return 0;
        }
        finally
        {
            cmd.Dispose();
            con.Close();
        }
    }

    public int UpdateState(int id, string name)
    {
        try
        {
            con = new SqlConnection(conStr);
            con.Open();
            cmd = new SqlCommand("USP_UPDATESTATE", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add("@stateId", SqlDbType.BigInt, 900000000).Value = id;
            cmd.Parameters.Add("@stateName", SqlDbType.VarChar, 50).Value = name;
            cmd.ExecuteNonQuery();
            return 1;
        }
        catch
        {
            return 0;
        }
        finally
        {
            cmd.Dispose();
            con.Close();
        }
    }
}



Put below code into your code behind file.

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGrid();
        }
    }



    protected void BindGrid()
    {
        ManageState obj = new ManageState();

        DataSet ds = obj.RetiveData();

        if (ds.Tables[0].Rows.Count > 0)
        {
            GridView1.DataSource = ds;
            GridView1.DataBind();
        }
        else
        {
            ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
            GridView1.DataSource = ds;
            GridView1.DataBind();
            int columncount = GridView1.Rows[0].Cells.Count;
            GridView1.Rows[0].Cells.Clear();
            GridView1.Rows[0].Cells.Add(new TableCell());
            GridView1.Rows[0].Cells[0].ColumnSpan = columncount;
            GridView1.Rows[0].Cells[0].Text = "No Records Found";
        }
        obj = null;
    }



    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Footer)
        {
            DropDownList ddl = (DropDownList)e.Row.FindControl("ddl_country");
            if (ddl != null)
            {
                ManageState obj = new ManageState();
                DataSet ds = obj.RetiveCountry();

                if (ds.Tables[0].Rows.Count > 0)
                {
                    ddl.DataSource = ds;
                    ddl.DataValueField = "countryID";
                    ddl.DataTextField = "countryName";
                    ddl.DataBind();

                    ddl.Items.Insert(0, "Select Country");
                }
                else
                {
                    ddl.Items.Insert(0, "No Rows");
                }
                obj = null;
            }
        }

        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            //getting username from particular row
            string username = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "stateName"));
            //identifying the control in gridview
            ImageButton lnkbtnresult = (ImageButton)e.Row.FindControl("imgbtnDelete");
            //raising javascript confirmationbox whenver user clicks on link button
            if (lnkbtnresult != null)
            {
                lnkbtnresult.Attributes.Add("onclick", "javascript:return ConfirmationBox('" + username + "')");
            }

        }
    }



    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        //----------- ADD BUTTON --------------------

        if (e.CommandName.Equals("AddNew"))
        {
            TextBox txtStatename = (TextBox)GridView1.FooterRow.FindControl("txt_stateEnter");
            DropDownList ddl_country = (DropDownList)GridView1.FooterRow.FindControl("ddl_country");

            if (txtStatename.Text.Trim() != "" && ddl_country.SelectedIndex > 0)
            {
                ManageState obj = new ManageState();

                if (obj.InsetState(Convert.ToInt32(ddl_country.SelectedValue), txtStatename.Text.Trim()) == 1)
                {
                    BindGrid();
                    lbl_msg.Text = txtStatename.Text.Trim() + " successfully inserted !!!";
                    lbl_msg.ForeColor = System.Drawing.Color.Green;
                    txtStatename.Text = string.Empty;
                    ddl_country.SelectedIndex = 0;
                }
                else
                {
                    lbl_msg.ForeColor = System.Drawing.Color.Red;
                    lbl_msg.Text = "Error in insertion, try again !!!";
                }
                obj = null;
            }
            else
            {
                lbl_msg.ForeColor = System.Drawing.Color.Red;
                lbl_msg.Text = "Please enter country name !!!";
            }
        }
    }



    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        //---------------- EDIT BUTTON ---------------------

        GridView1.EditIndex = e.NewEditIndex;
        BindGrid();
    }



    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        //------------- ROW EDIT CANCEL BUTTON -----------------------

        GridView1.EditIndex = -1;
        BindGrid();
    }



    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        //-------------- DELETE BUTTON  -----------------------------

        int Stateid = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values["stateId"].ToString());
        string name = GridView1.DataKeys[e.RowIndex].Values["stateName"].ToString();

        ManageState obj = new ManageState();

        if (obj.DeleteState(Stateid) == 1)
        {
            lbl_msg.ForeColor = System.Drawing.Color.Green;
            lbl_msg.Text = name + " deleted successfully !!!";
            BindGrid();
        }
        else
        {
            lbl_msg.ForeColor = System.Drawing.Color.Red;
            lbl_msg.Text = "Error in deleting " + name + "'s information !!!";
        }
        obj = null;
    }



    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        int STateid = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString());
        TextBox txt_name = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txt_state");

        ManageState obj = new ManageState();

        if (txt_name.Text.Trim() != "")
        {
            if (obj.UpdateState(STateid, txt_name.Text.Trim()) == 1)
            {
                lbl_msg.ForeColor = System.Drawing.Color.Green;
                lbl_msg.Text = "State name successfully updated !!!";
                GridView1.EditIndex = -1;
                BindGrid();
            }
            else
            {
                lbl_msg.ForeColor = System.Drawing.Color.Red;
                lbl_msg.Text = "Error in updating, try again !!!";
            }
        }
        else
        {
            lbl_msg.ForeColor = System.Drawing.Color.Red;
            lbl_msg.Text = "Plese enter country name !!!";
        }
        obj = null;
    }


If you enquire any query then fill free to contact me.
Enjoy happy coding...

No comments:

Post a comment