Gridview Inline Add/Insert, Edit/Update, Delete Data Example

16:04

Introduction

In this articales I want to show how to do inline editing in ASP.Net Griv View. Also use add functionality with validation and link button in the Grid view.

Inline editing Grid View Image




Create Project

Open Visual Studio > File > New > Project > ASP.NET MVC 4 Web Application > Basic > OK

Create a new page

Right click on the project > Add > New Item > Web Form > Change name of the web form by "GridView.aspx" > Add > Page is given below:
<form id="form1" runat="server">
        <div>
            <h2>Gridview Inline Add/Insert, Edit/Update, Delete Data Example</h2>
            <asp:Label ID="lblMsg" runat="server"></asp:Label>
            <br />

            <asp:GridView ID="gvSubDetails" runat="server" AutoGenerateColumns="False" BackColor="White" BorderColor="#3366CC" BorderStyle="None" BorderWidth="1px" CellPadding="4" Height="223px"
                OnRowCancelingEdit="gvSubDetails_RowCancelingEdit"
                OnRowCommand="gvSubDetails_RowCommand"
                OnRowDeleting="gvSubDetails_RowDeleting"
                OnRowEditing="gvSubDetails_RowEditing"
                OnRowUpdating="gvSubDetails_RowUpdating"
                DataKeyNames="SubjectId"
                ShowFooter="True"
                Width="1513px" OnRowDataBound="gvSubDetails_RowDataBound" OnPageIndexChanging="gvSubDetails_PageIndexChanging" AllowPaging="true" PageSize="8">
                <Columns>

                    <asp:TemplateField HeaderText="SubjectName" ControlStyle-Width="200px">
                        <EditItemTemplate>
                            <asp:TextBox ID="txtSubjectName" Text='<%#Eval("SubjectName") %>' runat="server" CssClass="stytext" />
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="lblSubjectName" Text='<%#Eval("SubjectName") %>' runat="server" />
                        </ItemTemplate>
                        <FooterTemplate>
                            <asp:TextBox ID="newSubjectName" runat="server" CssClass="stytext" />
                            <asp:RequiredFieldValidator ID="rfvSubjectName" runat="server" Text="*" ControlToValidate="newSubjectName" ValidationGroup="vgAdd" ForeColor="Red" />
                        </FooterTemplate>
                    </asp:TemplateField>

                    <asp:TemplateField HeaderText="Marks" ControlStyle-Width="100px">
                        <EditItemTemplate>
                            <asp:TextBox ID="txtMarks" runat="server" Text='<%#Eval("Marks") %>' CssClass="stytext" />
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="lblMarks" runat="server" Text='<%#Eval("Marks") %>' CssClass="stytext" />
                        </ItemTemplate>
                        <FooterTemplate>
                            <asp:TextBox ID="newMarks" runat="server" CssClass="stytext" />
                            <asp:RequiredFieldValidator ID="rfvMarks" runat="server" Text="*" ControlToValidate="newMarks" ForeColor="Red" ValidationGroup="vgAdd" />
                            <asp:RegularExpressionValidator ID="revMarks" runat="server" ForeColor="Red" ControlToValidate="newMarks" ValidationExpression="^[0-9]*$" Text="*Numbers" ValidationGroup="vgAdd" />
                        </FooterTemplate>
                    </asp:TemplateField>

                    <asp:BoundField DataField="Grade" HeaderText="Grade" ItemStyle-HorizontalAlign="Center" ControlStyle-Width="100px" />

                    <asp:TemplateField HeaderText="Actions" FooterStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center" ControlStyle-Width="100px">
                        <ItemTemplate>
                            <asp:LinkButton ID="btnEdit" runat="server" CommandName="Edit" Text="Edit"></asp:LinkButton>
                            <asp:LinkButton ID="btnDelete" runat="server" CommandName="Delete" Text="Delete" OnClientClick="return confirm('Are you sure you want to delete this record?')" CausesValidation="false"></asp:LinkButton>
                        </ItemTemplate>
                        <EditItemTemplate>
                            <asp:LinkButton ID="btnUpdate" runat="server" CommandName="Update" Text="Update"></asp:LinkButton>
                            <asp:LinkButton ID="btnCancel" runat="server" CommandName="Cancel" Text="Cancel"></asp:LinkButton>
                        </EditItemTemplate>
                        <FooterTemplate>
                            <asp:LinkButton ID="btnAdd" runat="server" CommandName="Add" Text="Add New" ValidationGroup="vgAdd" />
                        </FooterTemplate>
                    </asp:TemplateField>

                </Columns>
                <FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
                <HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="#CCCCFF" />
                <PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Left" />
                <RowStyle BackColor="White" ForeColor="#003399" />
                <SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
                <SortedAscendingCellStyle BackColor="#EDF6F6" />
                <SortedAscendingHeaderStyle BackColor="#0D4AC4" />
                <SortedDescendingCellStyle BackColor="#D6DFDF" />
                <SortedDescendingHeaderStyle BackColor="#002876" />
            </asp:GridView>
        </div>
    </form>

