简体   繁体   中英

C# ASP.NET Add "remove button" to List in grid-view

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.

PS 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!

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:

在此处输入图像描述

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:

在此处输入图像描述

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;

        rstData.Rows[gRow.DataItemIndex].Delete();
        rstData.AcceptChanges();
        // now re-load/update grid
        LoadGrid();
    }

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

Because we are using dataitemIndex, we have to use acceptchanges. This means that we can't then update the database in one shot using a single update command, but I would suggest we then build up a list of pk values when we hit delete.

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

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)
{

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM