Delete items from an ArrayList

G

Guest

I have an event below to remove items from an arraylist and then to rebind
the arraylist to the datagrid subsequently deleting the appropriate row. My
problem is that my code makes sense and I think my logic seems fine but when
I click the button on my datagrid nothing seems to happen. Have you any idea
where Im going wrong. Was thinking it might have something to do with my page
load/ postback but not really sure. Can someone please help me.

My event handler looks like the following: -

private void DataGrid1_DeleteCommand(object source,
System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
//get a reference to the ArrayList
ArrayList addresses;
addresses = (ArrayList) ViewState["Addresses"];

//get the index of the item to be deleted
//(available in the EventArgs)
int deleteIndex = e.Item.ItemIndex;

//remove from ArrayList
addresses.RemoveAt(deleteIndex);

//save back to viewstate!
ViewState("Addresses") = addresses;

//now, rebind
DataGrid1.DataSource = addresses;
DataGrid1.DataBind();
}

My datagrid code is as follows: -
<asp:datagrid id="DataGrid1" style="Z-INDEX: 108; LEFT: 26px; POSITION:
absolute; TOP: 276px" tabIndex="7" runat="server" Width="689px"
AutoGenerateColumns="false" Height="81px">
<Columns>
<asp:BoundColumn DataField="FullAddress" HeaderText="Full Address">
<HeaderStyle HorizontalAlign="Center" ForeColor="White"
BackColor="Black"></HeaderStyle>
<ItemStyle HorizontalAlign="Left"></ItemStyle>
</asp:BoundColumn>
<asp:ButtonColumn Text="Remove" CommandName="Remove">
<HeaderStyle HorizontalAlign="Center" ForeColor="White"
BackColor="Black"></HeaderStyle>
<ItemStyle HorizontalAlign="Center"></ItemStyle>
</asp:ButtonColumn>
</Columns>
</asp:datagrid>

My page load event is as follows:
private void Page_Load(object sender, System.EventArgs e)
{
ArrayList addresses;

// when the page is first loaded only
if( !IsPostBack )
{
addresses = new ArrayList(5);
ViewState["Addresses"] = addresses;
}
// on subsequent PostBacks:
else
{
addresses = (ArrayList) ViewState["Addresses"];
if( addresses != null )
{
DataGrid1.DataSource = addresses;
DataGrid1.DataBind();
}
}
}
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,

DataGrid1_DeleteCommand:

This method is ok, except this line that is not needed:
ViewState("Addresses") = addresses;

remember that you are dealing with references


The problem is in the Load event:

You are binding the grid EACHTIME you postback, you SHOULD NOT do that.
just remove the else of the if ( !IsPostBack ) and it should work fine.


Cheers,
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top