Error on Postback - c#

I have a webpage that has a grid on it. When you click edit, a popup modal window opens. Inside the popup modal window, there is a grid and below it a dropdownlist and save button. When you click save, the selected value is inserted in the grid located in the modal window.
Everything works fine for the first time, however if you already close the modal window and you happen to do the process all over again (Click edit on the first grid > modal window shows > selects an item on the ddl > hit save button) a postback error happens. Im using an update panel and I also added a postbacktrigger to the add button inside the modal window..
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.
Code in the edit button of the first grid (this calls the modal window to open)
protected void grd_depreciation_RowEditing(object sender, GridViewEditEventArgs e)
{
Guid DepID = new Guid(grd_depreciation.DataKeys[e.NewEditIndex].Values[0].ToString());
//Show the Depreciation Modal Popup
EditModalDepPopup.Show();
//btnModalDepreciation_Click(sender,e);
//checks the type of depreciation.. Network or Equipment
DropDownList ddldescriptiondep = (DropDownList)(grd_depreciation.Rows[e.NewEditIndex].Cells[0].FindControl("ddlDescriptionDep"));
var incotype = (ddldescriptiondep.SelectedItem).ToString();
populategrd_Editdepreciation(DepID, incotype);
}
Here's the code in the add button inside the modal window (the one that causes the error):
MarginAnalysi checkmarginanalysisid = MarginAnalysisAssumption_worker.get(a => a.ProjectCode == lbl_projectCode.Text).SingleOrDefault();
DepreciationMatrix tblDepreciationMatrix = new DepreciationMatrix();
tblDepreciationMatrix.DepMatrixID = Guid.NewGuid();
tblDepreciationMatrix.DepID = new Guid(ViewState["DepID"].ToString());
tblDepreciationMatrix.IncCapexOpexID = new Guid(ddDepreciationModalEmpty.SelectedValue);
DepreciationMatrix_worker.insert(tblDepreciationMatrix);
DepreciationMatrix_worker.submit();
EditModalDepPopup.Show();
populategrd_Editdepreciation(new Guid(ViewState["DepID"].ToString()), ViewState["incotype"].ToString());
Code for to populate the grid on modal window:
//Populate Edit Depreciaiton Grid on Modal
public void populategrd_Editdepreciation(Guid DepID, string incotype)
{
ViewState["DepID"] = DepID;
ViewState["incotype"] = incotype;
var x = from a in DepreciationMatrix_worker.get(a => a.DepID == DepID)
select new { a.DepMatrixID, a.IncCapexOpexID };
grd_Editdepreciation.DataSource = x;
grd_Editdepreciation.DataBind();
//Populate dropdownlist on edit depreciation modal
MarginAnalysi checkmarginanalysisid = MarginAnalysisAssumption_worker.get(a => a.ProjectCode == lbl_projectCode.Text).SingleOrDefault();
//Selects eithers Equipment or Network Depreciation
string test = incotype.ToUpper();
if (test.Contains("EQUIPMENT"))
{
var dropdowndepreciationmodal = from a in tblIncCapexOpex_worker.get(a => a.MarginAnalysisID == checkmarginanalysisid.MarginAnalysisID && a.IncCoTypeID == "CAPEX" && a.DepreciationTypeID == "EQUIPMENT")
select new { text = a.Description, value = a.IncCapexOpexID };
populateDropdownlist(ddDepreciationModalEmpty, dropdowndepreciationmodal, true);
}
else
{
var dropdowndepreciationmodal = from a in tblIncCapexOpex_worker.get(a => a.MarginAnalysisID == checkmarginanalysisid.MarginAnalysisID && a.IncCoTypeID == "CAPEX" && a.DepreciationTypeID == "NETWORK")
select new { text = a.Description, value = a.IncCapexOpexID };
populateDropdownlist(ddDepreciationModalEmpty, dropdowndepreciationmodal, true);
}
}
Aspx Code for the Modal Pop out. This code is located inside an updatepanel tag.
<asp:Button ID="btnModalDepreciation" CssClass="popup_ButtonsHide" runat="server"
Text="Click here to show the modal" /><cc1:ModalPopupExtender BehaviorID="test4"
ID="EditModalDepPopup" BackgroundCssClass="ModalPopupBG" runat="server" TargetControlID="btnModalDepreciation"
PopupControlID="DivEditDepTab" Drag="True" PopupDragHandleControlID="DepPopupHeader"
DynamicServicePath="" Enabled="True">
</cc1:ModalPopupExtender>
<div id="DivEditDepTab" style="display: none;" class="popupConfirmation2">
<div class="popup_Container">
<div class="popup_Titlebar" id="DepPopupHeader">
<div class="TitlebarLeft">
Depreciation Items</div>
<div class="TitlebarRight">
</div>
</div>
<div class="popup_Body">
Depreciation Details
<br />
<asp:Table ID="Table25" runat="server" Width="400px">
<asp:TableRow>
<asp:TableCell>
<asp:GridView ID="grd_Editdepreciation" runat="server" AutoGenerateColumns="False"
Width="100%" OnRowCancelingEdit="grd_Editdepreciation_RowCancelingEdit" OnRowDeleting="grd_Editdepreciation_RowDeleting"
OnRowEditing="grd_Editdepreciation_RowEditing" OnRowUpdating="grd_Editdepreciation_RowUpdating"
OnRowDataBound="grd_Editdepreciation_RowDataBound" DataKeyNames="DepMatrixID">
<Columns>
<asp:TemplateField HeaderText="Depreciation" SortExpression="Depreciation">
<EditItemTemplate>
<asp:DropDownList ID="ddDepreciationModal" runat="server" Width="100%">
</asp:DropDownList>
<asp:HiddenField ID="hiddenIncCapexOpexID" runat="server" Value='<%# Bind("IncCapexOpexID") %>' />
</EditItemTemplate>
<ItemTemplate>
<asp:DropDownList ID="ddDepreciationModal" runat="server" Enabled="False" Width="100%">
</asp:DropDownList>
<asp:HiddenField ID="hiddenIncCapexOpexID" runat="server" Value='<%# Bind("IncCapexOpexID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<EditItemTemplate>
<asp:LinkButton ID="btnUpdateDepModal" runat="server" CausesValidation="True" CommandName="Update"
Text="Update"></asp:LinkButton> <asp:LinkButton ID="LinkButton2" runat="server"
CausesValidation="False" CommandName="Cancel" Text="Cancel"></asp:LinkButton></EditItemTemplate>
<ItemTemplate>
<asp:LinkButton ID="btnEditDepModal" runat="server" CausesValidation="False" CommandName="Edit"
Text="Edit"></asp:LinkButton> <asp:LinkButton ID="btnDeleteDepModal" runat="server"
CausesValidation="False" CommandName="Delete" Text="Delete"></asp:LinkButton>
<%-- <cc1:ConfirmButtonExtender ID="confirm1" TargetControlID ="btnDeleteDepModal" ConfirmText="Are you sure you want to delete this?" runat="server">
</cc1:ConfirmButtonExtender>--%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
No Data Found</EmptyDataTemplate>
</asp:GridView>
</asp:TableCell></asp:TableRow>
</asp:Table>
<asp:Table ID="Table26" runat="server" Width="400px">
<asp:TableRow>
<asp:TableHeaderCell>Depreciation</asp:TableHeaderCell></asp:TableRow>
<asp:TableRow>
<asp:TableCell Width="70%">
<asp:DropDownList ID="ddDepreciationModalEmpty" runat="server" Width="100%">
</asp:DropDownList>
</asp:TableCell><asp:TableCell Width="30%">
<asp:Button ID="btnAddDepreciationItem" runat="server" Text="Add" Height="26px" OnClick="btnAddDepreciationItem_Click"
Width="70%" /></asp:TableCell></asp:TableRow>
</asp:Table>
<asp:ValidationSummary ID="ValidationSummary22" runat="server" ValidationGroup="AddDepreciationModal" />
<asp:ValidationSummary ID="ValidationSummary23" runat="server" ValidationGroup="DeleteDepreciationModal" />
</div>
<div class="popup_Buttons">
<asp:Button ID="btnCancelDepreciationModal" runat="server" Text="Close" OnClick="CancelDepreciationItem_Click" /></div>
</div>
</div>

