Update quantity if item already exists else add new row in ASP.Net GridView using C# and VB.Net

Last Reply 9 days ago By pandeyism

Posted 10 days ago

I am inserting item from Dropdownlist and QTY from textbox in gridview.

if item is already exit in gridview then qty get add like (if A item has 5 qty in gridview then i am inserting again 2 qty of A item then it qty get add 7)

i am using view state

DataTable dt = new DataTable();
DataRow dr;
protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        dt.Columns.Add("Descriptionitem");
        dt.Columns.Add("Qty");
        DataTable dtddl = new DataTable();
        dtddl.Columns.Add("Descriptionitem");
        dtddl.Columns.Add("Codeitem");
        dtddl.Rows.Add("A", 1);
        dtddl.Rows.Add("B", 2);
        dtddl.Rows.Add("C", 3);
        ddlItems.DataSource = dtddl;
        ddlItems.DataTextField = "Descriptionitem";
        ddlItems.DataValueField = "Codeitem";
        ddlItems.DataBind();
        ddlItems.Items.Insert(0, new ListItem("Select", "0"));
        ViewState["dt"] = dt;
    }
}

 

You are viewing reply posted by: pandeyism 9 days ago.
Posted 9 days ago

Hi akhter,

Refer below sample.

HTML

Qty :
<asp:TextBox runat="server" ID="txtqty" />
Description :
<asp:DropDownList runat="server" ID="ddlItems">
</asp:DropDownList>
<asp:Button Text="Insert" runat="server" OnClick="Insert" />
<asp:GridView runat="server" ID="GridView1" AutoGenerateColumns="false" OnRowEditing="GridView1_RowEditing">
    <Columns>
        <asp:BoundField DataField="Descriptionitem" HeaderText="Descriptionitem" />
        <asp:BoundField DataField="QTY" HeaderText="QTY" />
        <asp:TemplateField>
            <ItemTemplate>
                <asp:LinkButton ID="lnkEdit" Text="Edit" runat="server" CommandName="Edit" />
            </ItemTemplate>
            <EditItemTemplate>
                <asp:LinkButton ID="lnkUpdate" Text="Update" runat="server" OnClick="OnUpdate" />
                <asp:LinkButton ID="lnkCancel" Text="Cancel" runat="server" OnClick="OnCancel" />
            </EditItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

Namespaces

C#

using System.Data;

VB.Net

Imports System.Data

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        DataTable dtddl = new DataTable();
        dtddl.Columns.Add("Descriptionitem");
        dtddl.Columns.Add("Codeitem");
        dtddl.Rows.Add("A", 1);
        dtddl.Rows.Add("B", 2);
        dtddl.Rows.Add("C", 3);
        ddlItems.DataSource = dtddl;
        ddlItems.DataTextField = "Descriptionitem";
        ddlItems.DataValueField = "Codeitem";
        ddlItems.DataBind();
        ddlItems.Items.Insert(0, new ListItem("Select", "0"));
    }
}

protected void BindGrid()
{
    GridView1.DataSource = ViewState["dt"] as DataTable;
    GridView1.DataBind();
}

protected void Insert(object sender, EventArgs e)
{
    bool ifExist = false;
    string item = ddlItems.SelectedItem.Text;
    int quantity = Convert.ToInt16(txtqty.Text);
    DataTable dt;
    if (ViewState["dt"] == null)
    {
        dt = new DataTable();
        dt.Columns.Add("Descriptionitem");
        dt.Columns.Add("Qty");
        dt.Rows.Add(item, quantity);
        ViewState["dt"] = dt;
    }
    else
    {
        dt = ViewState["dt"] as DataTable;
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            if (dt.Rows[i]["Descriptionitem"].ToString().ToLower() == item.ToLower())
            {
                dt.Rows[i]["QTY"] = Convert.ToInt16(dt.Rows[i]["QTY"]) + quantity;
                ifExist = true;
                break;
            }
        }
        if (!ifExist)
        {
            dt.Rows.Add(item, quantity);
        }
        ViewState["dt"] = dt;
    }
    GridView1.DataSource = dt;
    GridView1.DataBind();
}

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