Add new database file i.e. "Database.mdf" in the App_Data

Right click on the App_Data > Add > New Item > Data > Sql Server Database > Change the name by "Database.mdf" > Add
Now create a table name "SubjectDetails". Structure of the table like this:
CREATE TABLE [dbo].[SubjectDetails] (
    [SubjectId]   INT            IDENTITY (1, 1) NOT NULL,
    [SubjectName] NVARCHAR (100) NULL,
    [Marks]       INT            NULL,
    [Grade]       NVARCHAR (50)  NULL,
    PRIMARY KEY CLUSTERED ([SubjectId] ASC)
);

Now the connection string in web.config is:

 <add name="connect" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=Database;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\Database.mdf" />

Add Connection string in "GridView.cs" file like this:

 string conn = ConfigurationManager.ConnectionStrings["connect"].ConnectionString;

Page_Load code:

protected void Page_Load(object sender, EventArgs e)
{
    lblMsg.Text = "";
    if (!IsPostBack)
    {
        BindSubjectData();
        lblMsg.Text = "";
    }
}

BindSubjectData function:

protected void BindSubjectData()
{
    using (SqlConnection sqlCon = new SqlConnection(conn))
    {
        using (SqlCommand cmd = new SqlCommand())
        {
            cmd.CommandText = "SELECT * FROM SubjectDetails";
            cmd.Connection = sqlCon;
            if (sqlCon.State == ConnectionState.Open) { sqlCon.Close(); }
            sqlCon.Open();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            da.Fill(dt);
            if (dt.Rows.Count > 0)
            {
                gvSubDetails.DataSource = dt;
                gvSubDetails.DataBind();
            }
            else
            {
                DataRow dr = dt.NewRow();
                dt.Rows.Add(dr);
                gvSubDetails.DataSource = dt;
                gvSubDetails.DataBind();
                gvSubDetails.Rows[0].Visible = false;
            }
            sqlCon.Close();
        }
    }
}

Grade function code is below:

public string getGrade(int marksValue)
{
    string Grade = "";
    if (marksValue < 30)
    {
        Grade = "Fail";
    }
    else if (marksValue > 30 && marksValue < 40)
    {
        Grade = "C";
    }
    else if (marksValue > 40 && marksValue < 50)
    {
        Grade = "B";
    }
    else if (marksValue > 50 && marksValue < 60)
    {
        Grade = "B+";
    }
    else if (marksValue > 60 && marksValue < 75)
    {
        Grade = "A";
    }
    else if (marksValue >= 75)
    {
        Grade = "A+";
    }
    return Grade;
}

RowCommand code is below:

protected void gvSubDetails_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "Add")
    {
        bool IsAdded = false;
        TextBox SubjectName = (TextBox)gvSubDetails.FooterRow.FindControl("newSubjectName");
        TextBox Marks = (TextBox)gvSubDetails.FooterRow.FindControl("newMarks");
        int marksVal = Convert.ToInt32(Marks.Text);
        string Grade = getGrade(marksVal);
        if (Grade != "")
        {
            using (SqlConnection sqlCon = new SqlConnection(conn))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    //here i'd added "@" for continuous string in new line
                    cmd.CommandText = @"INSERT INTO SubjectDetails(SubjectName,Marks,Grade)
                            VALUES(@SubjectName,@Marks,@Grade)";
                    cmd.Parameters.AddWithValue("@SubjectName", SubjectName.Text);
                    cmd.Parameters.AddWithValue("@Marks", Marks.Text);
                    cmd.Parameters.AddWithValue("@Grade", Grade);
                    cmd.Connection = sqlCon;
                    if (sqlCon.State == ConnectionState.Open) { sqlCon.Close(); }
                    sqlCon.Open();
                    IsAdded = cmd.ExecuteNonQuery() > 0;
                    sqlCon.Close();
                }
            }
        }
        if (IsAdded)
        {
            lblMsg.Text = "'" + SubjectName.Text + "' subject details added successfully!";
            lblMsg.ForeColor = System.Drawing.Color.Green;
            BindSubjectData();
            Response.Redirect("GridView.aspx");
        }
        else
        {
            lblMsg.Text = "Error while adding '" + SubjectName.Text + "' subject details";
            lblMsg.ForeColor = System.Drawing.Color.Red;
        }
    }
}

RowEditing code is below:

protected void gvSubDetails_RowEditing(object sender, GridViewEditEventArgs e)
{
    gvSubDetails.EditIndex = e.NewEditIndex;
    BindSubjectData();
}

