I have added a like button on my product listview, and the like button suppose to get the value of the ads title and Adsid and the userid whose clicked on this like btn and then the code should store this add in favorite table as it mention in the code but i have a problem as i am still biggner in c# and i dont know how fix it very well could you please help with that(fix the below code cuz I am getting error message:
"Error 3 The name 'Adstitlinkbtn' does not exist in the current context
Error 2 The name 'Labeladsid' does not exist in the current context"
and aslo i will be thankfull if you add a message to user that in case if he didnt login and he click on the likebtn will recive a message " Please login to add this ads to your favorite list".
you can find this screen record that may can explain what i am meaning
screen record
Many thanks for all of you
protected void likebtn_Click(object sender, ImageClickEventArgs e)
{
SqlConnection likecn = new SqlConnection(cs);
SqlCommand likecmd = new SqlCommand();
string sqlstatment = "INSERT INTO favourite (AdsID, UID, AdsTit) VALUES (#AdsID,#UID,#AdsTit)";
likecmd.Connection = likecn;
likecmd.CommandType = CommandType.Text;
likecmd.CommandText = sqlstatment;
//Insert the parameters first
likecmd.Parameters.AddWithValue("#AdsID", Labeladsid);
likecmd.Parameters.AddWithValue("#UID", Session["UsrNme"]);
likecmd.Parameters.AddWithValue("#AdsTit", Adstitlinkbtn.Text);
SqlDataAdapter ad = new SqlDataAdapter(likecmd);
DataSet ds = new DataSet();
ad.SelectCommand = likecmd;
ad.Fill(ds);
Response.Write("This Ads has been added to your Fovarite List");
}
<asp:ListView ID="adsshow" runat="server" DataSourceID="locationdatalistshow"
style="text-align: left" >
<ItemTemplate>
<div class="templist">
<asp:Label ID="Labeladsid" runat="server" Text='<%# Eval("AdsID") %>' style="color: #ffffff"></asp:Label>
<asp:ImageButton ID="ImageButton3" runat="server" Height="88px" Width="91px"
CssClass="imag1" ImageUrl='<%# "/images/AdsImgs/" + Eval("Img1") %>'
PostBackUrl='<%# "AdsDetails.aspx?Img1=" + Eval("AdsID") %>' />
<asp:LinkButton ID="Adstitlinkbtn" runat="server"
style="font-weight: 700; color: #0066FF" Text='<%# Eval("AdsTit") %>'
CssClass="adstit" onclick="Adstitlinkbtn_Click"
PostBackUrl='<%# "AdsDetails.aspx?AdsTit=" + Eval("AdsID") %>' ></asp:LinkButton>
<br />
<asp:Label ID="AdsDescLabel" runat="server" Text='<%# Eval("AdsDesc") %>'
CssClass="adsdisc" />
<br /><br />
<br /><br />
<asp:Label ID="CountryLabel" runat="server" Text='<%# Eval("Country") %>'
style="font-family: Arial, Helvetica, sans-serif; font-size: small" />
-
<asp:Label ID="StateLabel" runat="server" Text='<%# Eval("State") %>'
style="font-family: Arial, Helvetica, sans-serif; font-size: small" />
-
<asp:Label ID="CityLabel" runat="server" Text='<%# Eval("City") %>'
style="font-size: small; font-family: Arial, Helvetica, sans-serif" />
<div class="adsprice">Price:
<asp:Label ID="AdsPriceLabel" runat="server" style="color: #FF0000"
Text='<%# Eval("AdsPrice") %>' /></div>
<br />
<div class="iconadsbox">
<asp:ImageButton ID="likebtn" runat="server"
ImageUrl="~/iconsimg/favoritestar2.png" OnClick="likebtn_Click" CommandName="like" />
<asp:ImageButton ID="Sndmailtoadder" runat="server"
ImageUrl="~/iconsimg/mailposter.png" OnClick="Sndmailtoadder_Click" />
</div>
<asp:Image ID="Image1" runat="server" CssClass="divideline"/>
</div>
</ItemTemplate>
<LayoutTemplate>
<asp:PlaceHolder ID="itemPlaceholder" runat="server"></asp:PlaceHolder>
<asp:DataPager ID="DataPager1" runat="server" PagedControlID="adsshow" PageSize="7">
<Fields>
<asp:NumericPagerField />
<asp:NextPreviousPagerField />
</Fields>
</asp:DataPager>
<br />
</div>
</LayoutTemplate>
</asp:ListView>
Create a bool value to represent whether user has logged in or not (call it bool loggedIn). Wherever your code is to login (you did not post this code), set that bool to be true. Then when the user clicks the 'like' button, in your 'likebtn_Click' method, check the bool:
if(!loggedIn)
{
MessageBox.Show("Please login to add this ads to your favorite list");
return;
}
I believe you have not shown us all your markup. It appears you are inside a grid view or some other collection control. In those controls, the template layout is dynamically generated for each item. So your label and link button controls don't really exist. What you have to do is create a GridView_Command event and in that code you will have access to the controls in that item.
So basically you created a template item and those controls are generated dynamically at runtime, which is why they are not available to you at design time. If you post the rest of your mark up me or anyone else who wants can give you more specific help.
protected void adsshow_ItemCommand(object sender, ListViewCommandEventArgs e)
{
if (e.CommandName == "like")
{
var lblAds = e.Item.FindControl("Labeladsid") as Label;
var lbtn = e.Item.FindControl("Adstitlinkbtn") as LinkButton;
var id = lblAds.Text;
var title = lbtn.Text;
}
}
<asp:ListView ID="adsshow" runat="server" DataSourceID="locationdatalistshow"
style="text-align: left" onitemcommand="adsshow_ItemCommand" >
<ItemTemplate>
...
<asp:ImageButton ID="likebtn" runat="server"
ImageUrl="~/iconsimg/favoritestar2.png" CommandName="like" />
...
Noticed I added a onCommand event to the ListView, and I removed your OnClick event from the imagebutton. I'm not 100% sure about the removing the OnClick event, so if you can please confirm for me that the OnCommand event fires correctly with the OnClick removed from the ImageButton.
Related
I have searched about this topic all over the internet and have come up with nothing. Either I am having a hardtime wording my problem or I am do something so wrong that no one else has ever even tried it...
I have a gridview. I am using a button in the gridview to execute a command to open a ModalPopupExtender. That part works great. Once I have the popup open, I want to be able to press a button to execute a function which will perform a Sql query and bind a gridview that is INSIDE the popup panel. After that the user can perform an action with the gridview which would close the modal popup.
Here is my HTML -
<cc1:ModalPopupExtender runat="server" ID="MPE_Issue" PopupControlID="pnlIssue" BackgroundCssClass="ModalPopupBG"
TargetControlID="Hid_Sno" CancelControlID="btnIssueCancel">
</cc1:ModalPopupExtender>
<asp:Panel ID="pnlIssue" runat="server" Style="display: none" >
<div class="HelloPopup">
<div>
<br />
<h2> Issue Equipment</h2>
<br />
<asp:Panel runat="server" ID="pnlIssueSearch" DefaultButton="btnIssueSearch">
<div class="block" style="text-align: right; margin-left: 50px">
<asp:Label CssClass="lblBlock" runat="server" ID="lblIssueSearch" Text="Search:"></asp:Label>
</div>
<div class="block">
<asp:TextBox runat="server" ID="txtIssueSearch" Width="160px"></asp:TextBox>
<asp:ImageButton runat="server" ID="btnIssueSearch" ImageUrl="../Images/search.png" OnClick="btnIssueSearch_Click" />
</div>
</asp:Panel>
<asp:Panel runat="server" ID="pnlIssueSubmit" DefaultButton="btnIssueSubmit">
<div style="width: 275px; margin: auto; height: 295px; overflow: scroll;">
<asp:GridView runat="server" ID="gvIssue" AutoGenerateColumns="false" CssClass="mGrid" OnRowCommand="gvIssue_RowCommand">
<Columns>
<asp:TemplateField HeaderText="Qty">
<ItemTemplate>
<asp:TextBox ID="txtIssueQty" runat="server" Text='<%# Bind("QTY") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Assignment" DataField="FIRST_NAME" />
</Columns>
</asp:GridView>
</div>
<div class="center">
<asp:Button runat="server" ID="btnIssueSubmit" Text="Issue" OnClick="btnIssueSubmit_Click" />
<input type="button" id="btnIssueCancel" value="Cancel" />
</div>
</asp:Panel>
And the codebehind -
protected void gv1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "issue")
{
GridViewRow gvr3 = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);
string itemNo = ((Label)gvr3.Cells[0].FindControl("lblItemNo")).Text;
btnIssueSubmit.Visible = false;
txtIssueSearch.Text = "";
MPE_Issue.Show();
}
protected void btnIssueSearch_Click(object sender, ImageClickEventArgs e)
{
string query = "SELECT QTY, NEW_EMP_ID as NAME FROM TRANSACTION_TRACKING WHERE NEW_EMP_ID = #inputINT";
string inputString = "%" + txtIssueSearch.Text + "%";
int inputINT = Convert.ToInt32(txtIssueSearch.Text);
SqlConnection con = new SqlConnection(CS);
SqlDataAdapter da = new SqlDataAdapter(query, con);
SqlParameter parameter = new SqlParameter("inputString", inputString);
SqlParameter parameter2 = new SqlParameter("inputINT", inputINT);
da.SelectCommand.Parameters.Add(parameter);
da.SelectCommand.Parameters.Add(parameter2);
DataSet ds = new DataSet();
da.Fill(ds);
gvIssue.DataSource = ds;
gvIssue.DataBind();
btnIssueSubmit.Visible = true;
MPE_Issue.Show();
}
EDIT/SOLUTION
I was going about solving this problem wrong. I wanted to override the nature of asp.net instead of going with the flow and solving the problem systematically. To overcome this issue I changed my data bind into its own method and had the button within the panel activate the that method, set the popup control to Open(), and also set a boolean from false to true. Then on the page_load I have an event that checks the boolean and automatically does the data Method if it is true (and therefore a search parameter is in the textbox).
Thanks all for the suggestions and help.
If you make your pnlIssueSubmit an UpdatePanel then do an asyncpostback trigger on btnIssueSearch wouldn't that fix your issue? Because your imageButton needs to do a post back in order to refresh you grid but then you'll lose your modal. Something like this:
<asp:UpdatePanel id="pnlIssueUpdate" runat="server">
<ContentTemplate>
<asp:Panel runat="server" ID="pnlIssueSubmit" DefaultButton="btnIssueSubmit">
<div style="width: 275px; margin: auto; height: 295px; overflow: scroll;">
<asp:GridView runat="server" ID="gvIssue" AutoGenerateColumns="false" CssClass="mGrid" OnRowCommand="gvIssue_RowCommand">
<Columns>
<asp:TemplateField HeaderText="Qty">
<ItemTemplate>
<asp:TextBox ID="txtIssueQty" runat="server" Text='<%# Bind("QTY") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Assignment" DataField="FIRST_NAME" />
</Columns>
</asp:GridView>
</div>
<div class="center">
<asp:Button runat="server" ID="btnIssueSubmit" Text="Issue" OnClick="btnIssueSubmit_Click" />
<input type="button" id="btnIssueCancel" value="Cancel" />
</div>
</asp:Panel>
</ContentTemplate>
<Triggers>
<asp:asyncPostBackTrigger ControlID="btnIssueSearch" />
</Triggers>
I was going about solving this problem wrong. I wanted to override the nature of asp.net instead of going with the flow and solving the problem systematically. To overcome this issue I changed my data bind into its own method and had the button within the panel activate the that method, set the popup control to Open(), and also set a boolean from false to true. Then on the page_load I have an event that checks the boolean and automatically does the data Method if it is true (and therefore a search parameter is in the textbox).
I need to Edit and Delete Row of GridView using C# ASP.NET.
I tried once and able to fill the data in TextBox after click on Edit Button,But I have also one Image to Edit and what I need is when user will click on Edit Image, The Image will also Display in proper place to Edit.In case of Delete part I have Image in Anchor Tag and I need which event I should pass from GridView and define in code behind page so that I can do the operation.
faq.aspx:
<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>
</div>
</div>
<!--end_1st_faq_add_div-->
<!--2nd_list_banner_view_div-->
<div class="widget-area">
<h2 class="widget-title"><strong>FAQ List</strong></h2><asp:HiddenField ID="HiddenField1" runat="server" />
<div class="streaming-table margin-top-zero padding-top-zero">
<div class="table-responsive">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
Width="100%" CssClass="table table-striped table-bordered margin-top-zero"
onselectedindexchanged="GridView1_SelectedIndexChanged">
<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>
<a href=" " data-toggle="tooltip" title="" class="btn btn-xs btn-danger" data-original-title="Delete"><i class="fa fa-times"></i>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
faq.aspx.cs:
protected void GridView1_SelectedIndexChanged(object sender, GridViewSelectEventArgs e)
{
int index = Convert.ToInt32(e.NewSelectedIndex);
TextBox1.Text = GridView1.Rows[index].Cells[1].Text;
TextBox2.Text = GridView1.Rows[index].Cells[2].Text;
HiddenField1.Value = GridView1.Rows[index].Cells[0].Text;
Button1.Text = "Update";
}
Please help me to resolve this issue.
I see that you have only item temples in grid view.
Hence I'm going to tell you two ways to do this:
1) Add edit template in grid view and handle the OnRowEditing event of grid view.
2) Add a hyperlink with key of row and link to another page where you can design the editor like you have done in this page by pre-populating the data using the key(primary key)
it is better that you use Modern data control like 'entitydataSource' or 'linqdateSource' or 'sqlDataSource' and bind your gridview by them .
using 'itemtemplate' for all rows is not a good way , instead fill you grid with 'dataSource' and use 'itemTemplate' for delete or Edit Button . send button name As commandName and rowID As commandArgument to gridViewItemCommand event in code behind.
in code behindin in GridviewItemcommand_Event with switch statement loop through itemCommands like this :
int itemID = int.parse(e.commandArgument)
switch(e.commandName)
{
case 'DoEdite' :{//some Code
Viewstate["ID"] = itemID;
break;}
case 'DoDelete' :{//some Code
break;}
}
you have the itemID(e.commandeArgument) and know which button clicked(e.commandName) .so you can do what you want.
In edit Mode when you send data to textBoxes use viewstate or other collection to hold your dataID because of after Edit, for Update edited date
you need it,
I've searched, but no luck...
I have a textbox inside an accordion control, that's inside a datalist... I want to allow the accordion form to submit some values, but I can't get those values out of the textbox, and findcontrol isn't working.
<asp:DataList ID="AddProjectDataList" runat="server">
<ItemTemplate>
<asp:HiddenField ID="clientid" runat="server" Value='<%# Eval("mmmclientlistid") %>'></asp:HiddenField>
<asp:Table ID="ProjectTableClass" runat="server" style="width:600px;height:600px"><asp:TableRow><asp:TableCell VerticalAlign="Top">
<b>New <asp:Label ID="ProjectTypeLabel" Text='<%# Eval("ProjectTypeName") %>' runat="server"></asp:Label> Project</b>
<table class="AddProject" cellpadding="5">
<tr>
<td valign="top">
<b>Campaign</b> information:
</td>
<td>
<asp:DropDownList ID="DDCampaignList" runat="server" AutoPostBack="true" OnSelectedIndexChanged="OnChange_selectCampaign" AppendDataBoundItems="True" >
<asp:ListItem Text="SELECT A CAMPAIGN:" Value="-1"></asp:ListItem>
</asp:DropDownList>
<br />
<ajaxToolkit:Accordion
ID="CampaignAccordion"
runat="Server"
SelectedIndex="1"
HeaderCssClass="accordionHeader"
HeaderSelectedCssClass="accordionHeaderSelected"
ContentCssClass="accordionContent"
AutoSize="None"
FadeTransitions="true"
TransitionDuration="250"
FramesPerSecond="40"
RequireOpenedPane="false"
SuppressHeaderPostbacks="true">
<Panes>
<ajaxToolkit:AccordionPane ID="AccordionPane1" runat="server"
HeaderCssClass="accordionHeader"
HeaderSelectedCssClass="accordionHeaderSelected"
ContentCssClass="accordionContent">
<Header>
<asp:LinkButton ID="AddCampaignLink" runat="server">Or Click to Add New Campaign</asp:LinkButton> </Header>
<Content>
<asp:TextBox ID="campaignNameTextBox" Style="width: 400px" runat="server"></asp:TextBox><br />
Description (optional):<br />
<asp:TextBox ID="campaignDescriptionTextBox" runat="server" TextMode="MultiLine"
Columns="30" Rows="3"></asp:TextBox>
<br />
<asp:Button ID="AddCampaignButton" runat="server" Text="Add New Campaign" OnClick="AddCampaign_Click" />
</Content>
</ajaxToolkit:AccordionPane>
</Panes>
<HeaderTemplate>...</HeaderTemplate>
<ContentTemplate>...</ContentTemplate>
And then in the codebehind
protected void AddCampaign_Click(object sender, EventArgs e)
{
//click to add campaign
//campaignname
//clientid
HiddenField EID = (HiddenField)FindControl("HiddenFieldEID");
TextBox campaignNameTextBox = (TextBox)AddProjectDataList.Items[0].FindControl("campaignNameTextBox");
TextBox campaignDescriptionTextBox = (TextBox)AddProjectDataList.Items[0].FindControl("campaignDescriptionTextBox");
tbl_campaign newcampaign = new tbl_campaign();
newcampaign.clientID = Convert.ToInt32(DDClientList.SelectedValue);
newcampaign.employeeID = Convert.ToInt32(HiddenFieldEID.Value);
newcampaign.campaignName = campaignNameTextBox.Text;
newcampaign.campaignDescription = campaignDescriptionTextBox.Text;
db.AddTotbl_campaign(newcampaign);
db.SaveChanges();
}
If I get rid of the accordion pane, it works fine. The control is located no problem. But with the accordion, no such luck. (The "hiddenFieldEID" field is located just fine because it's outside of the accordion.)
Do I need a separate onItemDataBound event in the DataList control? If so, what goes in there, and how do I relate it to the buttonclick event?
Thanks!
Well, I might have just figured it out.
I did this:
Control CampaignAccordion = (Control)AddProjectDataList.Items[0].FindControl("CampaignAccordion");
TextBox campaignNameTextBox = (TextBox)CampaignAccordion.FindControl("campaignNameTextBox");
TextBox campaignDescriptionTextBox = (TextBox)CampaignAccordion.FindControl("campaignDescriptionTextBox");
And it worked. No separate databinding event. Is this the normal way to do it?
I need a way for a piece of data to presist across postbacks. Is there a way besides, cookies, and sessions?
I've got a listbox, when clicked, the selected index changed event takes a session which contains user id and feeds it to a method that fetches user's name, etc. Then I use FindControl method to locate a button inside the form view. I set the button's text property with data just fetched such as first and last name.
It works on the initial load, but if I click on other records in the listbox second time the text property is not set.
I did not write this code - I'm trying to make chages.
Here is the list box:
<asp:ListBox ID="lbxUpcommingEvents" runat="server" DataSourceID="odsUpcommingEvents"
Rows="6" DataTextField="Title" DataValueField="id" AutoPostBack="true"
Width="206px" OnSelectedIndexChanged="lbxUpcommingEvents_OnSelectedIndexChanged" />
Listbox'x on selected index changed:
protected void lbxUpcommingEvents_OnSelectedIndexChanged(object sender, EventArgs e)
{
pnlEventsSignUp.Visible = true;
string _selectedItemValue = lbxUpcommingEvents.SelectedValue.ToString();
LoadName();
}
protected void LoadName()
{
MembershipUser user = Membership.GetUser();
DataSetTableAdapters.MemberInfoTableAdapter da = new DataSetTableAdapters.MemberInfoTableAdapter();
Guid _memberId = Guid.Empty;
_memberId = new Guid(Session["myId"].ToString());
DataSet.MemberInfoDataTable dt = da.GetMember(_memberId);
if (dt.Rows.Count == 1)
{
DataSet.MemberInfoRow mr = dt[0];
RolloverLink rlnkSignUp = (RolloverLink)(fvEventSignUp.FindControl("rlnkSignUp"));
rlnkSignUp.Text = "I, " + mr.firstname + " " + mr.lastname + " will be attending this event.";
}
}
Here is markup for the form view where I set the RolloverLinkButton's text property.
<asp:Panel runat="server" ID="pnlEventsSignUp" visible="false">
<div class="dashedline" ></div>
<asp:FormView ID="fvEventSignUp" runat="server" DataSourceID="SqlDataSource1"
DataKeyNames="id" Width="100%" >
<ItemTemplate>
<h2>
<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="panel1" runat="server" CssClass="actionbuttons" Visible='<%#User.IsInRole("Administrators") %>'>
<table border="0" cellpadding="2" cellspacing="2">
<tr>
<td>
<asp:Label runat="server" ID="Label2" Text="Action<br />Required" Width="80px" />
</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"
/>
</td>
</tr>
</table>
</asp:Panel>
</ItemTemplate>
</asp:FormView>
</asp:Panel>
You can use ViewState. Since you are dynamically looking up the button, setting a property is quicker and we can then let Asp.Net find the button and set its text via one of the two methods I explain below:
public string rlnkSignUpText
{
get { return Convert.ToString(ViewState["rlnkSignUpText"] ?? "default value"); }
set { ViewState["rlnkSignUpText"] = value; }
}
Replace your code that searches for the button and assigns the text with:
rlnkSignUpText = "I, " + mr.firstname + " " + mr.lastname + " will be attending this event.";
Then use one of these methods to set the text to the control:
1) Use the control's OnPreRender event:
To render it, add OnPreRender="rlnkSignUp_PreRender" to your xaml like this:
<Club:RolloverLink ID="rlnkSignUp" runat="server" OnPreRender="rlnkSignUp_PreRender" />
Then in your codebehind:
protected void rlnkSignUp_PreRender(object sender, EventArgs e)
{
RolloverLink rlnkSignUp = (RolloverLink)sender;
rlnkSignUp.Text = rlnkSignUpText;
}
2) Bind the property and control together:
Instead of using the control's PreRender you can bind to the property with:
<Club:RolloverLink ID="rlnkSignUp" runat="server" Text='<%# rlnkSignUpText %>' />
You then need to call DataBind in your Page_PreRender() like so:
void Page_PreRender(object sender, EventArgs e)
{
DataBind();
}
Have you enabled ViewState in the control.
Enable View State
i to get the clientid of the control which is placed inside the Edit item template of the gridview in javascript without going to the server side code..
<asp:TemplateField HeaderText="FromDate" SortExpression="FromDate">
<ItemTemplate>
<asp:Label ID="FromDate" runat="server" Text='<%#((DateTime)DataBinder.Eval(Container.DataItem,"FromDate")).ToShortDateString()%>'></asp:Label>
<asp:HiddenField ID="ID" runat="server" Value='<%#Eval("ID") %>' />
<asp:HiddenField ID="ApproveLeaveID" runat="server" Value='<%#Eval("ApproveLeaveID") %>' />
<asp:HiddenField ID="hidLevel3" runat="server" Value='<%#Eval("Level3ManagerACENumber") %>' />
</ItemTemplate>
<EditItemTemplate>
<table>
<tr>
<td>
<asp:TextBox ID="txtFDate" runat="server" Text='<%#((DateTime)DataBinder.Eval(Container.DataItem,"FromDate")).ToShortDateString()%>'>
</asp:TextBox>
<asp:HiddenField ID="ID" runat="server" Value='<%#Eval("ID") %>' />
<asp:HiddenField ID="ApproveLeaveID" runat="server" Value='<%#Eval("ApproveLeaveID") %>' />
<asp:HiddenField ID="hidLevel3" runat="server" Value='<%#Eval("Level3ManagerACENumber") %>' />
</td>
<td>
<a onclick="showCalendarControl(3,<%# Container.ItemIndex %>)">
<img id="img3" runat="server" alt="Clock" src="../Images/clock_add.png" style="border: none" /></a>
</td>
</tr>
</table>
</EditItemTemplate>
<ItemStyle HorizontalAlign="Left" />
<HeaderStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText="ToDate" SortExpression="ToDate">
<ItemTemplate>
<asp:Label ID="ToDate" runat="server" Text='<%#((DateTime)DataBinder.Eval(Container.DataItem,"ToDate")).ToShortDateString()%>'>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<table>
<tr>
<td>
<asp:TextBox ID="txtTDate" runat="server" Text='<%#((DateTime)DataBinder.Eval(Container.DataItem,"ToDate")).ToShortDateString()%>'>
</asp:TextBox>
</td>
<td>
<a onclick="showCalendarControl(4,<%# Container.ItemIndex %>)">
<img id="img4" runat="server" alt="Clock" src="../Images/clock_add.png" style="border: none" /></a>
</td>
</tr>
</table>
</EditItemTemplate>
<ItemStyle HorizontalAlign="Left" />
<HeaderStyle HorizontalAlign="Center" />
</asp:TemplateField>
This is my java script:
function showCalendarControl(ControlNo,index) {
var textField;
if(ControlNo==1)
{
textField=document.getElementById('<%=txtFromDate.ClientID%>');
}
else
{
textField=document.getElementById('<%=txtToDate.ClientID%>');
}
if(ControlNo==3)
{
textField=document.getElementsByClassName('txtFDate')[index];
}
if(ControlNo==4)
{
textField=document.getElementsByClassName('txtTDate')[index];
}
calendarControl.show(textField);
}
first two textbox(txtFromDate,txtToDate) is for the not in the grid control...
You can fetch the elements in the ItemDataBound event of the grid (using FindControl), and then pass the ClientID of the textbox as a parameter to showCalendarControl:
TextBox txtFDate = e.Item.FindControl("txtFDate") as TextBox;
TextBox txtTDate = e.Item.FindControl("txtTDate") as TextBox;
HtmlAnchor link = e.Item.FindControl("aLink") as HtmlAnchor;
if (txtTDate != null && txtFDate != null && link != null)
{
link.Attributes.Add("onclick", String.Format("showCalendarControl({0}, '{1}', '{2}')", 4, txtFDate.ClientID, txtTDate.ClientID);
}
(you'll also need to add an ID and a runat="server" to your link. I'm also assuming txtFDate is declared in your EditTemplate although it's not there. The ControlNo parameter could be a data key instead of a constant as in the example, it's not really clear what it is)
Then, in your function, use the clientID parameters to get the textboxes:
function showCalendarControl(ControlNo, txtFDateClientID, txtTDateClientID) {
var textField;
if(ControlNo==3)
{
textField=document.getElementById(txtFDateClientID);
}
if(ControlNo==4)
{
textField=document.getElementById(txtTDateClientID);
}
calendarControl.show(textField);
}
The problem is that every control should have unique server ID. So server side controls which are placed inside template are rendered multiple times with different auto generated ids based on ID you've specified in the template. You can easily see it if you will have a look on the generated html. Therefore your js code is accessing only the html element with hardcoded id. As I guess it is placed in the first row.
Simple solution is to describe your text box in a following way
<asp:TextBox ID="txtTDate" runat="server" CssClass="txtTDate" Text='<%#((DateTime)DataBinder.Eval(Container.DataItem,"ToDate")).ToShortDateString()%>'>
</asp:TextBox>
Then modify the js function in the following way :
function showCalendarControl(ControlNo, index) {
var textField;
if(ControlNo==3)
{
textField=document.getElementsByClassName('txtFDate')[index];
}
if(ControlNo==4)
{
textField=document.getElementsByClassName('txtTDate')[index];
}
calendarControl.show(textField);
}
And modify your link as the following :
<a onclick="showCalendarControl(4, <%# Container.DataItemIndex %>)">
Updated the answer
DataItemContainer has DataItemIndex property which has to be used in this case.