Hi
I have girdview with product id and price when the user select row from gridview the product id shpuld be added to listbox and when the user click on delete button the selected row in the listbox should be removed from the gridview ..
here is my code for selecting the item and adding them to the listbox

protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {
        GridViewRow row = GridView1.SelectedRow;
        string id = row.Cells[0].Text;
              ListItem list = new ListItem(id);
        if (ListBox1.Items.Contains(list) == false)
        {
            ListBox1.Items.Add(id);
        }

and this is what I did so far for the delete button I'm not sure if it correct

 protected void btnDeleteFromListBox_Click1(object sender, EventArgs e)
    {
        string choice = ListBox1.SelectedItem.Text;
        GridViewRow row = GridView1.SelectedRow;
        string id = row.Cells[0].Text;
        foreach (GridView a in GridView1.Rows)
        {
            if (choice == id)
            {

             }
        }
    }


}

Recommended Answers

All 2 Replies

try this:

 protected void btnDeleteFromListBox_Click1(object sender, EventArgs e)
{
    GridViewRow row = GridView1.SelectedRow;
    GridView1.Rows.Remove(row);
}

Your code is showing a GridView, but its named a ListBox? Anyway, if you're using data keys this will get row and a key(s) which can be used to remove the particular selection. This is not like above, where its only removed from the grid, to be shown again on databind.

protected void btnDeleteFromListBox_Click(object sender, EventArgs e)
{
    LinkButton lnkbtn = (LinkButton)sender;

    // command argument from selected row
    string id = lnkbtn.CommandArgument;
    GridViewRow row = (GridViewRow)lnkbtn.NamingContainer;

    // row selected
    int gridRow = row.RowIndex;
    DataKey key = GridView1.DataKeys[gridRow];

    // data key 'Key' from selected row
    string k = (string)key["Key"];

    // For testing purpose.  A method can be coded to do what ever to the record.
    // RemoveSelection(k);
    Response.Write("title: " + k + ",  Id: " + id);
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.