How could I use Content.ItemIndex in Code behind ASP.NET? - c#

I have this code on ASPX
<div class="col-md-8 col-sm-12 text-poster-box">
<p tabindex="1">
<asp:Label ID="LabelResultName" CssClass="h3" runat="server">Name: <%# Eval("Name") %> </asp:Label>
</p>
<p tabindex="2">
<asp:Label ID="LabelResultPrice" CssClass="h3" runat="server">Price: <%# Eval("Price") %>$ </asp:Label>
</p>
<p tabindex="3">
<asp:Label ID="LabelResultSalePrice" runat="server" CssClass="h3" Visible='<%#Eval("SalePrice").ToString() != "" ? true : false %>'>New Price: <%#Eval("SalePrice")%>$</asp:Label>
</p>
<p tabindex="4">
<asp:Label ID="LabelSize" CssClass="h3" runat="server">Size: <%# Eval("Size") %></asp:Label>
</p>
<p tabindex="5">
<asp:Button ID="ButtonRemove" runat="server" CssClass="btn btn-primary-c wishlist" Text="Remove" OnClick="ButtonRemove_Click" />
</p>
<p tabindex="6">
<asp:Label ID="lblListNumber" Text='<%# Container.ItemIndex%>' runat="server" Visible="true" /></td>
</p>
</div>
and i would like to use the number given by Content.ItemIndex in Code Behind so I could remove from List<T> of objects like this:
MyList.RemoveAt("value received from Content.ItemIndex")
I have no clue if this is even possible?

I would use onitemcommand for the repeater.
For example:
<asp:Repeater id="rptYourPages" runat="server" onitemcommand="rpt_ItemCommand">
Then add CommandArgument with an Eval for the ID of the record to the button.
CommandArgument='<%# Eval("ProductID") %>'
Your Button code would look like this:
<asp:Button ID="ButtonRemove" runat="server" CssClass="btn btn-primary-c wishlist" Text="Remove" CommandArgument='<%# Eval("ProductID") %>' />
You don't need the OnClick.
In the code behind file:
protected void rpt_ItemCommand(object source, RepeaterCommandEventArgs e)
{
string sProductID = e.CommandArgument.ToString();
// Write your logic here...
}
Hope this helps.

Related

Why Button is not working in my datalist control?

I'm using a datalist control to show product details before adding to cart. But here add to cart button is not working. How can I resolve this problem?
Here is the code of datalist control
<asp:DataList ID="DataList1" runat="server" DataSourceID="SqlDataSource1" OnItemCommand="DataList1_ItemCommand">
<ItemTemplate>
<div class="container" style="z-index:-1;">
<div class="wrapper" style="margin-left:400px;" >
<div class="databox effect1">
<div id="imagedata" style="padding:10px">
<asp:Image ID="product_imageLabel" runat="server" Height="300px" Width="300px"
ImageUrl='<%# "data:Image/png;base64,"
+ Convert.ToBase64String((byte[])Eval("product_image")) %>'/>
</div>
<div style="margin-top:-300px;margin-left:310px;padding:10px">
<asp:Label ID="product_nameLabel" runat="server" Text='<%# Eval("product_name") %>' Font-Size="XX-Large" Font-Bold="True" />
<br/>
<asp:Label ID="product_compositionLabel" runat="server" Text='<%# Eval("product_composition") %>' Font-Size="Larger"/>
<br/>
<asp:Label ID="brand_nameLabel" runat="server" Text='<%# "Brand Name : "+Eval("brand_name") %>' Font-Size="Larger" />
<br/>
<asp:Label ID="product_stock_unitLabel" runat="server" Text='<%# Eval("product_stock_unit")+" of "+Eval("product_quantity")+" "+Eval("product_quantity_unit") %>' Font-Size="Larger"/>
<br/>
<asp:Label ID="product_priceLabel" runat="server" Text='<%# "MRP ₹ "+Eval("product_price") %>' ForeColor="#0E8CE4" Font-Size="Larger" />
<br/>
<br/>
<asp:Label ID="Label_product_code" runat="server" Text='<%# "Product Code : "+Eval("product_code") %>' Font-Size="Larger"/>
<br/>
<asp:Button ID="Button_addtocart" runat="server" Text="Add to cart" CssClass="btn third" CommandName="addtocart" CommandArgument='<%# Eval("product_code")%>' />
</div>
</div>
</div>
</div>
</ItemTemplate>
</asp:DataList>
Here is the code of c# against OnItemCommand handler
protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName == "addtocart")
{
ClientScript.RegisterStartupScript(this.GetType(), "randomtext", "not_login()", true);
}
}
Add
onclick = "DataList1_ItemCommand"
in your HTML button code
because onclick Event Main Tips. The "onclick" event occurs when the user clicks on an element. It runs a specified line of code when you click an HTML object that has the “onclick” attribute. The event can be triggered by "object.onclick" or "object.addEventListener".

