About Asp.Net DataList Commands And EventValidation - asp.net

I have Datalist that is inside an updatepanel and it is in panel in modalpopupextender;
I can list items as I wanted. I am also putting 2 buttons for Delete and AddBelow. Here is the markup:
<asp:DataList ID="SpeedDialsDL" runat="server">
<ItemTemplate>
<table id="speedDialValueEditorTable" width="100%">
<tr>
<td width="275px">
<asp:Label ID="ValueLabel" runat="server" Text="Value"></asp:Label>
</td>
<td>
<asp:TextBox ID="ValueTextBox" runat="server" Text='<%# Eval("Value") %>' Width="340px"
Enabled="false"></asp:TextBox>
</td>
</tr>
<tr>
<td colspan="2">
<asp:Button ID="Delete" runat="server" Text="Delete" CommandName="Delete"
CausesValidation="false" />
<asp:Button ID="AddNewButton" runat="server" Text="AddBelow" CommandName="AddBelow"
CausesValidation="false" />
</td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
And register evenst like following: (I have used both ItemCommand and DeleteCommand to see which works:)
protected void Page_Load(object sender, EventArgs e)
{
SpeedDialsDL.ItemCommand += SpeedDialsDL_ItemCommand;
SpeedDialsDL.DeleteCommand += SpeedDialsDL_ItemCommand;
}
void SpeedDialsDL_ItemCommand(object source, DataListCommandEventArgs e)
{
switch (e.CommandName)
{
case "Delete":
this.DeleteFromList((string)e.CommandArgument);
break;
case "AddBelow":
break;
}
}
But when I click Delete Or AddBelow buttons I get following error:
Invalid postback or callback argument. Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%# Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.
I have disabled eventvalidation of page but the event couldn't be caught...
What am I missing here?

A control registers its events during rendering and then validates the events during the post-back or callback handling. You're registering the events manually during Page_Load.
Try refactoring your code so you specify the event handler in the .aspx page, bind the item's Id to the button's CommandArgument, then get the bound item Id in the handler. I would also have separate event handlers for the different events, it's a little cleaner. Something like:
<asp:DataList ID="SpeedDialsDL" runat="server">
<ItemTemplate>
<table id="speedDialValueEditorTable" width="100%">
<tr>
<td width="275px">
<asp:Label ID="ValueLabel" runat="server" Text="Value"></asp:Label>
</td>
<td>
<asp:TextBox ID="ValueTextBox" runat="server" Text='<%# Eval("Value") %>' Width="340px" Enabled="false"></asp:TextBox>
</td>
</tr>
<tr>
<td colspan="2">
<asp:Button ID="Delete" runat="server" Text="Delete" OnClick="Delete" CausesValidation="false" CommandArgument='<%# Eval("Id") %>' />
<asp:Button ID="AddNewButton" runat="server" Text="AddBelow" OnClick="AddBelow" CausesValidation="false" CommandArgument='<%# Eval("Id") %>' />
</td>
</tr>
</table>
</ItemTemplate>
protected void Delete(object sender, EventArgs e)
{
Button b = (Button)sender as Button;
string boundItemId = b.CommandArgument;
//handle delete
}
protected void AddBelow(object sender, EventArgs e)
{
Button b = (Button)sender as Button;
string boundItemId = b.CommandArgument;
//handle add below
}

Related

Updating <tr> visible with RadComboBox selectedindexchanged is Firing but not updating

Im new to ASP C# and I just want to ask on what is wrong on my code. It is going on the SelectedIndexChanged but not updating the visibility of my <tr>
Here is my ClientSide code
<tr id="trList2" runat="server" visible="false">
<td>
<asp:Label ID="lblList" AssociatedControlID="rcbList" runat="server" Text="Car List:" />
</td>
<td>
<telerik:RadComboBox ID="rcbList" runat="server" Skin="Sunset" Width="400px" DataTextField="car_name"
DataValueField="car_id" AppendDataBoundItems="true"
OnSelectedIndexChanged="rcbList_SelectedIndexChanged" AutoPostBack="true" >
<Items>
<telerik:RadComboBoxItem Value="0" Text="[Select Project]" />
</Items>
</telerik:RadComboBox>
</td>
</tr>
<tr id="trList4" runat="server" visible="false">
<td>
<asp:Label runat="server" AssociatedControlID="chkIsOpen">Check if Open</asp:Label>
</td>
<td>
<asp:CheckBox runat="server" ID="chkIsOpen" OnCheckedChanged="IsOpen_CheckedChange" AutoPostBack="true" />
</td>
</tr>
Here is my Server Side:
protected void rcbList_SelectedIndexChanged(object sender, EventArgs e)
{
var checkVal = rcbList.SelectedIndex;
if (rcbList.SelectedValue != "0")
{
trList4.Visible = false;
}
else
{
trList4.Visible = true;
}
}
im getting the error
Uncaught Sys.InvalidOperationException: Sys.InvalidOperationException: Could not find UpdatePanel with ID "xxx". If it is being updated dynamically then it must be inside another UpdatePanel in browser element but I dont have any updatepanel in my Page

