Why Button is not working in my datalist control? - c#

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".

Related

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

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.

I am trying to close modelpopupextender using a button click, this button belongs to another form so modelpopupextender is not able to access it

I am trying to close modelpopupextender using a button click, this button belongs to another form so modelpopupextender is not able to accessable.
I have tried to remove the updatepanel as suggested, but it's not working.
This is my form1.aspx (which includes a button, onclick which will display a ModalPopupExtender in which includes grid view)
<asp:Button id="btnclick" text="Show Modal Popup" runat="server" >
</asp:Button>
<cc1:ModalPopupExtender ID="ModelPopupExtender1" runat="server"
PopupControlID="pc" TargetControlID="btnclick" OkControlID ="Button2"
CancelControlID="Button1" BackgroundCssClass="bcc" BehaviorID="MPE1">
</cc1:ModalPopupExtender>
<asp:Panel ID="pc" runat="server" CssClass="pop" Style="display:none;">
<iframe style="width:1003px;height:550px;" id="if"src="EstPopUp.aspx" runat="server"></iframe>
</asp:Panel>
This is my EstPopUp.aspx ( Where gridview is dislpayed with save and cancel buttons)
<asp:GridView ID="gvContacts" runat="server" AutoGenerateColumns="false" CellPadding="5" DataKeyNames="EstimateBreakUpTypeId" OnSelectedIndexChanged="gvContacts_SelectedIndexChanged" OnRowDataBound="gvContacts_RowDataBound" >
<Columns>
<asp:TemplateField HeaderText="DispOrder">
<ItemTemplate>
<center>
<asp:TextBox ID="TextBox1" width="20px" runat="server" Text='<%#
Bind("DispOrder") %>'></asp:TextBox>
</center>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="EstBreakUpName">
<ItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" ></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Percentage(%)">
<ItemTemplate>
<center>
<asp:TextBox ID="TextBox2" Width="30px" runat="server"></asp:TextBox>
</center>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Amount">
<ItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" CssClass="sum" ></asp:TextBox>
<cc1:FilteredTextBoxExtender ID="fte" runat="server" Enabled="true"
TargetControlID="TextBox3" FilterType="Numbers,Custom" ValidChars=".">
</cc1:FilteredTextBoxExtender>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br/>
<asp:Button ID="Button1" runat="server" Text="Save" OnClick="Button1_Click"></asp:Button>
<asp:Button class="abc" ID="Button2" runat="server" Text="Cancel" CssClass=".cancel" OnClick="Button2_Click1"></asp:Button >
<br />
</asp:GridView>
My expected result is, when cancel button is clicked the modelpopup should disappear.
Try this, it works fine.
protected void Button2_Click(object sender, EventArgs e)
{
string url = " form1.aspx";
Response.Write("<script>top.location='" + url + "';parent.location='" + url + "';</script>");
}

The name ' ' does not exist in the current context

The name 'Label2.Text' does not exist in the current context
Catalog.aspx
<asp:DataList ID="DataList1" runat="server" DataKeyField="Id" DataSourceID="SqlDataSource1" RepeatColumns="4" RepeatLayout="Flow">
<ItemTemplate>
<div class="Item">
<div class="name">
<asp:Label ID="NameLabel" runat="server" Text='<%# Eval("Name") %>' />
</div>
<div>
Код:<asp:Label ID="Label2" runat="server" Text='<%# Eval("Id") %>' />
</div>
<img src="<%# Eval("Image") %>" height="115" alt="item"/>
<div class="price">
Цена:
<asp:Label ID="PriceLabel" runat="server" Text='<%# Eval("Price")%>' />p.
<asp:Button ID="Button2" runat="server" ForeColor="Black"
onclick="Button2_Click" Text="В КОРЗИНУ" />
</div>
<div class="desc">
<asp:Label ID="DescriptionLabel" runat="server" Text='<%# Eval("Description") %>' />
</div>
</div>
</ItemTemplate>
</asp:DataList>
Catalog.aspx.cs
sqlCon.Open();
SqlCommand cmd_SQL = new SqlCommand("INSERT INTO Cart(ClientId,ProductId,Amount) VALUES (#ClientId,#ProductId,#Amount)", sqlCon);
cmd_SQL.Parameters.Add("#ClientId", SqlDbType.NVarChar).Value =Membership.GetUser().ProviderUserKey.ToString();
cmd_SQL.Parameters.Add("#ProductId", SqlDbType.NVarChar).Value =Label2.Text;
cmd_SQL.Parameters.Add("#Amount", SqlDbType.NVarChar).Value = 1;
cmd_SQL.CommandType = CommandType.Text;
cmd_SQL.ExecuteNonQuery();
The name 'Label2.Text' does not exist in the current context
Your label is inside of an item template, which means you cannot just access it any old place on the page. If you want to gain access to the value inside the label, then you need to tie into one of the DataList events, such as OnItemCommand (if you wanted to access the value as the result of a command button click, for instance). You can use FindControl inside of the event handler to access the value. For example:
<asp:DataList runat="server" ID="test" OnItemCommand="test_ItemCommand">
<ItemTemplate>
<asp:Label runat="server" ID="Label2" Text="Test" />
</ItemTemplate>
</asp:DataList>
protected void test_ItemCommand(object source, System.Web.UI.WebControls.DataListCommandEventArgs e)
{
if (e.Item != null)
{
var label2 = e.Item.FindControl("Label2");
if (label2 != null && label2 is Label)
{
var productID = ((Label)label2).Text;
// now you have the contents of the label's text property
}
}
}

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()

Categories