How to access ItemTemplate control from ItemCommand event using Repeater - c#

My repeater:
<asp:Repeater ID="rptrContacts" runat="server" OnItemCommand="rptrContact_ItemCommand" >
<div ID="itemTemplate>
<ItemTemplate>
<%# Eval("Name") %>
<%# Eval("Email") %>
<asp:LinkButton ID="lbtnEditContact" runat="server" CommandName="Edit" Text="Edit" CommandArgument='<%# Eval("ContactID") %>' />
<asp:Label ID="lblUpdateConfirm" runat="server" Text="Update Confirmed" Visible="false" />
</ItemTemplate>
</div>
<div ID="editTemplate runat="server" visibility="false">
Update your Info:<br>
Name: <asp:TextBox ID="txtName" runat="server Text="<%# Eval("Name") %>"/> <br>
Email: <asp:TextBox ID="txtEmail" runat="server Text="<%# Eval("Email") %>"/><br>
<asp:LinkButton ID="lbtnUpdateContact" CommandArgument='<%# Eval("ContactID") %>' CommandName="UpdateContact" runat="server" >Update</asp:LinkButton>
</div>
</asp:Repeater
and code for ItemCommand:
switch(e.CommandName)
{
case "Edit":
//make editTemplate div visible
HtmlGenericControl divEditContact = (HtmlGenericControl)e.Item.FindControl ("divEditContact");
divEditContact.Visible = true;
break;
case "Update":
Employee updateEmployee = new Employee
{
employeeName = txtName.Text:
employeeEmail = txtEmail.Text:
}
updateEmployee = API.UpdateEmployee(updateEmployee);
//display lblUpdateConfirm visible to True
// so user sees this confirm messge in the newly updated ItemTemplate
}
How can I access my lblUpdateConfirm and turn its Text state to visible from inside the ItemCommand, so that when the user sees the newly updated ITemTemplate, the label is showing the "Update Confirmed" message?

VB:
CType(e.Item.FindControl("lblUpdateConfirm"), Label).Visible = True;
C #:
Label lblToMakeVisible = (Label)e.Item.FindControl("lblUpdateConfirm");
lblToMakeVisible.Visible = True;

Related

Why Rowcommand event of a gridview is not getting fired ?