RowCancelingEdit code is below:

protected void gvSubDetails_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
    gvSubDetails.EditIndex = -1;
    BindSubjectData();
}

RowUpdating code is below:

protected void gvSubDetails_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    bool IsUpdated = false;
    //getting key value, row id
    int SubjectID =
    Convert.ToInt32(gvSubDetails.DataKeys[e.RowIndex].Value.ToString());
    //getting row field details
    TextBox SubjectName =
    (TextBox)gvSubDetails.Rows[e.RowIndex].FindControl("txtSubjectName");
    TextBox Marks = (TextBox)gvSubDetails.Rows[e.RowIndex].FindControl("txtMarks");
    int marksVal = Convert.ToInt32(Marks.Text);
    string Grade = getGrade(marksVal);
    if (Grade != "")
    {
        using (SqlConnection sqlCon = new SqlConnection(conn))
        {
            using (SqlCommand cmd = new SqlCommand())
            {
                //here i'd added "@" for continuous string in new line
                cmd.CommandText = @"UPDATE SubjectDetails SET SubjectName=@SubjectName,
                        Marks=@Marks,Grade=@Grade WHERE SubjectID=@SubjectId";
                cmd.Parameters.AddWithValue("@SubjectId", SubjectID);
                cmd.Parameters.AddWithValue("@SubjectName", SubjectName.Text);
                cmd.Parameters.AddWithValue("@Marks", Marks.Text);
                cmd.Parameters.AddWithValue("@Grade", Grade);
                cmd.Connection = sqlCon;
                sqlCon.Open();
                IsUpdated = cmd.ExecuteNonQuery() > 0;
                sqlCon.Close();
            }
        }
    }
    if (IsUpdated)
    {
        lblMsg.Text = "'" + SubjectName.Text + "' subject details updated successfully!";
        lblMsg.ForeColor = System.Drawing.Color.Green;
    }
    else
    {
        lblMsg.Text = "Error while updating '" + SubjectName.Text + "' subject details";
        lblMsg.ForeColor = System.Drawing.Color.Red;
    }
    gvSubDetails.EditIndex = -1;
    BindSubjectData();
}

RowDeleting code is below:

protected void gvSubDetails_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
    bool IsDeleted = false;
    //getting key value, row id
    int SubjectID = Convert.ToInt32(gvSubDetails.DataKeys[e.RowIndex].Value.ToString());
    //getting row field subjectname
    Label SubjectName = (Label)gvSubDetails.Rows[e.RowIndex].FindControl("lblSubjectName");
    using (SqlConnection sqlCon = new SqlConnection(conn))
    {
        using (SqlCommand cmd = new SqlCommand())
        {
            cmd.CommandText = "DELETE FROM SubjectDetails WHERE SubjectId=@SubjectID";
            cmd.Parameters.AddWithValue("@SubjectID", SubjectID);
            cmd.Connection = sqlCon;
            sqlCon.Open();
            IsDeleted = cmd.ExecuteNonQuery() > 0;
            sqlCon.Close();
        }
    }
    if (IsDeleted)
    {
        lblMsg.Text = "'" + SubjectName.Text + "' subject details has been deleted successfully!";
        lblMsg.ForeColor = System.Drawing.Color.Green;
        BindSubjectData();
    }
    else
    {
        lblMsg.Text = "Error while deleting '" + SubjectName.Text + "' subject details";
        lblMsg.ForeColor = System.Drawing.Color.Red;
    }
}

RowDataBound code is below:

protected void gvSubDetails_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        if (e.Row.Cells[2].Text == "Fail") { applyColor(Color.Red, e); }
        else if (e.Row.Cells[2].Text == "C") { applyColor(Color.Pink, e); }
        else if (e.Row.Cells[2].Text == "B") { applyColor(Color.Blue, e); }
        else if (e.Row.Cells[2].Text == "B+") { applyColor(Color.DarkBlue, e); }
        else if (e.Row.Cells[2].Text == "A") { applyColor(Color.Green, e); }
        else if (e.Row.Cells[2].Text == "A+") { applyColor(Color.DarkGreen, e); }
    }
}

applyColor function code is below:

public void applyColor(Color color, GridViewRowEventArgs e)
{
    e.Row.Cells[2].ForeColor = color; 
    e.Row.Cells[2].Font.Bold = true;
}

PageIndexChanging code is below:

protected void gvSubDetails_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
    gvSubDetails.PageIndex = e.NewPageIndex;
    BindSubjectData();
}

Conclusion

I try to show how to create a inline data editing in GridView. Hope this will be helpfull.

Download

You can download application zip file here - 3.4 MB

You Might Also Like

0 comments