Have a look at my answer to this question to get an idea as to what is wrong.
https://stackoverflow.com/a/8572928/168371
The problem is not in your code but some control which is not inside an update panel and has old values in markup.
Please comment for any further assistance.

Related

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>");
}

How to correctly get cell value in gridview after clicking on a linkbutton inside a gridview and enable correct async postback to display a modal

I am making a reservation system and currently stuck on the following situation.
Basically I have a GridView which is loaded with the reservation ID and two LinkButton which opens a modal popup to enable the customer to view the details.
What I want to achieve is that when I click any LinkButton, it will show the ID from the first cell of a GridViewRow.
I have tried these methods here, here, here, and here but it still doesn't work. Is there any way to do it, Aside from using a SELECT Command and does involve async postback or if async postback is not possible with this, any fix recommended?
Here is my GridView code:
<asp:UpdatePanel runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="gvReservationSummaries"/>
</Triggers>
<ContentTemplate>
<h2>Reservations</h2>
<br />
<asp:GridView ID="gvReservationSummaries" runat="server"
AutoGenerateColumns="False" DataSourceID="SqlDataSource1"
AllowPaging="True" ShowHeader="False" CellPadding="5" CellSpacing="5"
onrowcommand="Gridview1_RowCommand">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="Label1" runat="server"><%# Eval("Master_Reservation_ID")%></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server" CommandName="ViewReservationDetails" CommandArgument='<%# DataBinder.Eval(Container, "RowIndex") %>'>View Reservation Details</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server" CommandName="ViewReceiptDetails" CommandArgument='<%# DataBinder.Eval(Container, "RowIndex") %>'>View Receipt Details</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:DB_9E4ABD_GratchiOBRSConnectionString2 %>"
SelectCommand="SELECT [Master_Reservation_ID] FROM [Master_Reservation] WHERE User_Unique_ID = #uuid">
<SelectParameters>
<asp:SessionParameter Name="uuid" SessionField="uid" />
</SelectParameters>
</asp:SqlDataSource>
<br />
<asp:Button ID="btnShowModal" runat="server" Text="Show Modal 1 (Debug Purposes Only)" onclick="btnShowModal_Click" />
<!--Here, put the details of the reservaton, plus options to edit reservation.-->
</ContentTemplate>
</asp:UpdatePanel>
</div>
</div>
<asp:Panel ID="reservationSummaryModal" runat="server" Width="500px" Height="500px" style="display: none; background-color:Black; color:#CCC;">
<asp:Button ID="btnExitRs" runat="server" Text="Hide Modal (Debug Purposes Only)" onclick="btnExitAct_Click" />
<asp:Label ID="lblReservationSummary" runat="server" Text="Label"></asp:Label>
</asp:Panel>
<asp:ModalPopupExtender ID="ModalPopupExtender1" runat="server" TargetControlID="HiddenField1" PopupControlID="reservationSummaryModal" BackgroundCssClass="modalBg" CancelControlID="btnExitRs">
</asp:ModalPopupExtender>
<asp:HiddenField ID="HiddenField1" runat="server" />
And here is my codebehind:
protected void Gridview1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "ViewReservationDetails")
{
//GridViewRow gvr = gvReservationSummaries.Rows[Convert.ToInt32(e.CommandArgument)];
gvReservationSummaries.SelectedIndex = Convert.ToInt32(e.CommandArgument);
GridViewRow gvr = gvReservationSummaries.Rows[gvReservationSummaries.SelectedIndex];
lblReservationSummary.Text = "The id is: " + gvr.Cells[0].Text.ToString();
ModalPopupExtender1.Show();
}
else if (e.CommandName == "ViewReceiptDetails")
{
gvReservationSummaries.SelectedIndex = Convert.ToInt32(e.CommandArgument);
GridViewRow gvr = gvReservationSummaries.Rows[gvReservationSummaries.SelectedIndex];
lblReservationSummary.Text = "The id is: " + gvr.Cells[0].Text.ToString();
ModalPopupExtender1.Show();
}
else
{
}
}