I am facing a kind of weird problem.
Problem:
When I click a link button inside a grid view then RowCommand event of a grid view is getting fired when deployed on a localhost but not when deployed on the IIS i.e. client system. I have also tried a link button inside grid view but that's also not getting fired.
Solution: (Temporary)
When I disabled ValidateRequest on the top of the .aspx page. It worked.
What should I do?
So what can be the possible solution for it? I have googled but nothing good came up.
Code:
<asp:GridView ID="gvAppliedWorks" runat="server" OnRowCommand="gvAppliedWorks_RowCommand" AutoGenerateColumns="false" DataKeyNames="AppliedWorkID, ContractorID" EmptyDataText="No Data Found"
CssClass="table table-responsive table-bordered table-striped" OnRowDataBound="gvAppliedWorks_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Form No">
<ItemTemplate>
<asp:Literal ID="liFormNo" runat="server" Text='<% #Eval("FormNo")%>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Company Name">
<ItemTemplate>
<asp:Literal ID="liCompanyName" runat="server" Text='<% #Eval("Name")%>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Financial Bid">
<ItemTemplate>
<asp:Label ID="txtBidAmount" runat="server" CssClass="control-label" Text='<% # string.Format("{0:n2}", Eval("FinancialMoney").ToString())%>' />
%
<asp:Label ID="ddlBidPer" runat="server" CssClass="control-label" Text='<%# Eval("AboveBelow").ToString() %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Awarded Percentage">
<ItemTemplate>
<div class="pull-left">
<asp:HiddenField ID="hdnIsAwarded" Value='<%# Eval("IsAwarded") %>' runat="server" />
<asp:TextBox ID="txtAwardedBid" Text='<%#Eval("AwardedBid")%>' Style="width: 70px !important;" runat="server" CssClass="form-control"></asp:TextBox>
</div>
<div class="pull-left" style="margin-top: 7px">
% <%# Eval("AboveBelow").ToString() %>
</div>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Remarks">
<ItemTemplate>
<asp:TextBox ID="txtRemarks" Text='<%#Eval("Remarks")%>' runat="server" CssClass="form-control"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Award Tender">
<ItemTemplate>
<asp:LinkButton ID="lnkAward" runat="server"
CommandArgument='<%# Eval("AppliedWorkID") %>' CommandName="award"
CssClass="btn btn-sm btn-danger" Enabled='<%# Convert.ToBoolean(Eval("IsBlackList")) == true ? false: true %>'
Visible='<%# Convert.ToBoolean( Eval("IsAwarded"))== false? true:false%>' CausesValidation="false" Text="Award"></asp:LinkButton>
<ajax:ConfirmButtonExtender ID="cbe" runat="server" DisplayModalPopupID="mpe" TargetControlID="lnkAward">
</ajax:ConfirmButtonExtender>
<ajax:ModalPopupExtender ID="mpe" runat="server" PopupControlID="pnlPopup" TargetControlID="lnkAward" OkControlID="btnYes"
CancelControlID="btnNo" BackgroundCssClass="modalBackground">
</ajax:ModalPopupExtender>
<asp:Panel ID="pnlPopup" runat="server" CssClass="modalPopup" Style="display: none">
<div class="header">
Confirmation
</div>
<div class="body">
Are you sure to Award this Work?
</div>
<div class="Popupfooter" align="right">
<asp:Button ID="btnYes" CssClass="btn btn-sm btn-danger" runat="server" Text="Yes" />
<asp:Button ID="btnNo" CssClass="btn btn-sm btn-primary" runat="server" Text="No" />
</div>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText='Action'>
<ItemTemplate>
<asp:LinkButton ID="btnBlackList" runat="server" OnClick="btnBlackList_Click" Visible='<%# Convert.ToBoolean( Eval("IsAwarded"))== false? true:false%>' Enabled='<%# Convert.ToBoolean(Eval("IsBlackList")) == true ? false: true %>' Text='Defective'
CssClass="" ToolTip="Blacklist"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
**.cs**
protected void gvAppliedWorks_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
// GridViewRow gr = ((GridViewRow)((Control)sender).Parent.Parent);
if (e.CommandName == "award")
{
GridViewRow gr = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
int AppliedWorkID = e.CommandArgument.ToInt32(); //gvAppliedWorks.DataKeys[gr.RowIndex].Value.ToInt32();
TextBox txtAwardedBid = gr.FindControl("txtAwardedBid") as TextBox;
TextBox txtRemarks = gr.FindControl("txtRemarks") as TextBox;
Label txtBid = gr.FindControl("txtBidAmount") as Label;
Label lblAboveBelow = gr.FindControl("ddlBidPer") as Label;
string AboveBelow = lblAboveBelow.Text;
Decimal BidAmount = txtBid.Text.ToDecimal();
if (String.IsNullOrEmpty(txtRemarks.Text))
{
Utility.Msg_Error(this.Master, "Remarks Required!!!");
return;
}
Decimal AwardedBid = string.IsNullOrEmpty(txtAwardedBid.Text.Trim()) ? 0 : txtAwardedBid.Text.Trim().ToDecimal();
string Remarks = txtRemarks.Text;
if (AwardedBid != BidAmount)
{
Utility.Msg_Error(this.Master, "Financial Bid must be equal to Awarded Percentage");
return;
}
if (ClsTender.IsReceivedSubMainOffice(AppliedWorkID, LoginUserID, AwardedBid, Remarks, BidAmount, AboveBelow))
{
Utility.Msg_Success(this.Master, "Work Awarded Successfully!!!");
fill_gvAppliedWorks(labNitNo.Text.Replace("NIT No :", "").ToInt32(), labWorkNo.Text.Replace("Work No :", "").ToInt32());
}
}
}
catch (Exception ex)
{
Utility.Msg_Error(Master, ex.Message);
}
}
It sounds like your page is trying to submit what it thinks is potentially dangerous content if setting the ValidateRequest = false solves the issue. Is it possible that one of the controls on your page is sending html or something like that?
If one of your controls needs to send HTML then you can overcome this by adding an attribute to your model.
[AllowHtml]
[Required]
public string article_content { get; set; }
This will allow html to be entered into the control.

Add Repeater items to Listbox

