(2/5) ListView events, ItemInserting, ItemDeleting

1452
1
SHARE

Add Record

In order to have this ADD button work, what we need is to wire the events first in the page’s code behind.

LstItems.ItemInserting += new EventHandler<ListViewInsertEventArgs>(LstItems_ItemInserting);
LstItems.ItemDeleting += new EventHandler<ListViewInsertEventArgs>(LstItems_ItemDeleting);
LstItems.InsertItemPosition = InsertItemPosition.LastItem;

And usually, we will have this insert template either in the first item of this ListView or the last item. In this example, it is in the last item.

Button “Add” click.

protected void LstItems_ItemInserting(object sender, ListViewInsertEventArgs e)
{
    if (!Page.IsValid)
    return;

    var txtNewHost = e.Item.FindControl<TextBox>("TxtNewHost");
    var txtNewPointsTo = e.Item.FindControl<TextBox>("TxtNewPointsTo");
    var ddlNewTtl = e.Item.FindControl<DropDownList>("DdlNewTTL");

    var host = txtNewHost.Text;
    var pointsTo = txtNewPointsTo.Text;
    var ttl = ddlNewTtl.SelectedValue;

    var result = AddNewRecord();
    if (result == Status.Ok)
    {
        // Rebind the ListView
    }
    else
    {
        // Do error handling
    }
}

Button “Remove” click.

protected void LstItems_ItemDeleting(object sender, ListViewInsertEventArgs e)
{
    var item = LstItems.Items[e.ItemIndex];

    var result = RemoveRecord();
    if (result == Status.Ok)
    {
        LstItems.EditIndex = -1;

        // Rebind the ListView
    }
    else
    {
        // Do error handling
    }
}

1 COMMENT

LEAVE A REPLY