Dropdown does not populate when last item deleted from gridview

I am having trouble determining where the bug is for this problem.
I have an ASP.NET Master.Page web application that has a Gridview. I am using the jquery-chosen plugin for a dropdown list in the EmptyDataTemplate (or FooterControl if there is data).
On initialization if there is no data for the grid, the dropdown is populated and displays correctly. If the grid has items in it and I delete all of them, so that there is no data, the dropdown does not display any data. The DataBound event is called and the DataTable has all of the correct data in it. It is bound to the dropdown. But do items appear in the list.
This is my markup:
<div id="DelegateGridWrapper">
<asp:GridView ID="DelegateInfoGridView" runat="server"
AutoGenerateColumns="false" Caption="Delegate Information"
CaptionAlign="Top" CssClass="grid" RowStyle-Wrap="true"
HorizontalAlign="Left" ShowFooter="true"
AllowPaging="true" PageSize="5" ShowHeaderWhenEmpty="false" onrowediting="DelegateInfoGridView_RowEditing"
onrowcancelingedit="DelegateInfoGridView_RowCancelingEdit" onrowdeleting="DelegateInfoGridView_RowDeleting"
onrowupdating="DelegateInfoGridView_RowUpdating"
ondatabound="DelegateInfoGridView_DataBound"
onrowcommand="DelegateInfoGridView_RowCommand">
<Columns>
<asp:TemplateField HeaderText="Recipient ID">
<ItemTemplate>
<asp:Label ID="deligvLblRecipientID" runat="server" Text='<%# Bind("RecipientID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delegate" ItemStyle-Wrap="false">
<ItemTemplate>
<asp:Label ID="deligvLblRecipientName" runat="server" Text='<%# Bind("RecipientName") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="deligvDDLRecipientName" runat="server" ClientIDMode="Static"
data-placeholder="Choose delegate…" class="chosen-single">
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Active">
<ItemTemplate>
<asp:Label ID="deligvLblActive" runat="server" Text='<%# (Boolean.Parse(Eval("Active").ToString())) ? "Yes" : "No" %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="deligvDDLActive" runat="server" Text='<%# (Boolean.Parse(Eval("Active").ToString())) ? "Yes" : "No" %>'>
<asp:ListItem>Yes</asp:ListItem>
<asp:ListItem>No</asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="deligvDDLActiveInsert" runat="server">
<asp:ListItem Selected="True">Yes</asp:ListItem>
<asp:ListItem>No</asp:ListItem>
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Action" ItemStyle-Wrap="false" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Button ID="deligvEditButton" runat="server" CausesValidation="False" CommandName="Edit"
Text="Edit" CssClass="gridActionbutton">
</asp:Button>
<asp:Button ID="deligvDeleteButton" runat="server" CausesValidation="False" CommandName="Delete" ClientIDMode="Static"
Text="Delete" CssClass="gridActionbutton" OnClientClick="return confirm('Are you sure you want to delete this Delegate Information?')" >
</asp:Button>
</ItemTemplate>
<EditItemTemplate>
<asp:Button ID="deligvUpdateButton" runat="server" CausesValidation="False" CommandName="Update"
Text="Update" CssClass="gridActionbutton"></asp:Button>
<asp:Button ID="deligvCancelButton" runat="server" CausesValidation="False" CommandName="Cancel"
Text="Cancel" CssClass="gridActionbutton"></asp:Button>
</EditItemTemplate>
<FooterTemplate>
<asp:Button ID="deligvAddButton" runat="server" CommandName="Add" Text="Add Delegate" Width="90%" CausesValidation="false"
CssClass="gridActionbutton">
</asp:Button>
</FooterTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
<tr>
<th>Recipient ID</th>
<th>Delegate</th>
<th>Active</th>
<th>Action</th>
</tr>
<tr>
<td colspan="4" style="text-align:center;">
No Delegates were found for you. Delegates can be added by clicking the 'Add Delegate' Button.
</td>
</tr>
<tr>
<td></td>
<td>
<asp:DropDownList ID="deligvDDLRecipientName" runat="server" ClientIDMode="Static"
data-placeholder="Choose delegate…" class="chosen-single">
</asp:DropDownList>
</td>
<td>
<asp:DropDownList ID="deligvDDLActiveInsert" runat="server">
<asp:ListItem Selected="True">Yes</asp:ListItem>
<asp:ListItem>No</asp:ListItem>
</asp:DropDownList>
</td>
<td>
<asp:Button ID="deligvAddButtonEmpty" runat="server" CommandName="Add" Text="Add Delegate" Width="90%" CausesValidation="false"
CssClass="gridActionbutton">
</asp:Button>
</td>
</tr>
</EmptyDataTemplate>
</asp:GridView>
This is my DataBound event:
protected void DelegateInfoGridView_DataBound(object sender, EventArgs e)
{
try
{
m_strUserID = CommonMethods.ParseUserID(User.Identity.Name);
//Get the Footer controls that have the new entry data
Control tFooterControls = getFooterControls(DelegateInfoGridView);
DropDownList ddlRecipientNames = tFooterControls.FindControl("deligvDDLRecipientName") as DropDownList;
m_strXmlTableData = m_pagingClient.GetAllPossibleDelegates(m_strUserID);
DataTable tdtAllDelegates = CommonMethods.ParseXML(m_strXmlTableData);
ddlRecipientNames.DataSource = tdtAllDelegates;
ddlRecipientNames.DataTextField = "RecipientName";
ddlRecipientNames.DataValueField = "RecipientID";
ddlRecipientNames.DataBind();
ddlRecipientNames.Items.Insert(0, new ListItem("", "0"));//This is needed for the jquery-chosen dropdown to add data-holder text
}
catch (Exception ex)
{
//TO DO: Response.Redirect("~/Error.aspx");
}
}
Why won't the dropdown display the items after all items are deleted but will correctly display if initially there are no items in the gridview to display?
I tried triggering an update for the chosen dropdown but that is called initially, before the data is retrieved.
I don't know if there is a bug in the code-behind or do I need to add something in the javascript.
Thanks.
UPDATE
The problem is not with the chosen plugin. I removed the attribute from the DropDown list that changes it to a 'chosen' style and the problem still exists. So the asp:DropDownList will not populate after the user deletes all of the items in the grid. But if the grid is initialized with no items, the DropDown is correctly populated.
UPDATE
I got a suggestion to use the 'RowDeleted' event to bind the dropdown. However, the event is not firing. I added the event to the markup:
onrowdeleted="DelegateInfoGridView_RowDeleted"
This is the event that is never called:
protected void DelegateInfoGridView_RowDeleted(object sender, GridViewDeletedEventArgs e)
{
try
{
m_strUserID = CommonMethods.ParseUserID(User.Identity.Name);
//Get the Footer controls that have the new entry data
Control tFooterControls = getFooterControls(DelegateInfoGridView);
DropDownList tddlRecipientNames = tFooterControls.FindControl("deligvDDLRecipientName") as DropDownList;
m_strXmlTableData = m_pagingClient.GetAllPossibleDelegates(m_strUserID);
DataTable tdtAllDelegates = CommonMethods.ParseXML(m_strXmlTableData);
tddlRecipientNames.DataSource = tdtAllDelegates;
tddlRecipientNames.DataTextField = "RecipientName";
tddlRecipientNames.DataValueField = "RecipientID";
tddlRecipientNames.DataBind();
tddlRecipientNames.Items.Insert(0, new ListItem("", "0"));//This is needed for the jquery-chosen dropdown to add data-holder text
}
catch (Exception ex)
{
//TO DO: Response.Redirect("~/Error.aspx");
}
}
What is different about the RowDeleted event that it will not fire?
The problem was that I was checking if the FooterControl was null. If it was, I got the EmptyTemplateData control. When you delete all of the rows, the FooterControl is not null, but it needs to get the EmptyTemplateData control.
So, I changed the logic to check for Grid Row Count > 0 instead of a null FooterControl.
That fixed the problem..

