I display some images in a datalist by getting the images from folder.
Now, I want to delete the image in folder when I click the Delete button on my datalist .
Here is my delete button code:
protected void delete_onClick(object sender, EventArgs e)
{
string fileName = sender as string;
File.Delete(Server.MapPath(fileName));
FileInfo fInfo;
fInfo = new FileInfo(fileName);
fInfo.Delete();
gvImages.DataBind();
}
I don't know how to get the exact image name which I want to delete, there is a delete button with each image.
Here is my datalist:
<div>
<asp:DataList ID="gvImages" RepeatColumns="5" RepeatDirection="Horizontal" GridLines="Horizontal"
runat="server" BorderColor="#336699" BorderStyle="Solid" ShowHeader="true">
<ItemTemplate>
<center>
<table>
<tr>
<td style="width: 90px; height: 90px">
<img id="PICID" runat="server" src='<%# Container.DataItem %>' alt='' style="height: 100px;
width: 100px;" />
<br />
<asp:Button ID="Delete" Height="22px" OnClick="delete_onClick" Width="100px" runat="server"
Text="Delete Picture" /><br />
</td>
</tr>
</table>
</center>
</ItemTemplate>
</asp:DataList>
</div>
Nesting functions as you have done is a poor programming practice:
File.Delete(Server.MapPath(fileName));
Try is like this and then when you debug, you will be able to see what file you are are trying to delete:
string fileName = e.CommandArgument;
fileName = Server.MapPath(fileName);
File.Delete(fileName);
Also, are you getting an error? An exception? Why isn't there an exception handler around the code?
you should use commandName on button. And you should use OnDeleteCommand on DataList.
<div>
<asp:DataList OnDeleteCommand="Delete_Command" ID="gvImages" RepeatColumns="5" RepeatDirection="Horizontal" GridLines="Horizontal"
runat="server" BorderColor="#336699" BorderStyle="Solid" ShowHeader="true">
<ItemTemplate>
<center>
<table>
<tr>
<td style="width: 90px; height: 90px">
<img id="PICID" runat="server" src='<%# Container.DataItem %>' alt='' style="height: 100px;
width: 100px;" />
<br />
<asp:Button ID="Delete" Height="22px" CommandName="Delete" Width="100px" runat="server"
Text="Delete Picture" /><br />
</td>
</tr>
</table>
</center>
</ItemTemplate>
</asp:DataList>
</div>
Then,
For example Hold FileName:
<asp:Button CommandArgument ='<%# Container.DataItem %>' />
Then,
public void Delete_Command(Object sender, DataListCommandEventArgs e)
{
//you can hold filename on Button's CommandArgument
string fileName = e.CommandArgument;
File.Delete(Server.MapPath(fileName));
FileInfo fInfo;
fInfo = new FileInfo(fileName);
fInfo.Delete();
gvImages.DataBind();
}
Related
I have created a table in my .aspx file that looks like this:
Here is the code that does this:
<!-- code for generating the "add selected sessions" button -->
<table>
<tr>
<td><strong>Individual Sessions</strong></td>
<td >
<div class="addButton" style="text-align: center;">
<asp:LinkButton ID="LinkButton2" runat="server" Text="Add Selected Sessions" OnClick="btnAddToCart_Click" />
</div>
</td>
</tr>
</table>
<!-- add all the sessions for the user to select -->
<asp:Repeater ID="rptFeesSession" runat="server">
<HeaderTemplate>
<table >
</HeaderTemplate>
<ItemTemplate>
<asp:HiddenField ID="hdnIsSession" runat="server" Value='<%#Eval("isSession")%>' />
<tr runat="server" visible='<%# Eval("isSession")%>'>
<td valign="top" colspan="2" style="position: relative;">
<asp:HyperLink CssClass="siteColorFG popBtn" ID="hlFeeType" runat="server" Text='<%#Eval("title")%>' NavigateUrl="javascript:;"/>
</td>
<td valign="top">
<div class="">
<asp:CheckBox ID="LinkButton3" CommandArgument='<%#Eval("id")%>'CssClass="checkB" OnClick="btnAddToCart_Click" runat="server" Text='<%#Eval("amount", "{0:C}")%>' />
</div>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
In my code behind file i want to capture all the checkboxes that have been checked and their respective CommandArgument values.
protected void btnAddToCart_Click(object sender, EventArgs e)
{
using (MyEntities db = new MyEntities())
{
//button was clicked. fetch all the check boxes from the rptFeesSession repeater into an int[]
}
}
There are several issues in your code (including conceptual / logic)
Item events in a Repeater should address item related things.
Click event handler has no access to CommandArgument attribute. Use Command instead.
Checkbox control doesn't support onclick event.
Checkbox events can run immediately only when there is AutoPostback="true".
If you want to refresh all repeater data on change of any checkbox then you can do something like this.
<asp:ScriptManager runat="server" ID="scriptMgr" /><%-- Strongly recommended --%>
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:Repeater ID="rptFeesSession" runat="server">
<HeaderTemplate>
<table>
</HeaderTemplate>
<ItemTemplate>
<asp:HiddenField ID="hdnIsSession" runat="server" Value='<%#Eval("isSession")%>' />
<tr runat="server" visible='<%# Eval("isSession")%>'>
<td colspan="2" style="position: relative;">
<asp:HyperLink CssClass="siteColorFG popBtn" ID="hlFeeType" runat="server" Text='<%#Eval("title")%>' NavigateUrl="javascript:;" />
</td>
<td>
<div class="">
<asp:HiddenField runat="server" ID="hidID" Value='<%#Eval("id") %>' />
<asp:CheckBox ID="LinkButton3"
AutoPostBack="true" CssClass="checkB"
OnCheckedChanged="LinkButton3_CheckedChanged" runat="server"
Text='<%#Eval("amount", "{0:C}")%>' />
</div>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
</ContentTemplate>
</asp:UpdatePanel>
//.cs
protected void LinkButton3_CheckedChanged(object sender, EventArgs e)
{
decimal total = 0;
using (MyEntities db = new MyEntities())
{
foreach (RepeaterItem item in rptFeesSession.Items)
{
var chk = item.FindControl("LinkButton3") as CheckBox;
if(chk!=null && chk.Checked){
string id = (item.FindControl("hidID") as HiddenField).Value;
total += decimal.Parse(chk.Text);
//do stuff
}
}
}
}
I'm trying to retain the index of the Datalist item on page reload. I'm trying to do this by storing the index into a Session and then setting the index of DataList object equals to the Session. Here's the HTML code:
<asp:DataList ID="MyList" Width="100%" RepeatDirection="Vertical" runat="server"
OnItemDataBound="MyList_ItemDataBound" OnItemCommand="MyList_ItemCommand">
<ItemTemplate>
<table class="table">
<tr>
<td style="width: 5%;">
<asp:Label ID="lbl_id" runat="server" Text='<%# Eval("id") %>' Visible="false" />
<asp:Label ID="lbl_isread" runat="server" Text='<%# Eval("isread") %>' Visible="false" />
<input type="checkbox" id="chk_vd" runat="server" class="chkitem" />
</td>
<td style="width: 15%;">
<asp:HyperLink ID="usr" runat="server" Text='<%# Eval("from") %>' />
</td>
<td style="width: 62%;">
<asp:LinkButton ID="sub" Text='<%# Eval("subject") %>' CommandName="select" runat="server"></asp:LinkButton>
</td>
<td style="width: 18%;">
<asp:Label ID="dt" runat="server" Text='<%# Eval("Date_Added") %>' />
</td>
</tr>
</table>
</ItemTemplate>
<SelectedItemTemplate>
<table class="table">
<tr>
<td style="width: 5%;">
<asp:Label ID="lbl_id" runat="server" Text='<%# Eval("id") %>' Visible="false" />
<asp:Label ID="lbl_isread" runat="server" Text='<%# Eval("isread") %>' Visible="false" />
<asp:Label ID="lbl_messagetype" runat="server" Text='<%# Eval("messagetype") %>'
Visible="false" />
<asp:Label ID="lbl_groupid" runat="server" Text='<%# Eval("groupid") %>' Visible="false" />
<asp:Label ID="lbl_content_id" runat="server" Text='<%# Eval("content_id") %>' Visible="false" />
<asp:Label ID="lbl_sendertype" runat="server" Text='<%# Eval("sendertype") %>' Visible="false" />
<input type="checkbox" id="chk_vd" runat="server" class="chkitem" />
</td>
<td style="padding: 5px; text-align: left; vertical-align: top; width: 15%;">
<uc1:avator ID="avt" runat="server" UserName='<%# Eval("from") %>' PhotoName="" Width="65"
Height="65" />
<br />
<asp:HyperLink ID="usr" runat="server" Text='<%# Eval("from") %>' />
</td>
<td style="padding: 5px; text-align: left; vertical-align: top; width: 62%;">
<div class="item_pad_4">
<h3 id="s_sub" runat="server">
<%# Eval("subject") %>
</h3>
</div>
<asp:Label ID="msg" runat="server" Text='<%# Eval("body") %>'></asp:Label>
<div class="bx_br_tp item_pad_4">
<div class="btn-group" id="<%# Eval("id") %>">
<asp:LinkButton ID="a" CssClass="btn btn-primary btn-xs" runat="server" />
<asp:LinkButton ID="r" CssClass="btn btn-primary btn-xs" runat="server" />
<%-- <asp:LinkButton ID="lnk_spam" CssClass="btn btn-primary btn-xs" runat="server"
Text="spam" CommandName="spam"></asp:LinkButton>--%>
</div>
</div>
</td>
<td style="padding: 5px; text-align: left; vertical-align: top; width: 18%;">
<asp:Label ID="dt" runat="server" Text='<%# Eval("Date_Added") %>' />
</td>
</tr>
</table>
</SelectedItemTemplate>
</asp:DataList>
On the server side, I'm trying to restore the index of the DataList item as follows:
if (!Page.IsPostBack)
{
if (Session["datalist"] != null)
{
((DataList)Session["datalist"]).SelectedIndex = (int)Session["index"];
}
Here's the function which does data binding :
protected void MyList_ItemCommand(object source, DataListCommandEventArgs e)
{
Session["datalist"] = source;
string cmd = ((LinkButton)e.CommandSource).CommandName;
long messageid = long.Parse(((Label)e.Item.FindControl("lbl_id")).Text);
string username = ((HyperLink)e.Item.FindControl("usr")).Text;
// approve / ignore action related values
long content_id = 0;
long groupid = 0;
int messagetype = 0;
int index = e.Item.ItemIndex;
Session["index"] = index;
index = (int)Session["index"];
switch (cmd)
{
case "select":
((DataList)source).SelectedIndex = e.Item.ItemIndex;
int isread = int.Parse(((Label)e.Item.FindControl("lbl_isread")).Text);
// mark message as read it its unread message
if (isread == 0)
{
isread = 1; // message is read
MailBoxBLL.Update_isRead(messageid, isread, Page.User.Identity.Name);
}
string _cache = "usr_msg_cnt_" + UserName;
if (HttpContext.Current.Cache[_cache] != null)
{
Cache.Remove(_cache);
}
break;
This doesn't work and Datalist item does not get selected when the page reloads. How can I make it work?
Any help is appreciated.
Add this directly in Page Load:-
protected void Page_Load(object sender, EventArgs e)
{
if (Session["datalist"] != null)
((DataList)Session["datalist"]).SelectedIndex = (int)Session["index"];
}
The probelm with your code is that the Page.IsPostBack property will be false in the initial get request and for every page reload (actual postback) it will be true. Thus !Page.IsPostBack will become actually false and your code will never execute.
I have an item repeater that displays items that have been bid on by a user. The items are contained within a panel as they contain form elements to update the bid for each item individually. What I would like is for the user to be able to submit the individual item to be updated and for me to know which item they are trying to update so I can ignore all other fields when processing the update.
Right now, my repeater looks like:
<asp:Repeater ID="itemRepeater" runat="server" onitemdatabound="itemRepeater_DataBound">
<ItemTemplate>
<!-- Auction Item MASTER-->
<asp:Panel id="pnlDefaultButton" runat="server" DefaultButton="absenteeBtnBid">
<div style="position: absolute; left: 0px; top: 0px; transform: translate(0px, 236px);" class="item auction_item firearm user_item isotope-item">
<div class="item_image">
<asp:HyperLink ID="item_img_link" runat="server" Visible="False" EnableViewState="False">
<asp:Image ID="item_img" runat="server" Visible="False" EnableViewState="False" Width="224" />
</asp:HyperLink>
</div>
<div class="item_overlay">
<div class="item_buttons">
Following
<asp:Label ID="absenteeBidLabel" runat="server" Text="" CssClass="absenteePlaceBidLabel" AssociatedControlID="absenteeBid" style="font-size:11px;" Visible="false">
<asp:TextBox ID="absenteeBid" runat="server" Wrap="False" CssClass="absenteePlaceBid" placeholder="Enter Bid" />
</asp:Label>
<asp:TextBox ID="absenteeBidId" runat="server" Wrap="False" CssClass="timedPlaceBid" style="display:none;" Visible="false" />
<asp:TextBox ID="absenteeBidClose" runat="server" Wrap="False" CssClass="timedPlaceBid" style="display:none;" Visible="false" />
<asp:TextBox ID="absenteeBidSaleId" runat="server" Wrap="False" CssClass="timedPlaceBid" style="display:none;" Visible="false" />
<asp:Button runat="server" ID="absenteeBtnBid" cssClass="startbidding_button edit_button" OnClick="onclick_absenteeBid" Text="Edit Bid" />
<div class="bid_options">
Live Bid
Bid by Phone
<asp:HyperLink ID="bid_withdraw" runat="server" CssClass="withdrawbid"></asp:HyperLink>
</div>
</div>
<table class="item_bidstatus" border="0" cellpadding="0" cellspacing="0" width="190">
<tbody>
<tr>
<td class="status_label" width="50%">Bids:</td>
<td class="status_value" width="50%"><asp:Label ID="bid_count" runat="server" Text="0" /></td>
</tr>
<tr>
<td class="status_label">My Top Bid:</td>
<td class="status_value"><asp:Literal ID="bid_amount" runat="server"></asp:Literal></td>
</tr>
<tr>
<td class="status_label">Your Status:</td>
<td class="status_value status_low">LOW BID</td>
</tr>
</tbody>
</table>
<div class="item_description">
<h5>
<asp:HyperLink ID="labelLot" runat="server">Lot #<%# Eval("item_lot")%></asp:HyperLink> - <asp:HyperLink ID="item_title" runat="server"><%# Eval("item_title")%></asp:HyperLink>
</h5>
<asp:Label ID="labelEst" runat="server" Visible="false"></asp:Label>
<p class="item_details"><asp:Label ID="labelDesc" runat="server"><%# Eval("item_desc")%></asp:Label></p>
> Item Details
</div>
</div>
<table class="item_footer" width="100%">
<tbody>
<tr>
<td><div class="item_category"><asp:HyperLink ID="item_sale" runat="server"></asp:HyperLink></div></td>
<td><div class="item_daysleft">Bid left: <asp:Literal ID="bid_time" runat="server"></asp:Literal></div></td>
</tr>
</tbody>
</table>
</div>
</asp:Panel>
<!-- /Auction Item MASTER-->
</ItemTemplate>
</asp:Repeater>
So my question would be how do I make the method onclick_absenteeBid only look at the form fields within the panel where the submission was made? Or am I even going about this the right way at all using a panel within a repeater?
Thre's nothing wrong with this approach. You have to find the container panel in the button's click event and find controls inside it. Here's how you can do it:
protected void onclick_absenteeBid(object sender, EventArgs e)
{
Panel pnl = ((Button) sender).Parent as Panel;
if (pnl != null)
{
//Access controls inside panel here like this:
TextBox absenteeBidId = pnl.FindControl("absenteeBidId") as TextBox;
if(absenteeBidId != null)
{
string myAbsenteeBidId = absenteeBidId.Text;
}
//Access Repeater Item
RepeaterItem itm = pnl.NamingContainer as RepeaterItem;
if (itm != null)
{
// Do stuff
}
}
}
Am using a modal pop for a grid view column where the grid view is set with timer.
<asp:UpdatePanel ID="GridPanel" runat="server">
<ContentTemplate>
<asp:Timer ID="autorefresh" runat="server" Interval="5000" />
<asp:GridView ID="SigmaGrid" runat="server" AutoGenerateColumns="False"
onrowcommand="SigmaGrid_RowCommand" CssClass="mGrid" PagerStyle-CssClass="pgr"
AlternatingRowStyle-CssClass="alt" AllowPaging="True"
onpageindexchanging="SigmaGrid_PageIndexChanging">
<AlternatingRowStyle CssClass="alt" />
<PagerStyle />
<Columns>
<asp:TemplateField HeaderText="FirstName" SortExpression="FirstName">
<ItemTemplate>
<asp:LinkButton ID="FirstName" runat="server" Text='<% # Eval("FirstName") %>' CommandName="Select"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<PagerStyle CssClass="pgr" />
</asp:GridView>
<asp:Panel ID="DtlsPanel" runat="server" BackColor="White" Height="400" Width="500px" >
<table style="border: Solid 3px #626262; width: 100%; height: 100%"
cellpadding="0" cellspacing="0">
<tr style="background-color: #626262">
<td colspan="2" style="height: 10%; color: White; font-weight: bold; font-size: larger"
align="center">
Records
</td>
</tr>
<tr>
<td style="color: Black">
First Name:
</td>
<td align="center" style="color: Black">
<asp:Label ID="FNamelbl2" runat="server"></asp:Label>
</td>
</tr>
</table>
</asp:Panel>
<asp:Button ID="btnPopUp" runat="server" Style="display: none" />
<asp:ModalPopupExtender ID="DetailsPopUp1" runat="server" BackgroundCssClass="modalBackground"
TargetControlID="btnPopUp" PopupControlID="DtlsPanel" CancelControlID="btnCancel"
PopupDragHandleControlID="PopupHeader">
</asp:ModalPopupExtender>
</ContentTemplate>
</asp:UpdatePanel>
Code
protected void SigmaGrid_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
LinkButton FirstName = (LinkButton)e.CommandSource;
GridViewRow row = (GridViewRow)FirstName.NamingContainer;
FNamelbl2.Text = FirstName.Text;
this.DetailsPopUp1.Show();
}
}
Problem
Whne i click on firstname colunn i get a pop up which displays the details of a row.. As i have used timer gridview is refreshed and pop up is automatically closing.
If you're using a ModalPopupExtender with postbacks, you should ensure in codebehind that the popup will be shown. Therefore you can use it's method Show.
For example in the page's or UserControl's PreRender:
C#
protected void Page_PreRender(object sender, System.EventArgs e)
{
if (this.Visible) {
this.DetailsPopUp1.Show();
}
}
VB.NET
Private Sub Page_PreRender(sender As Object, e As System.EventArgs) Handles Me.PreRender
If Me.Visible Then
Me.DetailsPopUp1.Show()
End If
End Sub
I have the following markup:
<tr>
<td valign="top" align="left">
<asp:Label ID="Label1" runat="server" Text="Available Roles" />
<br />
<asp:ListBox ID="availableRolesListBox" runat="server" SelectionMode="Multiple" Width="100px" Rows="10" AutoPostBack="false" />
</td>
<td valign="top" align="center">
<br />
<asp:Button ID="addToRole" runat="server" Text="--->" OnClick="addToRole_Click" />
<br />
<asp:Button ID="removeFromRole" runat="server" Text="<---" OnClick="removeFromRole_Click" />
</td>
<td valign="top" align="left">
<asp:Label ID="Label2" runat="server" Text="User In Roles" />
<br />
<asp:ListBox ID="userInRolesListBox" runat="server" SelectionMode="Multiple" Width="100px" Rows="10" AutoPostBack="false" />
</td>
</tr>
And the following in code-behind:
protected void addToRole_Click(object sender, EventArgs e)
{
// Add user to the selected role...
foreach (ListItem myItem in availableRolesListBox.Items)
{
if (myItem.Selected)
{
Roles.AddUserToRole(userListBox.SelectedItem.Value, myItem.Text);
}
}
Refresh();
}
When I step into the code-behind absolutely no items are selected! What am I forgetting?
Are you perhaps rebinding the availableRolesListBox each time, instead of if(!IsPostback)?
You could check a few things.
CHeck that you are NOT reloading the listbox after each postback. Also, you might want to make sure you do not have ViewStateEnabled="false" for a parent container.
Other than that your code looks like it should be ok, debugging any further would require more code or information.