Prevent refresh page on list view button click in asp .net

I'm working on product cart page. Below is the code I'm working with. In the list view I'm getting all the products images as buttons. I want to update the carousel when any of the image in the list view clicked.
But When I click the image the page refreshes, I tried using update panel but since the button are dynamic can't able to find a proper way to handle it.
<div class="col-md-8 single-top-in simpleCart_shelfItem">
<div style="align-content: center">
<strong>CLICK THE IMAGE TO SELECT </strong>
</div>
<asp:ListView ID="ImagesList" runat="server"
DataKeyNames="ID"
GroupItemCount="14"
OnPagePropertiesChanging="ImagesList_PagePropertiesChanging" class="data" OnSelectedIndexChanged="OnSelectedIndexChanged">
<EmptyDataTemplate>
No Images found.
</EmptyDataTemplate>
<LayoutTemplate>
<table>
<tr runat="server" id="groupPlaceholder" />
</table>
</LayoutTemplate>
<GroupTemplate>
<tr>
<td runat="server" id="itemPlaceholder" />
</tr>
</GroupTemplate>
<ItemTemplate>
<td>
<div class="data" data-image='<%#"assets/products/"+Eval("ImageUrl").ToString() %>'
data-name='<%# Eval("Description") %>' data-price='<%# Eval("Price") %>'
data-image1='<%#"assets/products/1_"+Eval("ImageUrl").ToString() %>'
data-image2='<%#"assets/products/2_"+Eval("ImageUrl").ToString() %>'>
<asp:LinkButton ID="GridBtn" runat="server" CssClass="myButton"
CommandName="Change"
OnCommand="btnDetails_Command"
CommandArgument='<%# Eval("Notes") %>'>
<img src='<%#"assets/products/"+Eval("ImageUrl").ToString() %>' class="image" style="width: 50px; height: 50px" alt="Change" /></asp:LinkButton>
</div>
</td>
</ItemTemplate>
</asp:ListView>
</div>
<div class="col-md-4 single_left pull-left left">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<fieldset>
<div class="flexslider">
<ul class="slides">
<li id="image3" data-thumb="">
<%--<img id="image3" src="assets/products/1_ZP244.jpg" />--%>
<img id="image" src="assets/products/1_ZP244.jpg" />
<%-- <asp:Image ID="image" src="assets/products/1_ZP244.jpg" runat="server" />--%>
</li>
<li id="image4" data-thumb="">
<%--<img id="image4" src="assets/products/1_ZP244.jpg" />--%>
<img id="image1" src="assets/products/1_ZP244.jpg" />
<%--<asp:Image ID="image1" src="assets/products/1_ZP244.jpg" runat="server" />--%>
</li>
<li id="image5" data-thumb="">
<%--<img id="image5" src="assets/products/1_ZP244.jpg" />--%>
<img id="image2" src="assets/products/1_ZP244.jpg" />
<%--<asp:Image ID="image2" src="assets/products/1_ZP244.jpg" runat="server" />--%>
</li>
</ul>
</div>
</fieldset>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnSubmit" />
</Triggers>
</asp:UpdatePanel>
</div>
<script>
$(".data").mouseover(function () {
var image = $(this).attr('data-image');
var image1 = $(this).attr('data-image1');
var image2 = $(this).attr('data-image2');
var name = $(this).attr('data-name');
var price = $(this).attr('data-price');
var btnID = $(this).attr('ID');
$(".left").find('#image').attr('src', image);
$(".left").find('#image1').attr('src', image1);
$(".left").find('#image2').attr('src', image2);
$(".left").find('#image3').attr('data-thumb', image);
$(".left").find('#image4').attr('data-thumb', image1);
$(".left").find('#image5').attr('data-thumb', image2);
$(".left").find('#name').text(name);
$(".left").find('#price').text(price);
$(".left").find('#price').text(price);
})
</script>
You can register button for async postback inside an updatepanel by add a new OnPreRender event on the button:
protected void btnReloadQty_PreRender(object sender, EventArgs e)
{
ScriptManager scriptMan = ScriptManager.GetCurrent(this.Page);
scriptMan.RegisterAsyncPostBackControl((LinkButton)sender);
}

How to get image from GridView using GridView_RowCommand event in c# ASP.NET

