skip to Main Content

I am making a checkout program using C# and ASP.NET (because it has to work for offline(as a backup checkout register)).
I got the list working into a GridView but i want to make per added list added to the GridView that it will automatically make a "remove button".
I have tried to find in on the internet but most are database related(removing an item in database) and not just removing a row in a GridView.

what i have:

public static List<KassaItem> KassaList = new List<KassaItem>();
    
protected void Page_Load(object sender, EventArgs e)
{        
    TextBox1.Focus();
}

public string Connection(string eannr)
{
    // connection stuff here
}

public class KassaItem
{
    public string EanNr { get; set; }
    public string zoekName { get; set; }
    public int Quantity { get; set; }
    public double Price { get; set; }          

    public KassaItem(string eanNr,string zoekname, int quantity, double price)
    {
        EanNr = eanNr;
        zoekName = zoekname;
        Quantity = quantity;
        Price = price;
    }
}

protected void TextBox1_TextChanged(object sender, EventArgs e)
{       
    double TotalPrice = 0;
    string zoekfunctie = Connection(TextBox1.Text);

    string[] zoekSplit = zoekfunctie.Split('-');        

    string zoekNaam = zoekSplit[1];
    double Prijs = Convert.ToDouble(zoekSplit[0]);           

    List<KassaItem> KassaNew = new List<KassaItem>();
    bool isNew = true;

    if (TextBox1.Text != "")
    {
        foreach (var KassaItem in KassaList)
        {
            if (TextBox1.Text == KassaItem.EanNr)
            {
                KassaNew.Add(new KassaItem(KassaItem.EanNr, KassaItem.zoekName, KassaItem.Quantity + 1, KassaItem.Price + Prijs));
                isNew = false;
            }
            else
            {
                KassaNew.Add(KassaItem);
            }
        }

        if (isNew)
        {                    
            KassaNew.Add(new KassaItem(TextBox1.Text, zoekNaam, 1, Prijs));
        }

        KassaList = KassaNew;
        GridView1.DataSource = KassaList;
        GridView1.DataBind();
                            
        foreach(var item in KassaList)
        {
            TotalPrice += item.Price;                
        }

        // here i want to make a button
        foreach(var item in KassaList)
        {
            Button RemoveButton = new Button();
            RemoveButton.Text = "remove product??";
            RemoveButton.ID = "ButtonRemove_" + Item.EanNr;
        }       
    }
        
    TextBox1.Text = "";
    TextBox1.Focus();
    TotalItems.Text = TotalPrice.ToString();
}

What I want is basically:
how to make a "button" that is assigned to the row when, the row is created to delete the row when it is clicked.

P.S.
I’m also happy if i get a link to a documentation that i might not have seen/missed.
I wish you a happy new year in advance!

2