I have a Repeater which contains Eval commands and a Button (Which I can't access) I would like to access this button and when clicked insert one of the Eval commands (Eg. Car Model) into a listbox I have on the same page.
<asp:Button ID="modelButton" CommandArgument='<%# Eval("Model") %>' Text='<%# "Add Model to List:" + Eval("Model") %>' runat="server" />
<asp:Repeater ID="Repeater2" runat="server" DataSourceID="AccessDataSource1" DataMember="DefaultView" OnItemDataBound="Repeater2_ItemDataBound">
<ItemTemplate>
<div>
<p><img src="carImages/<%#Eval("Artwork")%>" /></div>
<div class="col-xs-4">
<h4><%# Eval("Make")%> (<%# Eval("Year") %>)</h4>
<p><%# Eval("Model")%></p>
<p><%# Eval("Colour")%></p>
<p><%# Eval("Type")%></p>
<div>
<asp:Button ID="modelButton" CommandArgument='<%# Eval("Model") %>' Text='<%# "Add Model to List:" + Eval("Model") %>' runat="server" />
</div>
</a>
</div>
</ItemTemplate>
Just add your oncommand argument to the repeated button
<asp:Button ID="modelButton" CommandArgument='<%# Eval("Model") %>' OnCommand="CommandBtn_Click" Text='<%# "Add Model to List:" + Eval("Model") %>' runat="server" />
you can grab the eval in the behind code
void CommandBtn_Click(Object sender, CommandEventArgs e){
var command = e.CommandArgument;
// Do whatever with it here
}
That will get the evaluated model

Make repeater row checkable

I have a ASP.NET repeater consists of image and label(wrap inside a div).
I want to make the repeater row work like a checkbox.
<asp:Repeater ID="rpt" runat="server">
<ItemTemplate>
<div class="divItem">
<asp:HiddenField ID="hfIID" runat="server" Value='<%# Eval("ID") %>' />
<asp:Image ID="imgItem" runat="server" ImageUrl='<%# Eval("ImageURL") %>' />
<asp:Label ID="lblName" runat="server" Text='<%# Eval("ItemName") %>'></asp:Label>
</div>
</ItemTemplate>
</asp:Repeater>
For example, the repeater have 10 items.
When a user select item 3 and item 5(similar like a checkbox) and press Save, I need to get the selected Item ID.
you will need to add some client side scripting with jquery.
Here's how to do it:
in your .aspx define repeater as :
<asp:Repeater ID="rpt" runat="server">
<ItemTemplate>
<div class="divItem" id='divItem<%# Eval("ID") %>'>
<asp:HiddenField ID="hfSelected" runat="server" />
<asp:HiddenField ID="hfIID" runat="server" Value='<%# Eval("ID") %>' />
<asp:Image ID="imgItem" runat="server" ImageUrl='<%# Eval("ImageURL") %>' />
<asp:Label ID="lblName" runat="server" Text='<%# Eval("ItemName") %>'></asp:Label>
</div>
</ItemTemplate>
</asp:Repeater>
and then add this javascript:
<script>
$(function () {
$('.divItem').click(function () {
var item = $(this);
item.toggleClass("divItemSelected"); //mark div as selected: set background color, etc...
var selector = "#" + item.attr("id") + " input[type='hidden'][id*='hfSelected']";
var selected = $(selector).val();
if (selected == "true") {
$(selector).val("false");
} else {
$(selector).val("true");
}
});
});
</script>
And then in code-behind on button click, you do this:
protected void OnSaveClick(object sender, EventArgs e)
{
foreach (RepeaterItem item in rpt.Items)
{
HiddenField hfSelected = item.FindControl("hfSelected") as HiddenField;
bool selected = false;
bool.TryParse(hfSelected.Value, out selected);
if (selected)
{
HiddenField hfIID = e.Item.FindControl("hfIID") as HiddenField;
int id = Convert.ToInt32(hfIID.Value);
// do appropriate action as needed.
}
}
}
Hope this helps!
Regards,
Uros

How to to get hiddenfield value in ItemTemplate

Just want to ask how can I find hiddenfield in repeater because my problem I have button and I want to get the associate hiddenfield inside ItemTemplate because I get null value when I try to get hiddenfield value
<asp:Repeater ID="rp_resList" runat="server" OnItemDataBound="rp_resList_ItemDataBound">
<ItemTemplate>
<div class="resourcesResult">
<asp:HiddenField ID="hf_resID" runat="server" Value='<%# Eval("Id") %>' />
<a href='<%# Eval("pageID") %>'><%# Eval("name") %></a>
<br />
<asp:Literal ID="litSummary" runat="server" Text='<%# Eval("summary") %>'></asp:Literal>
<br />
<%-- <asp:Repeater ID="rp_tagsSkill" runat="server">
<ItemTemplate>
<h6>
<%# Eval("Description") %>
</h6>
</ItemTemplate>
</asp:Repeater>--%>
<asp:Repeater ID="rp_tagsTopics" runat="server">
<ItemTemplate>
<h6>
<%# Eval("Description") %>
</h6>
</ItemTemplate>
</asp:Repeater>
<div id="controls">
<asp:ImageButton ID="imgbtnBookmark" runat="server" OnClick="imgbtnBookmark_Click" />
<asp:DropDownList ID="ddlGroup" runat="server" DataSourceID="SqlDS_Groups" DataTextField="name" DataValueField="id" AppendDataBoundItems="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" >
<asp:ListItem Value="-1">Select Group</asp:ListItem>
protected void imgbtnBookmark_Click(object sender, System.Web.UI.ImageClickEventArgs e)
{
Bookmark bm = new Bookmark();
HiddenField hiddenField = rptGroup.FindControl("hf_resID") as HiddenField;
bm.UserID =
Guid.Parse(Membership.GetUser(HttpContext.Current.User.Identity.Name).ProviderUserKey.ToString());
bm.Resoursce.ResourceID = Convert.ToInt32(hiddenField.Value);
Bookmark.Insert(bm);
}
Try this, change you button tag to pass id as CommandArgument value
<asp:ImageButton ID="imgbtnBookmark" runat="server"
OnClick="imgbtnBookmark_Click"
CommandArgument='<%# Eval("Id") %>'/>
in your button click event you can access id using
bm.Resoursce.ResourceID = Convert.ToInt32(e.CommandArgument.ToString());
Change rptGroup.FindControl("hf_resID") as HiddenField; to
e.Item.FindControl("hf_resID")....
I hope this link will help you .
jquery
function showid(dllval) {
var ID = $(dllval).parent().parent().find('[id*="hiddenID"]').val();
alert(ID)
}
asp.net
<asp:DropDownList ID="ddl" runat="server" onclick="showid(this);" >
</asp:DropDownList>
<asp:HiddenField ID="hiddenID" runat="server" Value='<%#Eval("ID")%>' />

Limiting javascript update to just an asp:UpdatePanel

I have a GridView inside an UpdatePanel and use javascript to toggle the visibility of a row when the user clicks on an expand button. There is quite a bit of information above the GridView, but I want only the information in the respective UpdatePanel to update so that the screen will stay as is, but the JavaScript call is causing an entire screen refresh and the window jumps back to the top.
The code I'm using for the GridView actually comes from the ExtGridView control on CodeProject (http://www.codeproject.com/Articles/12299/ExtGridView) - it turns the last asp:TemplateField of a GridView into a new row beneath the other items.
I'm new to JavaScript and fairly new to ASP.NET, so I may be missing something simple. Is there a way to keep the JavaScript refresh to just the respective UpdatePanel that caused it?
Here is the JavaScript code:
<script type="text/javascript">
//<![CDATA[
function TglRow(ctl)
{
var row = ctl.parentNode.parentNode;
var tbl = row.parentNode;
var crow = tbl.rows[row.rowIndex + 1];
var ihExp = ctl.parentNode.getElementsByTagName('input').item(0);
tbl = tbl.parentNode;
var expandClass = tbl.attributes.getNamedItem('expandClass').value;
var collapseClass = tbl.attributes.getNamedItem('collapseClass').value;
var expandText = tbl.attributes.getNamedItem('expandText').value;
var collapseText = tbl.attributes.getNamedItem('collapseText').value;
if (crow.style.display == 'none')
{
crow.style.display = '';
ctl.innerHTML = collapseText;
ctl.className = collapseClass;
ihExp.value = '1';
}
else
{
crow.style.display = 'none';
ctl.innerHTML = expandText;
ctl.className = expandClass;
ihExp.value = '';
}
}//]]>
</script>
And here is an excerpt from the GridView:
<asp:UpdatePanel ID="UpdatePanelChapter11" runat="server"
ChildrenAsTriggers="false" UpdateMode="Conditional">
<ContentTemplate>
<cc1:ExtGridView ID="gvChapter11" runat="server" AutoGenerateColumns="False" DataSourceID="odsChapter11"
DataKeyNames="pkChapter11ID" ShowFooter="True" SkinID="GridViewSKin" Width="85%"
onrowcommand="gvChapter11_RowCommand"
onrowdatabound="gvChapter11_RowDataBound"
onrowupdating="gvChapter11_RowUpdating"
CollapseButtonCssClass="GridCollapseButton"
ExpandButtonCssClass="GridExpandButton" CollapseButtonText=""
ExpandButtonText="" onrowcreated="gvChapter11_RowCreated">
<Columns>
<asp:TemplateField HeaderText="Name of<br/>Party" SortExpression="Name">
<EditItemTemplate>
<asp:TextBox ID="tbName" runat="server" Text='<%# Bind("Name") %>'></asp:TextBox>
<br /><asp:RequiredFieldValidator ID="tbNameValidator" runat="server" ErrorMessage="*Name Required" ControlToValidate="tbName"
Display="Dynamic" CssClass="Error" ValidationGroup="SaveChapter11Validation"></asp:RequiredFieldValidator>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="tbName" runat="server" Text='<%# Bind("Name") %>'></asp:TextBox>
<br /><asp:RequiredFieldValidator ID="tbNameValidator" runat="server" ErrorMessage="*Name Required" ControlToValidate="tbName"
Display="Dynamic" CssClass="Error" ValidationGroup="NewChapter11Validation"></asp:RequiredFieldValidator>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<EditItemTemplate>
<asp:LinkButton CssClass="Button" ID="SaveLink" runat="server" CommandName="Update" Text="Save" ValidationGroup="SaveChapter11Validation"></asp:LinkButton>
<asp:LinkButton CssClass="Button" ID="CancelLink" runat="server" CommandName="Cancel" Text="Cancel"></asp:LinkButton>
</EditItemTemplate>
<ItemTemplate>
<asp:LinkButton CssClass="Button" ID="EditLink" runat="server" CommandName="Edit" Text="Edit"></asp:LinkButton>
<asp:LinkButton CssClass="Button" ID="DeleteLink" runat="server" CommandName="Delete" Text="Delete"
OnClientClick="return confirm('Are you sure you want to delete this entry?');" ></asp:LinkButton>
</ItemTemplate>
<FooterTemplate>
<asp:LinkButton CssClass="Button" ID="AddLink" runat="server" CommandName="Insert" Text="<<< Add" ValidationGroup="NewChapter11Validation"></asp:LinkButton>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Plan">
<EditItemTemplate>
<div class="ExtGridRow" style="vertical-align:top;">Plan: </div>
<asp:TextBox ID="tbPlan" runat="server" Text='<%# Bind("Plan") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<div class="ExtGridRow" style="vertical-align:top;">Plan: </div>
<asp:Label ID="Label9" runat="server" Text='<%# Eval("Plan") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<div class="ExtGridRow" style="vertical-align:top;">Plan: </div>
<asp:TextBox ID="tbPlan" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</cc1:ExtGridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="gvChapter11" EventName="DataBound" />
</Triggers>
</asp:UpdatePanel>
Well shoot... a little more playing around with the ExtGridView code and I figured it out. The expand/toggle button that calls the javascript also had an HRef assigned, acting as a link, so when it was clicked it would not only call the JavaScript but also acted as if a link was clicked, causing the page refresh.
The culprit code from the ExtGridView:
// ...
else if (RowType == DataControlRowType.DataRow || RowType == DataControlRowType.Footer)
{
_expCell = new TableCell();
_ctlExpand = new HtmlAnchor();
//_ctlExpand.HRef = "#"; -- Commenting this out worked!
_ctlExpand.Attributes["onclick"] = "TglRow(this);";
_ihExp = new HtmlInputHidden();
_ihExp.ID = "e" + this.DataItemIndex.ToString();
_expCell.Controls.Add(_ctlExpand);
_expCell.Controls.Add(_ihExp);
}
if (_expCell != null)
{
_expCell.Width = Unit.Pixel(20);
Cells.AddAt(0, _expCell);
}

Categories

Resources