Wednesday, March 23, 2011

Binding a List or string array to ListView and operating on it

Suppose you have a Object Datasource attached to ListView and you have GetList, Delete and Insert operations set on it that would operate on a db. If that ODS primarily deals with string array, then you are about to face some challenges.
Displaying
The problem with showing a plain string array to ListView is, that array is nameless.
To overcome this, all you have to do is use Container.DataItem where it usually was Bind("Name")



Operating on the data
To delete a row from db, the only information you have in the ListView is string data. So, we have to make use of it and tie that info to every delete button (you get this when you select delete operation on the ODS) for every row. You do that in ItemDataBound event.

protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
{
string venueName = (e.Item as ListViewDataItem).DataItem.ToString();
(e.Item.FindControl("DeleteButton") as Button).CommandArgument = venueName;
}

To make insertion into db, find the input text control inside InsertItem template of ListView as shown below and in ItemCommand event, use the command name property to distinguish between operations.

protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
{
string venueName = (e.Item as ListViewDataItem).DataItem.ToString();
(e.Item.FindControl("DeleteButton") as Button).CommandArgument = venueName;
}
protected void ListView1_ItemCommand(object sender, ListViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
string venue = e.CommandArgument.ToString();
Venue.DeleteVenue(venue);
Response.Redirect(Request.Url.AbsolutePath, true);
}
else if (e.CommandName == "Insert")
{
VenueEntity venueEntity = new VenueEntity();
venueEntity.Name = (ListView1.InsertItem.FindControl("VenueTextBox") as TextBox).Text;
venueEntity.AddedBy = User.Identity.Name;
venueEntity.DateAdded = DateTime.Now;

Venue.InsertVenue(venueEntity);
Response.Redirect(Request.Url.AbsolutePath, true);
}
}

No comments:

Post a Comment