Asp.NET: How to keep focus on textbox in a nested Update Panel

I am working on making a semi simple post and reply/forum pages in asp.net(with C#). Everything works however when I went to add update panels it makes me want to throw my head into a wall.
I use a DataList to display the posts. I use a form consisting of two textboxes and a button to insert a new post. One textbox if for the name, and the other for the message.
First update panel I added (nested) is to provide a character count for the post. I have a label in the Content and it is triggered by the textboxes textchanged event. The textbox 'txtMessage' also has a java-script function run 'onkeyup' to keep the focus on the textbox when typing. I limit the characters at 1000.
The next update is to surround the DataList so that it does not post back everytime (if not used and the back button is hit it will go back and visually remove each post which is not a good design practice). However when I just put the panel around the DataList it did not postback the insert form so the boxes were not cleared. Which I would like to be done, so I wrapped everything then by this updatepanel, which then made the character count update panel nested by this one. This now works, but the focus is taken off of the txtMessage box each time the textchanged event fires. So the JavaScript is not firing now?
I have moved the opening and closing of the update panel countless times and have tried different fixes, so any further suggestions would help. The code is below.
ForumT.aspx
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="ForumT.aspx.cs" Inherits="UPE_Site_v1.ForumT" %>
<asp:Content ID="Content1" ContentPlaceHolderID="title" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="headPlaceHolder" runat="server">
<script type="text/javascript">
function reFocus(id) {
__doPostBack(id, '');
document.getElementById(id).blur();
document.getElementById(id).focus();
}
</script>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="contentPlaceHolder" runat="server">
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" SelectMethod="GetPosts" TypeName="TimeTrackerRepository" DataObjectTypeName="System.Guid" DeleteMethod="DeletePost"> </asp:ObjectDataSource>
<asp:UpdatePanel ID="upDataList" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<div>
<asp:DataList ID="DataList2" runat="server" CellPadding="4" DataSourceID="ObjectDataSource1"
ForeColor="#333333" OnItemCommand="DataList2_ItemCommand" OnItemDataBound="DataList2_ItemDataBound"
DataKeyField="PostID" OnItemCreated="DataList2_ItemCreated">
<AlternatingItemStyle BackColor="White" />
<FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<ItemStyle BackColor="#D4EBD4" />
<ItemTemplate>
<div class="row">
<div class="col-xs-12 col-sm-6">
Name: <strong><%# Eval("Name") %></strong>
</div>
<div class="col-xs-12 col-sm-6">
<%# Eval("TimePosted") %>
</div>
<div class="col-xs-12" style="word-break: break-all">
<%# Eval("Message") %>
</div>
</div>
<br />
<asp:Button ID="btnDelete" CssClass="btn btn-warning" runat="server" Text="Delete" CommandArgument='<%# Eval("PostID") %>' CommandName="DeleteItem" />
<asp:LinkButton CssClass="btn btn-primary" ID="lkbtnFullPost" runat="server" Text="See Full Post" CommandArgument='<%# Eval("PostID") %>' CommandName="FullPost"></asp:LinkButton>
</ItemTemplate>
<SelectedItemStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
</asp:DataList>
</div>
<%--</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnPost" EventName="Click" />
</Triggers>
</asp:UpdatePanel>--%>
<br />
<br />
<div class="row">
<div class="col-xs-12 col-sm-10 col-md-8 col-lg-6 col-sm-offset-1 col-md-offset-2 col-lg-offset-3">
<p>Add a post to this forum:</p>
<div class="form-group">
<asp:Label ID="Label1" runat="server" Text="Name: "></asp:Label>
<asp:TextBox CssClass="form-control" ID="txtName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator runat="server" ControlToValidate="txtName"
ErrorMessage="This is a required field." ValidationGroup="Application"
Display="Dynamic" ForeColor="Red">
</asp:RequiredFieldValidator>
</div>
<%--<asp:UpdatePanel ID="upMessage" runat="server" UpdateMode="Conditional">
<ContentTemplate>--%>
<div class="form-group">
<asp:Label ID="Label2" runat="server" Text="Message: "> </asp:Label>
<asp:TextBox onkeyup="reFocus(this.id);" CssClass="form-control" ID="txtMessage" runat="server" TextMode="MultiLine" Rows="4" OnTextChanged="txtMessage_TextChanged"></asp:TextBox>
<asp:RequiredFieldValidator runat="server" ControlToValidate="txtMessage"
ErrorMessage="This is a required field." ValidationGroup="Application"
Display="Dynamic" ForeColor="Red">
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator runat="server" ControlToValidate="txtMessage"
ErrorMessage="Character limit is 1000 characters."
ValidationGroup="Application" Display="Dynamic" ForeColor="Red"
ValidationExpression=".{0,1000}">
</asp:RegularExpressionValidator>
</div>
<br />
<%--</div>
</div>--%>
<%--</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnPost" EventName="Click" />
</Triggers>
</asp:UpdatePanel>--%>
<%--<div class="row">
<div class="col-xs-12 col-sm-10 col-md-8 col-lg-6 col-sm-offset-1 col-md-offset-2 col-lg-offset-3">--%>
<asp:UpdatePanel ID="upMessage" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="lblCharacterCount" runat="server">0/1000</asp:Label>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="txtMessage" EventName="TextChanged" />
</Triggers>
</asp:UpdatePanel>
<asp:Button ValidationGroup="Application" CssClass="btn btn-default" ID="btnPost" runat="server" Text="POST IT" OnClick="btnPost_Click" />
<asp:Label ID="lblError" runat="server" Text="" CssClas="Error" ForeColor="Red"></asp:Label>
</div>
</div>
<br />
<br />
<br />
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
ForumT.aspx.cs
only including the textchanged event
protected void txtMessage_TextChanged(object sender, EventArgs e)
{
lblCharacterCount.Text = txtMessage.Text.Count().ToString() + "/1000";
if (txtMessage.Text.Count() >= 1000)
{
lblCharacterCount.ForeColor = System.Drawing.Color.Red;
}
else
{
lblCharacterCount.ForeColor = System.Drawing.Color.Black;
}
}
Sorry for the code being a little sloppy. Also side not, I am using bootstrap so that is what all of the div's are for
I was facing the same issue as I needed to set focus on the textbox after postbacks in update panel. So I researched over internet & found this Javascript code. I tried it & it is working perfectly. It adds event listener for update panel for before & after postback. Gets textbox id before postback & set it after completion of postback.
var lastFocusedControlId = "";
function focusHandler(e) {
document.activeElement = e.originalTarget;
}
function appInit() {
if (typeof (window.addEventListener) !== "undefined") {
window.addEventListener("focus", focusHandler, true);
}
Sys.WebForms.PageRequestManager.getInstance().add_pageLoading(pageLoadingHandler);
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(pageLoadedHandler);
}
function pageLoadingHandler(sender, args) {
lastFocusedControlId = typeof (document.activeElement) === "undefined"
? "" : document.activeElement.id;
}
function focusControl(targetControl) {
if (Sys.Browser.agent === Sys.Browser.InternetExplorer) {
var focusTarget = targetControl;
if (focusTarget && (typeof (focusTarget.contentEditable) !== "undefined")) {
oldContentEditableSetting = focusTarget.contentEditable;
focusTarget.contentEditable = false;
}
else {
focusTarget = null;
}
targetControl.focus();
if (focusTarget) {
focusTarget.contentEditable = oldContentEditableSetting;
}
}
else {
targetControl.focus();
}
}
function pageLoadedHandler(sender, args) {
if (typeof (lastFocusedControlId) !== "undefined" && lastFocusedControlId != "") {
var newFocused = $get(lastFocusedControlId);
if (newFocused) {
focusControl(newFocused);
}
}
}
Sys.Application.add_init(appInit);
Just use this code in your script on aspx page.
You say your javascript is not working. When using update panels and js you will need to rebind your js subscribed events.
Reference: jQuery $(document).ready and UpdatePanels?

How to check atleast one checkbox is checked?

I have ascx page in that I have a grid in side that I have added radio button, I want to check at least one checkbox should be checked before unload the page or clicking on btn save.
<asp:GridView ID="grdTest" runat="server" DataKeyNames="Id" AutoGenerateColumns="False" HorizontalAlign="Center" GridLines="None" onrowcreated="grdTest_RowCreated">
<asp:TemplateField >
<ItemTemplate>
<asp:TextBox ID="txtText" Rows="10" Columns="40" runat="server" TextMode="MultiLine" Height="55px" Text='<%# Eval("Text") %>'></asp:TextBox>
<asp:Button ID="btnSave" runat="server" Text="Save" CommandName="Save"/>
<span id="checkbox">
<asp:RadioButton ID="rbtnTest" runat="server" Checked='<%# Eval("Correct") %>' TextAlign="Left" Height="28px" />
</span>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtText" Rows="10" Columns="40" runat="server" TextMode="MultiLine" />
<asp:Button ID="btnSave" runat="server" Text="Save" CommandName="Save"/>
<asp:CheckBox ID="rbtnTest" runat="server" Enabled="true" TextAlign="Left"/>
</EditItemTemplate>
</asp:TemplateField>
</asp:GridView>
How is this possible plz some one help me?
<script type="text/javascript" language="javascript">
function Validate_Checkbox()
{
var chks=document.getElementsByTagName('input');
var hasChecked = false;
for (var i = 0; i < chks.length; i++)
{
if (chks[i].checked)
{
hasChecked = true;
break;
}
}
if (hasChecked == false)
{
alert("Please select at least one checkbox..!");
return false;
}
return true;
}
</script>
and on Submit Button you have to write
OnClientClick="return Validate_Checkbox()"

Categories