i am doing edit operation inside GridView using c# ASP.NET.i need when user will click on edit button all data will retrive from that row and display in text box but here i am unable to display the image.I am explaining my code below.
faq.aspx:
<div class="row">
<div class="col-md-6">
<label for="question" accesskey="T"><span class="required">*</span> Question</label>
<asp:TextBox ID="TextBox1" runat="server" size="30" value="" name="question" ></asp:TextBox>
<div id="noty" style="display:none;" runat="server"></div>
<label for="answer" accesskey="A"><span class="required">*</span> Answer</label>
<asp:TextBox ID="TextBox2" runat="server" size="30" value="" name="answer" ></asp:TextBox>
<div id="Div1" style="display:none;" runat="server"></div>
</div>
<div class="col-md-6 bannerimagefile">
<label for="insertimage" accesskey="B"><span class="required">*</span> Insert Image</label>
<asp:FileUpload runat="server" class="filestyle" data-size="lg" name="insertimage" id="FileUpload1" onchange="previewFile()" />
<label for="bannerimage" accesskey="V"><span class="required">*</span> View Image</label>
<div style="padding-bottom:10px;">
<asp:Image ID="Image3" runat="server" border="0" name="bannerimage" style="width:70px; height:70px;" />
</div>
<div class="clear"></div>
<asp:Button ID="Button1" runat="server" Text="Submit" class="submit"
onclick="Button1_Click" />
</div>
</div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" Width="100%" CssClass="table table-striped table-bordered margin-top-zero" OnRowCommand="GridView1_RowCommand" >
<Columns>
<asp:TemplateField HeaderText="Sl No">
<ItemTemplate>
<asp:Label ID="faqid" runat="server" Text='<%#Eval("FAQ_ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Question" >
<ItemTemplate>
<asp:Label ID="question" runat="server" Text='<%#Eval("Question") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Answer" >
<ItemTemplate>
<asp:Label ID="answer" runat="server" Text='<%#Eval("Answer") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Image" >
<ItemTemplate>
<asp:Image ID="Image1" runat="server" border="0" name="bannerimage" style="width:70px; height:70px;" ImageUrl='<%# "/Upload/" + Convert.ToString(Eval("Image")) %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Action" >
<ItemTemplate>
<!--</i>
<i class="fa fa-times"></i> -->
<asp:HyperLink ID="HyperLink1" runat="server" data-toggle="tooltip" title="" class="btn btn-xs btn-success" data-original-title="Edit" CommandName="DoEdit" CommandArgument='<%# Eval("FAQ_ID") %>' ><i class="fa fa-edit"></i></asp:HyperLink>
<asp:HyperLink ID="HyperLink2" runat="server" data-toggle="tooltip" title="" class="btn btn-xs btn-danger" data-original-title="Delete" CommandName="DoDelete" CommandArgument='<%# Eval("FAQ_ID") %>' ><i class="fa fa-times"></i></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
faq.aspx.cs:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
int faqID = int.Parse(e.CommandArgument.ToString());
switch (e.CommandName)
{
case "doEdit":
{
int index = Convert.ToInt32(e.CommandArgument);
TextBox1.Text = GridView1.Rows[index].Cells[1].Text;
TextBox2.Text = GridView1.Rows[index].Cells[2].Text;
HiddenField1.Value = GridView1.Rows[index].Cells[0].Text;
Image3.ImageUrl=
Button1.Text = "Update";
}
}
}
Here i need the image will retrive and set to image3 id.Please help me to solve this issue.
WHere is image3; it's not in your snippet. Please include that, but if it's in the grid, then you do:
var img3 = (Image)GridView1.Rows[index].Cells[X].FindControl("Image3");
img3.ImageUrl = "XYZ";
Direct references only work when on the page outside of a container. If inside a container, you have to use FindControl (such as detailsview.findcontrol) or if a repeatable list, you have to use FindControl from the row (or in the case of the grid, the cell).
Get row index like this:
GridViewRow gvr = (GridViewRow)(((HyperLink)e.CommandSource).NamingContainer);
int index= gvr.RowIndex;
// to get image url
string url = ((Image)gvr.FindControl("Image3")).ImageUrl;
Image3.ImageUrl= url;

Panel visibilty on/off toggle effect not working

