Wednesday, 16 January 2013 13:54

how to edit,update,delete items in DataList

Written by 
Rate this item
(1 Vote)

If you used itemtemplate for items in datalist control then
you can easily delete,edit and then update items
using edititemtemplate.to do that add a itemtemplate and
edititemtemplate in the datalist.also you have to add
command buttons and command event handlers -

<asp:DataList ID="DataList1" DataKeyField="CommentId" runat="server"
OnEditCommand="DataList1_EditCommand" OnDeleteCommand="DataList1_DeleteCommand"
OnCancelCommand="DataList1_CancelCommand" OnUpdateCommand="DataList1_UpdateCommand">

<ItemTemplate>
<asp:LinkButton ID="Edit" Text="Edit" CommandName="Edit" Font-Size="9" runat="server" />
<asp:LinkButton ID="delete" Text="Delete" CommandName="Delete" Font-Size="9" runat="server" />
</div>

<div class="ViewMain">
<div class="commentdiv" style="float:left;"><asp:TextBox ID="Comments"
Enabled="false" runat="server" Text='<%# Bind("Comment")%>' ></asp:TextBox></div>
</div>
</ItemTemplate>
<EditItemTemplate>
<div style=" margin-left:110px;">
<asp:LinkButton ID="Button1" runat="server" Font-Size="9" CommandName="Update" Text="Update" />
<asp:LinkButton ID="Button2" runat="server" Font-Size="9" CommandName="Cancel" Text="Cancel" />
</div>

<div id="ViewMain">
<div class="commentdiv" style="float:left;"><asp:TextBox ID="Comments" Enabled="true"
runat="server" Text='<%# Bind("Comment")%>' ></asp:TextBox></div>
</div>
</EditItemTemplate>

define command event handlers in code behind file -

protected void DataList1_EditCommand(object source, DataListCommandEventArgs e)
{
//call edit item template for selected index
DataList1.EditItemIndex = e.Item.ItemIndex;
bindgrid();//it will populate datalist again
}
protected void DataList1_DeleteCommand(object source, DataListCommandEventArgs e)
{
int deleteid = Convert.ToInt32(DataList1.DataKeys[e.Item.ItemIndex]);
MS_Comments_Controller control = new MS_Comments_Controller();
control.MS_Comments_DeleteComment(deleteid, ModuleId);
//all chlid datalist items must be deleted
DataList1.EditItemIndex = -1;
bindgrid();//it will populate datalist again
}
protected void DataList1_UpdateCommand(object source, DataListCommandEventArgs e)
{
Int32 cid;
String comment;
cid = Convert.ToInt32(DataList1.DataKeys[e.Item.ItemIndex]);
comment = ((TextBox)(e.Item.FindControl("Comments"))).Text;

MS_Comments_Controller control = new MS_Comments_Controller();
control.MS_Comments_UpdateComment(cid, comment, ModuleId);
DataList1.EditItemIndex = -1; //without it not works
bindgrid();//it will populate datalist again
}
protected void DataList1_CancelCommand(object source, DataListCommandEventArgs e)
{
DataList1.EditItemIndex = -1;//Call Item Template //without it not works
bindgrid();//it will populate datalist again
}

Read 6256 times
Super User

Email This email address is being protected from spambots. You need JavaScript enabled to view it.

Latest discussions

  • No posts to display.