protected void OnUpdate(object sender, EventArgs e)
{
    GridViewRow row = (sender as LinkButton).NamingContainer as GridViewRow;
    string descriptionitem = (row.Cells[0].Controls[0] as TextBox).Text;
    int qty = Convert.ToInt32(((row.Cells[1].Controls[0] as TextBox).Text));
    DataTable dt = ViewState["dt"] as DataTable;
    dt.Rows[row.RowIndex]["Descriptionitem"] = descriptionitem;
    dt.Rows[row.RowIndex]["QTY"] = qty;
    ViewState["dt"] = dt;
    GridView1.EditIndex = -1;
    BindGrid();
}

protected void OnCancel(object sender, EventArgs e)
{
    GridView1.EditIndex = -1;
    BindGrid();
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        Dim dtddl As DataTable = New DataTable()
        dtddl.Columns.Add("Descriptionitem")
        dtddl.Columns.Add("Codeitem")
        dtddl.Rows.Add("A", 1)
        dtddl.Rows.Add("B", 2)
        dtddl.Rows.Add("C", 3)
        ddlItems.DataSource = dtddl
        ddlItems.DataTextField = "Descriptionitem"
        ddlItems.DataValueField = "Codeitem"
        ddlItems.DataBind()
        ddlItems.Items.Insert(0, New ListItem("Select", "0"))
    End If
End Sub

Protected Sub BindGrid()
    GridView1.DataSource = TryCast(ViewState("dt"), DataTable)
    GridView1.DataBind()
End Sub

Protected Sub Insert(ByVal sender As Object, ByVal e As EventArgs)
    Dim ifExist As Boolean = False
    Dim item As String = ddlItems.SelectedItem.Text
    Dim quantity As Integer = Convert.ToInt16(txtqty.Text)
    Dim dt As DataTable

    If ViewState("dt") Is Nothing Then
        dt = New DataTable()
        dt.Columns.Add("Descriptionitem")
        dt.Columns.Add("Qty")
        dt.Rows.Add(item, quantity)
        ViewState("dt") = dt
    Else
        dt = TryCast(ViewState("dt"), DataTable)
        For i As Integer = 0 To dt.Rows.Count - 1
            If dt.Rows(i)("Descriptionitem").ToString().ToLower() = item.ToLower() Then
                dt.Rows(i)("QTY") = Convert.ToInt16(dt.Rows(i)("QTY")) + quantity
                ifExist = True
                Exit For
            End If
        Next
        If Not ifExist Then
            dt.Rows.Add(item, quantity)
        End If
        ViewState("dt") = dt
    End If
    GridView1.DataSource = dt
    GridView1.DataBind()
End Sub

Protected Sub GridView1_RowEditing(ByVal sender As Object, ByVal e As GridViewEditEventArgs)
    GridView1.EditIndex = e.NewEditIndex
    BindGrid()
End Sub

Protected Sub OnUpdate(ByVal sender As Object, ByVal e As EventArgs)
    Dim row As GridViewRow = TryCast((TryCast(sender, LinkButton)).NamingContainer, GridViewRow)
    Dim descriptionitem As String = (TryCast(row.Cells(0).Controls(0), TextBox)).Text
    Dim qty As Integer = Convert.ToInt32(((TryCast(row.Cells(1).Controls(0), TextBox)).Text))
    Dim dt As DataTable = TryCast(ViewState("dt"), DataTable)
    dt.Rows(row.RowIndex)("Descriptionitem") = descriptionitem
    dt.Rows(row.RowIndex)("QTY") = qty
    ViewState("dt") = dt
    GridView1.EditIndex = -1
    BindGrid()
End Sub

Protected Sub OnCancel(ByVal sender As Object, ByVal e As EventArgs)
    GridView1.EditIndex = -1
    BindGrid()
End Sub

Screenshot