I've a got ListBox called lbxUpcommingEvents. When the index is changed the event handler is fired to check for duplicate records. If duplicates are not found, a panel called pnlAction inside a formview is turned on by the way of display style. If dups are found another panel pnlActionCancel is turned on and the oter is tuned off. Basically a toogle effect.
I've tried the visible property, viewstate property, but it does not work and I can't figure it out so once again, I seek wizdom from the collective. Here is my code.
protected void lbxUpcommingEvents_OnSelectedIndexChanged(object sender, EventArgs e)
{
pnlEventsSignUp.Visible = true;
string _selectedItemValue = lbxUpcommingEvents.SelectedValue.ToString();
int _eventid = Convert.ToInt32(_selectedItemValue);
Guid _memberId = Guid.Empty;
_memberId = new Guid(Session["myId"].ToString());
// Check for existing signup
EventsMemberSignup _createSingup = new EventsMemberSignup();
dsEventsSingupTableAdapters.MemberEventsTableAdapter da = new dsEventsSingupTableAdapters.MemberEventsTableAdapter();
dsEventsSingup.MemberEventsDataTable dt = da.GetDataForDupCheck(_memberId, _eventid);
if (dt.Rows.Count == 1)
{
Panel pnlAction = (Panel)(fvEventSignUp.FindControl("pnlAction"));
//pnlAction.Visible = false;
pnlAction.Style.Add("display","none");
Panel pnlActionCancel = (Panel)(fvEventSignUp.FindControl("pnlActionCancel"));
//pnlActionCancel.Visible = true;
pnlActionCancel.Style.Remove("display");
}
else
{
Panel pnlActionCancel = (Panel)(fvEventSignUp.FindControl("pnlActionCancel"));
//pnlActionCancel.Visible = false;
pnlActionCancel.Style.Add("display", "none");
Panel pnlAction = (Panel)(fvEventSignUp.FindControl("pnlAction"));
//pnlAction.Visible = true;
pnlAction.Style.Remove("display");
}
}
<div id="columnleft">
<a name="content_start" id="content_start"></a>
<div class="leftblock">
<h2>Events Signup</h2>
<p>
</p>
<h3> Upcomming Events</h3>
<p>
<asp:ListBox ID="lbxUpcommingEvents" runat="server" DataSourceID="odsUpcommingEvents"
Rows="6" DataTextField="Title" DataValueField="id" AutoPostBack="true"
Width="206px" OnSelectedIndexChanged="lbxUpcommingEvents_OnSelectedIndexChanged" />
</p>
<h3> Members Attending</h3>
<p>
<asp:DataGrid ID="lboxSignedUpMembers" runat="server" DataSourceID="odsSignedUpMembers"
AutoPostBack="true" AutoGenerateColumns="false" RowStyle-CssClass="gridview" AlternatingRowStyle-CssClass="altbgcolor"
Width="206px" onselectedindexchanged="lboxSignedUpMembers_SelectedIndexChanged" CssClass="gridview"
GridLines="None" BorderStyle="Solid" BorderWidth="1" BorderColor="Black" >
<AlternatingItemStyle BackColor="White" />
<Columns>
<asp:BoundColumn DataField="Name" />
<asp:BoundColumn DataField="Title" />
<asp:TemplateColumn >
<ItemTemplate>
<asp:Label runat="server" ID="lblDate" Text='<%# Eval("StartTime", "{0:d}") %>' />
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
</p>
</div>
</div>
</td>
<td align="left" >
<!--Start of right column-->
<div id="columnright">
<div class="rightblock">
<asp:Panel ID="pnlEventsSignUpTitle" runat="server" CssClass="actionbuttons">
<h2>Select an Event to Signup</h2>
</asp:Panel>
<asp:Label runat="server" ID="lblNote" ForeColor="#cc0000" Font-Bold="true" />
</div>
<div class="rightblock">
<asp:Panel runat="server" ID="pnlEventsSignUp" visible="false">
<div class="dashedline" ></div>
<asp:FormView ID="fvEventSignUp" runat="server" DataSourceID="ObjectDataSource1"
DataKeyNames="id" Width="100%" >
<ItemTemplate>
<h2>
<asp:HiddenField runat="server" ID="hfEventID" Value='<%# Eval("id") %>' />
<asp:Label Text='<%# Eval("title") %>' runat="server" ID="titleLabel" />
</h2>
<div class="itemdetails">
<br />
location:
<h3>
<asp:Label ID="locationLabel" runat="server" Text='<%# ShowLocationLink(Eval("locationname"),Eval("location")) %>' />
</h3>
<p>
<asp:Label Text='<%# Eval("starttime","{0:D}") %>' runat="server" ID="itemdateLabel" CssClass="GeneralText" />
<asp:Label Text='<%# ShowDuration(Eval("starttime"),Eval("endtime")) %>' runat="server" ID="Label1" CssClass="GeneralText" />
</p>
</div>
<div class="downloadevent">
<a href="#">
<img src="images/icon_download_event.gif" alt="Download this event to your personal calendar"
width="15" height="26" /></a><a href='<%# "events_download.ashx?EventID=" + Convert.ToString(Eval("id")) %>'>Add
this event to your personal calendar</a>
</div>
<Club:ImageThumbnail ID="thumb1" runat="server" ImageSize="Large" PhotoID='<%# Eval("photo") %>' />
<p>
<asp:Label Text='<%# Eval("description") %>' runat="server" ID="descriptionLabel" />
</p>
<div class="dashedline" ></div>
<asp:Panel ID="pnlAction" runat="server" CssClass="actionbuttons" >
<table border="0" cellpadding="2" cellspacing="2">
<tr>
<td>
<asp:Label runat="server" ID="Label2" Text="Action<br />Required" Width="80px" Font-Bold="true"
ForeColor="#cc0000" Font-Size="14px" />
</td>
<td>
<img src="images/RedArrow.jpg" alt="Red Arrow Right" />
</td>
<td>
<asp:CheckBox runat="server" ID="cbxCert" Height="30px" Text="Check to Confirm Attendance" /><br />
<asp:CustomValidator runat="server" ID="rfvConfirm"
ErrorMessage="You must check the box to continue" Font-Bold="true"
ForeColor="#cc0000" ClientValidationFunction="ensureChecked" /> <br />
<Club:RolloverLink ID="rlnkSignUp" runat="server" Text = "I will be attending this event"
OnClick="rlnkSignUp_OnClick" ToolTip="I hereby certify that I am commiting to attending this event."
/>
</td>
</tr>
</table>
</asp:Panel>
<asp:Panel runat="server" ID="pnlActionCancel" CssClass="actionbuttons" >
<table border="0" cellpadding="2" cellspacing="2">
<tr>
<td>
<asp:Label runat="server" ID="lblDupSignup" Text="You are alredy signed up for this event" ForeColor="#cc0000" Font-Bold="true" Font-Size="14px" />
</td>
<td>
</td>
<td>
<asp:CheckBox runat="server" ID="cbxCancel" Height="30px" Text="Check to Cancel Attendance" /><br />
<asp:CustomValidator runat="server" ID="CustomValidator1"
ErrorMessage="You must check the box to continue" Font-Bold="true"
ForeColor="#cc0000" ClientValidationFunction="ensureChecked" /> <br />
<Club:RolloverLink ID="rlnCancel" runat="server" Text="I'm cancelling my participation"
OnClick="rlnCancel_OnClick" />
</td>
</tr>
</table>
</asp:Panel>
</ItemTemplate>
</asp:FormView>
</asp:Panel>
</div>
I've set the ViewStateMode to "Disabled". I'm just hoping it won't back fire somewhere else.
Your existing code might work if you drop an update panel and place your controls inside it.
Alternatively you can create a property in your page like
private bool myRowCount;
protected bool HasRowsMyData
{
get { return myRowCount; }
set { myRowCount=value; }
}
Then inside your selectedIndex change event
if (dt.Rows.Count == 1)
{
HasRowsMyData=true;
//DataBind your controls here
YourUpdatePanel.Update();
}
Inside your aspx on panels you can set each panel's visible property like this so whenever page is updated they will turn on/off depeding upon the result
Visible='<%#HasRowsMyData%>'
Visible='<%#!HasRowsMyData%>'
If you like to do it client side I advise jQuery's toggle function
jQuey:toggle()