No file chosen is displayed in Fileupload control after fileupload control assigned value from session in asp.net

I have file upload control inside update panel and repeater control. Repeater control has an image button. When this button is pressed the postback occurs and File upload control has no value. I used postback trigger to store fileupload control in session when postback occurs.
At the time of page load we are assigning fileupload control from session
but Fileupload control shows No file chosen instead of selected file name.
<tr>
<td>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:FileUpload ID="FileUpload1" runat="server" CssClass="text"/>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="ApplicationUrl_Repeater" />
</Triggers>
</asp:UpdatePanel>
</td>
</tr>
<tr runat="server" visible="false" id="ApplicationUrl">
<td>
<asp:Repeater ID="ApplicationUrl_Repeater" runat="server" OnItemCommand="RepeaterItemCommmand11" OnItemDataBound="RepeaterItemDataBound11" Visible="True">
<ItemTemplate>
<table>
<tr>
<td>
<asp:TextBox ID="Repeater_ApplicationUrl_TxtBox" Text='<%# Eval("Url") %>' runat="server" CssClass="text" Width="200" MaxLength="1024"></asp:TextBox>
<asp:DropDownList ID="Repeater_ApplicationType_DropdownList" runat="server"></asp:DropDownList>
<asp:ImageButton ID="Repeater_ImgButton" runat="server" CssClass="AddIcon" Height="15px" ImageAlign="Bottom" />
</td>
</tr>
</table>
</ItemTemplate>
</asp:Repeater>
</td>
</tr>
protected void RepeaterItemCommmand11(object source, RepeaterCommandEventArgs e)
{
if (Session["FileUpload1"] == null && FileUpload1.HasFile)
{
Session["FileUpload1"] = FileUpload1;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if(Page.IsPostBack)
{
if (Session["FileUpload1"] != null && !FileUpload1.HasFile)
{
FileUpload1 = (FileUpload)Session["FileUpload1"];
Session.Remove("FileUpload1");
}
}
}
I want fileupload control should display file name after postback.
Please suggest.
Thanks in advance.

Visible property not showing the controls

I have created an aspx page in which I want some controls to be enabled on basis of user selection.
If user selects All two radio buttons should be enabled, hide otherwise.
My declarative part is:
<tr>
<td>
<asp:Label ID="lblCommunityMembers" runat="server" Text="Community Members" />
</td>
<td>
<asp:ScriptManagerProxy ID="ScriptManagerProxy1" runat="server">
</asp:ScriptManagerProxy>
<asp:UpdatePanel ID="upCommunityMembers" runat="server">
<ContentTemplate>
<asp:RadioButton ID="rdbCommunityMembersAll" runat="server" Text="All" GroupName="grpCommMembers" Checked="true" OnCheckedChanged="rdbCommunityMembersAll_CheckedChanged" AutoPostBack="true" />
<asp:RadioButton ID="rdbCommunityMembersSelectedUsers" runat="server" Text="Selected Users" GroupName="grpCommMembers" OnCheckedChanged="rdbCommunityMembersSelectedUsers_CheckedChanged" AutoPostBack="true" />
<SharePoint:ClientPeoplePicker ID="ppCommunityMembers" runat="server" AllowMultipleEntities="true" AllowEmpty="false" Visible="false" />
</ContentTemplate>
</asp:UpdatePanel>
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblCommunityCatagory" runat="server" Text="Community Catagory" />
</td>
<td>
<asp:DropDownList ID="ddlCommunityCatagory" runat="server">
<asp:ListItem Value="0">---- Select One ----</asp:ListItem>
</asp:DropDownList>
</td>
<td>
<asp:RequiredFieldValidator ID="rfvCommunityCatagory" runat="server" InitialValue="0" ErrorMessage="Please Select Community Catagory"
ForeColor="Red" ControlToValidate="ddlCommunityCatagory" Display="Dynamic" />
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblCommunityAccess" runat="server" Text="Required Approval?" Visible="false" />
</td>
<td>
<asp:RadioButton ID="rdbRequiredApprovalYes" runat="server" Text="Yes" GroupName="grpCommMembers" Checked="true" Visible="false" />
<asp:RadioButton ID="rdbRequiredApprovalNo" runat="server" Text="No" GroupName="grpCommMembers" Visible="false"/>
</td>
</tr>
My code behind:
protected void rdbCommunityMembersSelectedUsers_CheckedChanged(object sender, EventArgs e)
{
if (rdbCommunityMembersSelectedUsers.Checked)
{
enableControls();
}
else
{
disableControls();
}
}
protected void rdbCommunityMembersAll_CheckedChanged(object sender, EventArgs e)
{
if (rdbCommunityMembersAll.Checked)
{
disableControls();
}
else
{
enableControls();
}
}
protected void enableControls()
{
ppCommunityMembers.Visible = true;
lblCommunityAccess.Visible = true;
rdbRequiredApprovalNo.Visible = true;
rdbRequiredApprovalYes.Visible = true;
}
protected void disableControls()
{
ppCommunityMembers.Visible = false;
lblCommunityAccess.Visible = false;
rdbRequiredApprovalNo.Visible = false;
rdbRequiredApprovalYes.Visible = false;
}
If Community members are selected to all then "Required Approval?" part should get hidden.
But problem is when I select selected users then I am getting only people picker control visible, the required approval contorls are not getting displayed. What am I missing?
Your Radio Buttons rdbCommunityMembersAll and rdbCommunityMembersSelectedUsers are inside update panel, thus they are doing partial postback. To make the control visible outside the UpdatePanel you can do any one of the following:
Move rdbCommunityMembersAll and rdbCommunityMembersSelectedUsers
outside the UpdatePanel
Move the controls you need to make visible
(lblCommunityAccess, rdbRequiredApprovalNo, rdbRequiredApprovalYes)
inside UpdatePanel
Or
Instead of setting Visible="false", set style="display:none" and
trigger the visibility through javascript/jquery

.net ListView eventValidation error after RegisterforEventValidation

I have the following Listview defined
<asp:ListView
ID="reportData"
EnableSortingAndPagingCallback="True"
AllowPaging="True"
AllowSorting="True"
PageSize="20"
OnLayoutCreated="LoadReport"
onsorting="reportData_Cause_Sorting"
OnPagePropertiesChanging="reportData_PagePropertiesChanging"
runat="server">
I also have a DataPager defined
<asp:DataPager ID="reportPager" PagedControlID="reportData" PageSize="20" runat="server" >
<Fields>
<asp:NextPreviousPagerField ButtonType="Button" ShowFirstPageButton="True" ShowLastPageButton="True" />
</Fields>
</asp:DataPager>
Then, since i Have enableEventValidation set to true, i also have the item registered
Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)
Page.ClientScript.RegisterForEventValidation(reportData.UniqueID)
Page.ClientScript.RegisterForEventValidation(reportPager.UniqueID)
MyBase.Render(writer)
End Sub
My Initial page load runs just fine, however when I click on a page navigation I am sent to the codebehind and get through the page_load before I receive the error
Invalid postback or callback argument. Event validation is enabled
using in configuration or <%#
Page EnableEventValidation="true" %> in a page. For security
purposes, this feature verifies that arguments to postback or callback
events originate from the server control that originally rendered
them. If the data is valid and expected, use the
ClientScriptManager.RegisterForEventValidation method in order to
register the postback or callback data for validation.
I just don't understand why I am continuing to receive the error after I have registered both items for event validation. I never even make it into the RaiseCallbackEvent!
I am a total newbie to these controls and by no means a .net expert either. Any help or advice would be greatly appreciated!
I found the answer. I was calling my function to load the report data and bind it to the ListView both in OnLoad and Render. When I removed the extra call from OnLoad, I no longer received the message. However, paging is still not working, but the problem has moved to a different spot in the code :)
try this simple example.
url passes the values ​​of the paging
protected void DepartmentsListView_SelectedIndexChanged(object sender, ListViewCommandEventArgs e)
{
MessageLabel.Text = "The key value is " +
CountriesListView.SelectedValue.ToString() + ".";
}
<asp:ListView ID="CountriesListView" DataSourceID="ContactsDataSource" runat="server"
DataKeyNames="FirstName" OnItemCommand="DepartmentsListView_SelectedIndexChanged">
<LayoutTemplate>
<table cellpadding="4" width="500" runat="server" id="tblCountries">
<tr id="Tr1" runat="server">
<th id="Th0" runat="server">
ID
</th>
<th id="Th1" runat="server">
Code
</th>
<th id="Th2" runat="server">
Name
</th>
</tr>
<tr runat="server" id="itemPlaceholder" />
</table>
</LayoutTemplate>
<ItemTemplate>
<tr>
<td>
<asp:LinkButton runat="server" ID="SelectButton" Text="Select" CommandName="Select" />
</td>
<td>
<asp:Label ID="CountryCodeLabel" runat="server" Text='<%# Eval("EmployeeID")%>' />
</td>
<td>
<asp:Label ID="NameLabel" runat="server" Text='<%# Eval("FirstName")%>' />
</td>
</tr>
</ItemTemplate>
</asp:ListView>
<asp:DataPager runat="server" ID="DataPager2" PageSize="3" PagedControlID="CountriesListView"
QueryStringField="pageNumber">
<Fields>
<asp:NumericPagerField />
</Fields>
</asp:DataPager>
<asp:SqlDataSource ID="ContactsDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:conecec %>"
SelectCommand="SELECT [EmployeeID], [FirstName], [LastName] FROM Employees">
</asp:SqlDataSource>
I think you don't need to change EventValidation or use RegisterForEventValidation
Put this code in Page_Load event
if (!IsPostBack)
{
BindData();
}
And do not forget modify the PagePropertiesChanged Event of ListViews :
protected void lstProducts_PagePropertiesChanged(object sender, EventArgs e)
{
BindData();
}

