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
}
}
}
Related
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".
The ID is inside the ItemTemplate and it cannot be found in the code file.
<form id="form1" runat="server">
<asp:SqlDataSource ID="searchresults" runat="server"
ConnectionString='<%$ ConnectionStrings:AgileDatabaseConnection %>'
SelectCommand=" SELECT [userID], [userName], [firstName],[lastName],[password], [email] FROM [Users] WHERE ([email] LIKE '%' + #email + '%')">
<selectparameters>
<asp:querystringparameter querystringfield="searchquery" name="email" type="String"></asp:querystringparameter>
</selectparameters>
</asp:SqlDataSource>
<asp:ListView ID="displayitems" runat="server" DataSourceID="searchresults">
<itemtemplate>
<asp:label runat="server" associatedcontrolid="projectOwner" cssclass="col-md-2 control-label">Project Owner:</asp:label>
<div class="col-md-10">
<asp:TextBox runat="server" ID="ProjectOwner" CssClass="form-control" /><br />
<asp:label runat="server" associatedcontrolid="projectOwner" cssclass="col-md-2 control-label">Scrum Master:</asp:label>
<div class="col-md-10">
<asp:SqlDataSource ID="ScrumMaster" runat="server" ConnectionString='<%$ ConnectionStrings:AgileDatabaseConnection %>' SelectCommand="SELECT userName FROM [Users]"></asp:SqlDataSource>
<asp:dropdownlist runat="server" id="usertype" DataSourceID="ScrumMaster" DataTextField="userName"></asp:dropdownlist><br />
</div>
</div>
<asp:label runat="server" cssclass="col-md-2 control-label">Email:</asp:label>
<asp:Label Text='<%#Eval("email") %>' runat="server" ID="emaillabel" /><br />
<asp:label runat="server" cssclass="col-md-2 control-label">UserName:</asp:label>
<asp:Label Text='<%#Eval("userName") %>' runat="server" ID="username" /><br />
<asp:label runat="server" cssclass="col-md-2 control-label">UserID:</asp:label>
<asp:Label runat="server" Text='<%#Eval("userID") %>' ID="UserID" CssClass="form-control" />
<br />
<div class="actions"></div>
<asp:Button Text="Add" runat="server" class="btn pull-right" ID="uploadbutton" OnClick="add_Click"></asp:Button>
</div>
</itemtemplate>
</asp:ListView>
<emptydatatemplate>
<span>No users match <asp:Label Text='' runat="server" ID="email" /> .</span>
</emptydatatemplate>
</form>
C# says it can't find 'userName'. Here's my backend code:
string ownerName = ProjectOwner.Text;
string IDuser = username.Text;
string IDdata = Session["userID"].ToString();
How do I get the userName value through?
The problem is that ListView can return more then one item, so code behind doesn't know about which of the itens controls (username and ProjectOwner) are you talking about.
If you want to do the same thing for EACH item, you can do like this:
protected void displayitems_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
string ownerName = ((TextBox)e.Item.FindControl("ProjectOwner")).Text;
string IDuser = ((Label)e.Item.FindControl("username").Text;
string IDdata = Session["userID"].ToString();
}
}
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;
I have this nested datalist.
EDIT
<asp:DataList ID="mydatalist" DataKeyField="sid" ItemStyle-CssClass="lft_c_down" runat="server">
<ItemTemplate>
<div class="wholeC">
<div class="ctop">
<div class="lft_l">
<div class="lft_l_top">
<asp:Image ID="Image1" runat="server" ImageUrl='<%#DataBinder.Eval(Container.DataItem,"ipath")%>' Height="245px" Width="297px" />
<br/>
</div>
</div>
<div class="lft_r">
<asp:Label ID="lbl_sid" Text='<%#DataBinder.Eval(Container.DataItem,"sid") %>' runat="server" Visible="false" />
<b class="products" >Product Name:</b>
<asp:Label ID="lbl2" Text='<%#DataBinder.Eval(Container.DataItem,"ipath") %>' runat="server" />
<br/>
<b class="products">Brand:</b>
<asp:Label ID="lbl1" Text='<%#DataBinder.Eval(Container.DataItem,"brand") %>' runat="server" />
<br/>
</div>
</div>
<div class="cdown">
<asp:TextBox ID="tb_cmt" runat="server" Height="35px" Width="500px" placeholder="comment.." />
<asp:Button ID="Button1" runat="server" Text="Comment" backcolor="black" BorderStyle="None" Font-Names="Consolas" Font-Overline="False"
ForeColor="White" Height="34px" Width="108px" OnClick="cmt_Click" />
<asp:DataList ID = "dl_cmt" runat="server">
<ItemStyle CssClass="coment" />
<ItemTemplate>
<asp:Label ID="lblcmt" runat="server" Text='<%#Eval("ecomment")%>' />
<asp:Label ID="lblDate" style=" color:brown; font-family:Cursive; font-size:x-small; " runat="server" Text='<%#Eval("my_date","on {0}") %>' />
</ItemTemplate>
</asp:DataList>
<%--<asp:LinkButton ID="lb_showMore" runat="server">Show More</asp:LinkButton>--%>
</div>
</div>
</ItemTemplate>
</asp:DataList>
It uses the property onItemDataBound.But with its use i am unable to access the id of this datalist.
public void cmtdatabound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item)
{
DataList dl = e.Item.FindControl("dl_cmt") as DataList;
string str = gstr;
sq.connection();
SqlCommand cmd = new SqlCommand("select top 4 * from comment where sid='" + str + "' order by my_date desc", sq.con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
dl.DataSource = ds;
dl.DataBind();
}
}
Here the dl is null that means the id is not accessible.How do i access the id of the datalist here.
You can use sender parameter as DataList like this:
DataList dl = sender as DataList;
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()