add cssClass to CurrentNode in asp.net Navigation

Here is my code :
<div class="Cat-list unselectable" style="font-weight:bold;">
<div class="right-bar-nav-item">
<asp:HyperLink runat="server" ID="lnkHome" NavigateUrl="~/Default.aspx">Home</asp:HyperLink>
</div>
<asp:Repeater runat="server" ID="menu" DataSourceID="SiteMapDataSource1">
<ItemTemplate>
<div class="right-bar-nav-item">
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%# Eval("Url") %>' ToolTip='<%# Eval("description") %>'><%# Eval("Title") %></asp:HyperLink>
</div>
</ItemTemplate>
</asp:Repeater>
</div>
<div style="clear:both;"></div>
<asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" ShowStartingNode="false" />
I'd like to give class ".selected" to Current Node. example: if its Default.aspx then it should change from <div class="right-bar-nav-item"> to this <div class="right-bar-nav-item selected">
$(function(){
var url = window.location.pathname,
urlRegExp = new RegExp(url.replace(/\/$/,'') + "$");
// now grab every link from the navigation
$('.menu a').each(function(){
// and test its normalized href against the url pathname regexp
if(urlRegExp.test(this.href.replace(/\/$/,''))){
$(this).addClass('selected');
}
});
});
Here is how you can do this in javascript.

Categories