Accessing controls in the edititemtemplate of a listview

I am working with the listview control. By default I am showing the itemtemplate with an edit button. When the edit button is pressed the listview switches to the edititemtemplate. I need to populate one of the controls in the edititemtemplate based on the item being edited - I've tried accessing the control (via FindControl) in the ItemEditing event (and pretty much every other event as well), however the controls just don't seem to exist. I can access controls in the itemtemplate ok, but not the edititemtemplate.
Can anyone let me know how I can access a control held within the edititemtemplate of a listview, and from which event I should do so?
EDIT
I'm trying to access the control using this:
protected void UnitsLV_ItemEditing(object sender, ListViewEditEventArgs e)
{
ListViewItem item = UnitsLV.Items[e.NewEditIndex];
ListBox tempLB = (ListBox)e.item.FindControl("ListBox3");
}
I've also tried in ItemDataBound and ItemCreated.
The listview declaration is:
<asp:Content ID="Content1" ContentPlaceHolderID="ColumnA" runat="server">
<asp:Panel ID="Panel1" runat="server">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Panel ID="SummaryPnl" runat="server">
<asp:ListView ID="UnitsLV" runat="server" DataSourceID="DataLDS" DataKeyNames="u_uid"
InsertItemPosition="LastItem" OnItemInserting="UnitsLV_ItemInserting" OnItemDataBound="UnitsLV_ItemDataBound"
OnItemCreated="UnitsLV_ItemCreated" onitemediting="UnitsLV_ItemEditing">
<ItemTemplate>
<tr class="rowA">
<td>
<asp:Label runat="server" ID="UnitIDLbl" Text='<%# Eval("u_uid")%>'></asp:Label>
</td>
<td>
<%# Eval("u_Title")%>
</td>
<td>
<asp:LinkButton ID="EditBtn" runat="server" CommandName="Edit" CommandArgument='<%#Eval("u_uid") %>'
Text="Edit" />
</td>
<td>
<asp:LinkButton ID="DeleteBtn" runat="server" CommandName="Delete" CommandArgument='<%#Eval("u_uid") %>'
Text="Delete" />
</td>
</tr>
</ItemTemplate>
<InsertItemTemplate>
<tr class="rowB">
<td>
<br />
</td>
<td>
<br />
<asp:TextBox ID="TitleTB" runat="server" Text='<% #Bind("u_Title")%>'></asp:TextBox>
</td>
<td>
<br />
<asp:ListBox ID="ListBox3" runat="server"></asp:ListBox>
<asp:ListBox ID="ToBeDeletedLB" runat="server"></asp:ListBox>
</td>
<td>
<asp:LinkButton ID="InsertBtn" runat="server" CommandName="Insert" Text="Insert" />
</td>
<td>
<asp:LinkButton ID="CancelBtn" runat="server" CommandName="Cancel" Text="Cancel" />
</td>
</tr>
</InsertItemTemplate>
<EditItemTemplate>
<tr class="rowB">
<td>
<br />
<asp:Label runat="server" ID="UnitIDLbl" Text='<%# Bind("u_uid")%>'></asp:Label>
</td>
<td>
<br />
<asp:TextBox ID="TitleTB" runat="server" Text='<% #Bind("u_Title")%>'></asp:TextBox>
</td>
<td>
<br />
<asp:ListBox ID="ListBox3" runat="server"></asp:ListBox>
<asp:ListBox ID="ToBeDeletedLB" runat="server"></asp:ListBox>
</td>
<td>
<asp:LinkButton ID="UpdateBtn" runat="server" CommandName="Update" Text="Update" />
</td>
<td>
<asp:LinkButton ID="LinkButton2" runat="server" CommandName="Cancel" Text="Cancel" />
</td>
</tr>
</EditItemTemplate>
<LayoutTemplate>
<table id="Table2" runat="server" width="100%">
<tr id="Tr1" runat="server">
<td id="Td1" runat="server">
<table id="itemPlaceholderContainer" runat="server" border="0" style="" width="100%">
<tr id="itemPlaceholder" runat="server"></tr>
</table>
</td>
</tr>
<tr id="Tr2" runat="server">
<td id="Td2" runat="server" style=""></td>
</tr>
</table>
</LayoutTemplate>
</asp:ListView>
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Panel>
</asp:Content>
EDIT:
I've iterated over all the controls in the listview using code similar to below, and the control is still not visible. Does the ItemEditing event fire before the edit template is shown? If so, what event can I use to access the edit template controls?
foreach (Control child in control.Controls)
{
Control result = Find(child, id);
if (result != null)
{
return result;
}
}
**EDIT: **
I can access the controls in the edititemtemplate in the listview's ItemCreated event, however none they have no content (I'd assume the data hasn't been bound yet), so I can't get the key-value I need to do a lookup to get the data I need to populate the control.
I've figured out a way to do what I need to do, though I'm not terribly happy with it.
protected void UnitsLV_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (UnitsLV.EditIndex > -1)
{
// Controls within the edititemtemplate are available via e.Item.FindControl("controlname")
}
}
I don't know about previous editions but in Visual Studio 2010 you can easily access the edit item trhough the "ListView.EditItem" property like this:
private void myListView_ItemEditing(object sender, ListViewEditEventArgs e)
{
myListView.EditIndex = e.NewEditIndex;
myListView.DataBind();
ListViewItem lvwItem = lvwLista.EditItem;
ListBox tempLB = (ListBox) lvwItem.FindControl("ListBox3");
}
protected void ListView1_ItemUpdating(object sender, ListViewUpdateEventArgs e)
{
ListBox myListBox = (ListBox)(((ListView)sender).EditItem.FindControl("ListBox1"));
}
protected void UnitsLV_ItemEditing(object sender, ListViewEditEventArgs e)
{
ListViewItem item = UnitsLV.Items[e.NewEditIndex];
ListBox tempLB = (ListBox)e.item.FindControl("ListBox3");
}
I believe I found a typo in the above function. The second line should be
ListBox tempLB = (ListBox)item.FindControl("ListBox3");
What I did was replace "e.item" with "item"
I usually use the ItemDataBound Event... check the other options in ListItemType Enum
protected void UnitLV_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.EditItem)
{
ListBox myListBox = (ListBox) e.Item.FindControl("ListBox3");
}
}
this is similar to the accepted answer, but I think its author was really driving towards this:
protected void UnitsLV_ItemDataBound(object sender, ListViewItemEventArgs e)
{
ListViewDataItem listViewDataItem = e.Item as ListViewDataItem;
if (UnitsLV.EditIndex == listViewDataItem.DataItemIndex)
{
// Controls within the edititemtemplate are available via e.Item.FindControl("controlname")
}
}

Resources