Answers


  1. Chosen as BEST ANSWER

    Thanks Albert but got a way answer to this.

    C#:

    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
        List<KassaItem> KassaNew = new List<KassaItem>();
        TableCell NR = GridView1.Rows[e.RowIndex].Cells[1];
        string eanrNR = Convert.ToString(NR.Text);
    
        string zoekfunctie = Connection(eanrNR);
        string[] zoekSplit = zoekfunctie.Split('-');
        string zoekNaam = zoekSplit[1];
        double Prijs = Convert.ToDouble(zoekSplit[0]);
    
        GridViewRow row = GridView1.Rows[e.RowIndex];
        TableCell cell = GridView1.Rows[e.RowIndex].Cells[3];
        int quantity = Convert.ToInt32(cell.Text);
        int newquantity = quantity - 1;
        if (newquantity == 0)
      {
        KassaList.RemoveAt(e.RowIndex);
      }
       else
      {
            
        foreach (var KassaItem in KassaList)
      {
      if (eanrNR == KassaItem.EanNr)
        {
        KassaNew.Add(new KassaItem(KassaItem.EanNr, KassaItem.zoekName, newquantity, KassaItem.Price - Prijs));
        }
        else
        {
          KassaNew.Add(KassaItem);
        }
      }
        KassaList = KassaNew;
      }
    
      foreach (var item in KassaList)
      {
        TotalPrice += item.Price;
    
      }
    
      GridView1.DataSource = KassaList;
      GridView1.DataBind();
    
      TextBox1.Text = "";
      TextBox1.Focus();
      TotalItems.Text = TotalPrice.ToString();
    
    }
    
    protected void GridView1_RowDeleted(object sender, GridViewDeletedEventArgs e)
    {
    
    }
    

  2. Ok, so we have a grid view. We want to drop in a simple plane jane asp.net button, and when we click on this, we delete that row. But we do NOT YET delete from the database. And we could of course have a button below the gv that says "save changes" and then the deletes would actually occur against the database.

    So, lets do the first part. GV, load with data, add delete button.

    So we have this markup:

            <asp:GridView ID="GHotels" runat="server" CssClass="table"
                width="50%" AutoGenerateColumns="False" DataKeyNames="ID" >
                <Columns>
                    <asp:BoundField DataField="FirstName" HeaderText="FirstName"     />
                    <asp:BoundField DataField="LastName" HeaderText="LastName"       />
                    <asp:BoundField DataField="HotelName" HeaderText="HotelName"     />
                    <asp:BoundField DataField="City" HeaderText="City"               />
                    <asp:BoundField DataField="Description" HeaderText="Description" />
                    <asp:TemplateField HeaderText = "Delete" ItemStyle-HorizontalAlign ="Center" >
                        <ItemTemplate>
                        <asp:Button ID="cmdDelete" runat="server" Text="Delete" 
                           CssClass="btn" 
                            />
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>
            <br />
            <asp:Button ID="cmdSave" runat="server" Text="Save Changes" CssClass="btn" />
            <asp:Button ID="cmdUndo" runat="server" Text="Undo Changes" CssClass="btn"
                style="margin-left:25px" />
    

    I dropped in two buttons below the GV – we deal with those later.

    So, now here is our code to load the GV – NOTE very careful how we persit the table that drives this table. So we can load the table from database, and now our operations can occur against that table that drives the gv – but we do NOT send the changes back to the database (changes in this case = deletes – but it could be edits or additions if we want – and that’s easy too!).

    Ok, so our code is this:

        DataTable rstData = new DataTable(); // data to drive grid
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadData();
                Session["rstData"] = rstData;
                LoadGrid();
            }
            else
            {
                rstData = Session["rstData"] as DataTable;
            }
        }
    
        void LoadData()
        {
            using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
            {
                string strSQL = "SELECT * FROM tblHotels ORDER BY HotelName";
                using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
                {
                    conn.Open();
                    rstData.Load(cmdSQL.ExecuteReader());
                }
            }
        }
    
        void LoadGrid()
        {
            GHotels.DataSource = rstData;
            GHotels.DataBind();
        }    
    }
    

    and now we have this:

    enter image description here

    So, now lets add the code behind event stub for the delete button:

    We can’t double click on the button to jump to the click code behind event stub, so we have to type into the markup the onclick= (note VERY close how you are THEN offered to create a click event for the button. You see this:

    enter image description here

    So, we choose create new event (don’t look like much occures, but we can now flip to code behind – and you see our event stub created for us.

    Ok, so all we have to do is delete (remove) the row from the gv. The code looks like this:

        protected void cmdDelete_Click(object sender, EventArgs e)
        {
            Button btn = sender as Button;
            GridViewRow gRow = btn.NamingContainer as GridViewRow;
            int? pkID = (int?)GHotels.DataKeys[gRow.DataItemIndex]["ID"];
            // find row and delete
            DataRow[] DelRow = rstData.Select("ID = " + pkID);
            DelRow[0].Delete();
            LoadGrid();
        }
    

    Now, the delete code was a bit messy. In MOST cases, I could have done just this:

    rstData.Rows[gRow.DataItemIndex].Delete();
    

    However, when you delete from the table, we NOT YET done a rstData.AcceptChanges. So the row sync between table and Gv gets messed up.

    Now I COULD DO a accept changes to the table, but if we do that, then we LOSE the deleted rows – and we NEED that for the single final save button that would actually commit and do the deletes. So we use find on the table by PK row id, and we eliminate this issue but MORE important PERSERVE the deleted rows in that data table. (by NOT doing accept changes). And we do that, since now we can send with ONE SINGLE update to the database, the deleted rows. However, as noted, the problem is that when you delete the rstData row, but not accept changes – it STILL exists, an thus when we feed to GV, those deleted rows don’t show – but the data index is still set, but dataindex at that point does not match rows from the table.

    So, now when we click on the delete button, the row will be deleted. But we not deleted the row from the database.

    The undo command? Well, it would just run the same code we have on first page (postback = false) code, and thus we could un-do deletes with great ease.

    As you can see – not a lot of code here.

    And if you wish, I can post the actual delete code we would use for this to commit the deletes to the database. With above, it is only ONE update command to send the deletes to the database.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search