I have a radiobuttonlist with a selectedindexchanged event that updates a search function. One of the items is specified in the aspx, and the others are appended databound items. No matter what I set as the default, that item will not fire the event. All other items will fire the event. Also, it seems that after the "dead" item is selected, the event won't fire at all.
How can I track down the error and correct? Here is current code.
EDIT: Sorry if the short version was misleading. I wasn't sure what to include. Here is the whole page.
All aspx:
<%# Page Language="C#" MasterPageFile="~/MSDS/MSDS.master" EnableEventValidation="false"
AutoEventWireup="true" CodeFile="SearchMSDS.aspx.cs" Inherits="MSDS_ByDept" Title="NCLWeb - Search MSDS" %>
<%# Register Assembly="SqlWhereBuilder" Namespace="UNLV.IAP.WebControls" TagPrefix="cc1" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc2" %>
<asp:Content ID="Content1" ContentPlaceHolderID="PageContent" runat="Server">
<h2>
<asp:Label ID="lblTitle" runat="server">Search Active MSDS</asp:Label></h2>
<table class="style1">
<tr>
<td style="width: 435px" valign="top">
<asp:Panel runat="server" ID="pnlSearch" DefaultButton="btnSearch">
<asp:TextBox ID="txtSimpleSearch" runat="server" Width="262px"></asp:TextBox>
<asp:Button ID="btnSearch" runat="server" Text="Search" Width="96px" OnClick="btnSearch_Click" />
<br />
<asp:LinkButton ID="btnAdvSearch" runat="server" OnClick="btnAdvSearch_Click" Font-Size="Small">Show Advanced Search</asp:LinkButton>
</asp:Panel>
<asp:Panel ID="pnlAdvSearch" runat="server" Width="635px" DefaultButton="btnRunAdvSearch">
<asp:Button ID="btnRunAdvSearch" runat="server" OnClick="btnRunAdvSearch_Click" Text="Advanced Search" />
<cc1:SqlWhereBuilder ID="SqlWhereBuilder1" runat="server" ClientCodeLocation="../JavaScripts/SqlWhereBuilder.js"
FieldsFile="../ConfigFiles/SearchMSDS.config" OperatorListsFile="../ConfigFiles/SearchMSDS.config"
ValueEntryFile="../ConfigFiles/SearchMSDS.config">
</cc1:SqlWhereBuilder>
<br />
<br />
</asp:Panel>
<cc2:CollapsiblePanelExtender ID="pnlAdvSearch_CollapsiblePanelExtender" runat="server"
CollapseControlID="btnAdvSearch" Collapsed="True" Enabled="True" ExpandControlID="btnAdvSearch"
TargetControlID="pnlAdvSearch">
</cc2:CollapsiblePanelExtender>
</td>
<td valign="top">
<asp:Panel ID="pnlStatus" runat="server">
<asp:RadioButtonList ID="rblStatus" runat="server" AppendDataBoundItems="True"
AutoPostBack="True" DataSourceID="SqlDataSource1" DataTextField="DisplayValue"
DataValueField="Value" OnSelectedIndexChanged="RadioButtonList1_SelectedIndexChanged"
RepeatDirection="Horizontal" CellPadding="3" CellSpacing="3"
CausesValidation="True" Visible="True">
<asp:ListItem Selected="True">All</asp:ListItem>
</asp:RadioButtonList>
</asp:Panel>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NCLWebConnectionString %>"
SelectCommand="getOptionList" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:Parameter DefaultValue="msds_Status" Name="ListName" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
<asp:UpdatePanel runat="server" ID="upd2">
<ContentTemplate>
<asp:Button ID="btnExport" runat="server" Text="Export Results"
OnClick="btnExport_Click1" UseSubmitBehavior="False" />
</ContentTemplate>
</asp:UpdatePanel>
</td>
</tr>
</table>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:UpdateProgress ID="UpdateProgress1" runat="server" DisplayAfter="100" DynamicLayout="False">
<ProgressTemplate>
<img src="../images/loading.gif" alt="Loading..." style="text-align: center" />
<asp:Label ID="lblProgress" runat="server"></asp:Label></ProgressTemplate>
</asp:UpdateProgress>
<asp:GridView ID="gridResults" runat="server" DataSourceID="sqlMSDS" OnRowDataBound="GridView1_RowDataBound"
AllowPaging="True" PageSize="25" AllowSorting="True" OnSelectedIndexChanged="gridResults_SelectedIndexChanged"
AutoGenerateColumns="False" EmptyDataText="No matching MSDS Sheets." OnSorted="gridResults_Sorted">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" Visible="false"
ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="ChemicalTitle" HeaderText="ChemicalTitle" SortExpression="ChemicalTitle" />
<asp:BoundField DataField="Manufacturer" HeaderText="Manufacturer" SortExpression="Manufacturer" />
<asp:BoundField DataField="UsageDept" HeaderText="UsageDept" SortExpression="UsageDept" />
<asp:BoundField DataField="Notes" HeaderText="Notes" SortExpression="Notes" />
<asp:BoundField DataField="Health" HeaderText="Health" visible="false" SortExpression="Health" />
<asp:BoundField DataField="Fire" HeaderText="Fire" visible="false" SortExpression="Fire" />
<asp:BoundField DataField="Reactivity" HeaderText="Reactivity" visible="false" SortExpression="Reactivity" />
<asp:BoundField DataField="DateUpdated" HeaderText="DateUpdated" SortExpression="DateUpdated" />
</Columns>
<SelectedRowStyle BackColor="Yellow" />
</asp:GridView>
<asp:SqlDataSource ID="sqlMSDS" OnSelected="sqlMSDS_OnSelected" runat="server" ConnectionString="<%$ ConnectionStrings:NCLWebConnectionString %>"
SelectCommand="SELECT [ID]
,[ChemicalTitle]
,[Manufacturer]
,[UsageDept]
,[Notes]
,[Health]
,[Fire]
,[Reactivity]
,[DateUpdated]
FROM [msds_Sheets]" OnSelecting="sqlMSDS_Selecting"></asp:SqlDataSource>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnSearch" EventName="Click" />
<asp:AsyncPostBackTrigger ControlID="btnRunAdvSearch" EventName="Click" />
<asp:AsyncPostBackTrigger ControlID="rblStatus" EventName="SelectedIndexChanged" />
<asp:AsyncPostBackTrigger ControlID="btnExport" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
<br />
</asp:Content>
And code-behind:
List<String> safeWords = new List<String>();
protected void Page_Load(object sender, EventArgs e)
{
pnlStatus.Visible = User.IsInRole("msds_Admin");
gridResults.DataKeyNames = new String[] { "id" };
txtSimpleSearch.Focus();
if (!IsPostBack)
{
safeWords.Add("delete");
safeWords.Add("insert");
safeWords.Add("update");
safeWords.Add("set");
safeWords.Add("exec");
safeWords.Add("N'");
sqlMSDS.SelectCommand += " Where status = 0 ";
Session["Sql"] = sqlMSDS.SelectCommand;
try
{
Session["OriginalSQL"] = sqlMSDS.SelectCommand.Remove(sqlMSDS.SelectCommand.IndexOf("Where"));
}
catch (Exception)
{
Session["OriginalSQL"] = sqlMSDS.SelectCommand;
}
}
}
protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
{
((Label)UpdateProgress1.FindControl("lblProgress")).Text = "Searching...";
if (btnSearch.Visible)
{
btnSearch_Click(null, null);
if (RadioButtonList1.SelectedValue != "All")
{
sqlMSDS.SelectCommand += " And Status = " + RadioButtonList1.SelectedValue;
}
else
{
//Somehow force the grid to research using no status parameter
sqlMSDS.SelectCommand = Session["Sql"].ToString();
}
}
else
{
btnRunAdvSearch_Click(null, null);
if (RadioButtonList1.SelectedValue != "All")
{
if (sqlMSDS.SelectCommand.Contains("Where"))
{
sqlMSDS.SelectCommand += " And Status = " + RadioButtonList1.SelectedValue;
}
else
{
sqlMSDS.SelectCommand += " Where Status = " + RadioButtonList1.SelectedValue;
}
}
else
{
//Somehow force the grid to research using no status parameter
sqlMSDS.SelectCommand = Session["Sql"].ToString();
}
}
}
Here is what was happening to me and the fix.
I had a radiobuttonlist that was not in an update panel, but defined as a trigger for an update panel. I had onselectedindexchanged defined as well. Radiobuttonlist had the first listitem attribute selected="true", so it would be selected by default on page load. Then selecting the second listitem worked fine, posting back and updating the update panel.
However, selecting the first item again was not firing onselectedindexchanged event. Using Firefox's awesome Inspect Element utility, I was able to determine that the server was generating the html element (checked only on the first, default list item). But since the radiobuttonlist was not in the update panel, the checked="checked" attribute for the second item was never getting written to the browser, even though client-side the second radio button visually appeared to be selected. Therefore, when selecting the original item the second time, the onselectedindexchanged was not firing server-side, because the newly selected index was already indicated as selected in the POST event.
You won't see this problem if the list is inside the panel you want to refresh, because the postback causes the browser to receive "new" elements with the checked="checked" on the newly selected item. The layout of my page made it inconvenient to have these in the same panel, so the fix for me was to put the radiobuttonlist in it's own little update panel. Whichever works for you, the answer is to make sure the radiobuttonlist is in SOME update panel, so the checked attribute can be sent to the browser for each item when selected.
Does this RadioButtonList specified as AsyncPostBackTrigger for another UpdatePanel? If so, check following link: CheckedChanged event not firing on a radio button within UpdatePanel
I have reproduce that behaviour and fix this with the following script:
$(function () {
$("input[type='radio']:first", $("#<%= RadioButtonList1.ClientID %>")).attr("checked", true);
});
if you can't use the jQuery try this javascript:
window.onload = function () {
window.document.getElementById("<%= RadioButtonList1.ClientID %>_0").checked = true;
};
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ClientScript.RegisterStartupScript(this.GetType(), "RadioButtonListDefaultValue", String.Format("window.document.getElementById('{0}_0').checked = true;", RadioButtonList1.ClientID), true);
}
}
As user user2965308 said, if the RadioButtonList is inside of the UpdatePanel this issue doesn't happen.
https://www.codeproject.com/Questions/118042/RadioButtonList-Postback-issue-when-selected-by-co
"Get it inside an update panel, with property "ChildrenAsTriggers" on true. This solve the issue for me."
<asp:ListItem Selected="True">All</asp:ListItem>
Clicking "All" doesn't change the selected index since that item was already selected, so the event does not fire. Picking any other option changes the selected option and causes the event to fire. I believe your goal is to display results for all statuses when you click on "All". You should do one of the following:
Display those results when the page initially loads since "All" is already selected.
Add a "Search" button that initiates the post-back instead of using the radio button's AutoPostBack.
Replace the RadioButtonList with a DropDownList, and give it two initial ListItems: "Pick a Status" - whose value is an empty string, and "All" whose value is "All". The "Pick a Status" dummy entry would look less out of place in a DropDownList than in a RadioButtonList.
Of the options listed above, I would personally prefer the "Search" button, because AutoPostBack annoys me as a user. I hate AutoPostBack DropDownLists that make the web page go bonkers when I accidentally use my mouse wheel when the list has focus.
Related
my scenario: I have more dropdown lists, when you click the dropdown list including with "Other" this word. my textbox enable attribute will be true otherwise it will be false (default). currently, I ran into a problem is I want to use one method to do this. when all dropdown lists was selected, it will call the same function and do the same thing. but I can't (1) Get the current dropdown list ID and even I got the drop-down list id, I cannot change the textbox ENABLE attribute to true. Thanks
.ascx.cs
<asp:Panel ID="Panel1" runat="server">
<div class="formGreyBg">
<div>
<asp:Label ID="panellblS2Heading" runat="server" Font-Size="Larger" Font-Bold="True" CssClass="formHeading"></asp:Label><br />
<asp:Label ID="panellblS2Description" runat="server" Font-Size="Small" CssClass="formDescription"></asp:Label>
</div>
<br />
<br />
<div class="formRow__underline formRow">
<div style="vertical-align: top" class="formRowLabelWrapper">
<asp:Label ID="panellblListedEntity" runat="server" Font-Bold="True" CssClass="formLabel"></asp:Label>
</div>
<div style="vertical-align: top" class="formRowInputWrapper">
<asp:UpdatePanel ID="upPanelddlListedEntity" runat="server" UpdateMode="Conditional" Visible="true"
RenderMode="Inline">
<ContentTemplate>
<asp:DropDownList ID="panelddlListedEntity" runat="server" Width="510" CssClass="formInput"
OnSelectedIndexChanged="panelddlListedEntity_OnSelectedIndexChanged" AutoPostBack="True"></asp:DropDownList><br/><br/>
<asp:TextBox ID="paneltbListedEntity" runat="server" Enabled="false"></asp:TextBox>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="panelddlListedEntity" EventName="SelectedIndexChanged" />
</Triggers>
</asp:UpdatePanel>
</asp:Panel>
Another class:
protected void panelddlListedEntity_OnSelectedIndexChanged(object sender, EventArgs e)
{
//DropDownList dropDownList = (DropDownList)sender;
if (panelddlListedEntity.SelectedValue.Contains("Other"))
{
TextBox textBox = new TextBox();
textBox.ID = dropDownList.ID.ToString().Replace("ddl", "tb");
textBox.Enabled = true;
TextBox control = (TextBox)this.Page.LoadControl(#"~/_CONTROLTEMPLATES/15/FRC.WB/Report/ReportUserControl.ascx").FindControl(dropDownList.ID.ToString().Replace("ddl", "tb"));
//control.Enabled = true;
}
else
paneltbListedEntity.Enabled = false;
}
In my application I am using asp:GridView with download file link for each row. In order to register postback control I am using OnRowDataBound attribute of GridView.
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional" >
...
<asp:GridView ID="folderContentGrid" runat="server" AutoGenerateColumns="False"
width="100%" ShowHeaderWhenEmpty="true" CssClass="table table-hover" OnRowDataBound="bindDownloadAction">
<Columns>
<asp:TemplateField HeaderText="Action" ItemStyle-CssClass="text-center" HeaderStyle-Width="6%">
<ItemTemplate>
<ul class="icons-list hide-if-no-action">
<li class="dropdown">
<i class="icon-menu9"></i>
<ul class="dropdown-menu dropdown-menu-left fl-drp">
<li id="liDownloadBtn" runat="server" visible='<%# Eval("FileType").ToString().Equals("File")%>'>
<asp:LinkButton ID="lnkDownloadBtn" CssClass="block-ui-click" runat="server" data-pid ='<%# Eval("UiIndex") %>'
OnClick="onClickDownloadBtn"><i class="icon-download"></i>Download</asp:LinkButton></li>
<li id="liDeleteFileBtn" runat="server"><asp:LinkButton ID="lnkDeleteFileBtn" runat="server" data-pid ='<%# Eval("UiIndex") %>' data-md-button="btnDeleteFileHdn"
data-md-action="DELETE" data-md-title="Delete File" data-md-message="Do you want to delete {0} '{1}'?"
data-md-message-opt-0='<%# Eval("FileType").ToString().Equals("Folder") ? "folder" : "document" %>' data-md-message-opt-1='<%# Eval("Name") %>'
OnClientClick="return confirmActionModal(this);"><i class="icon-bin"></i>Delete</asp:LinkButton></li>
</ul>
</li>
</ul>
</ItemTemplate>
</asp:TemplateField>
<!-- Other Columns-->
</Columns>
</asp:GridView>
...
</asp:UpdatePanel>
Code behind to register postback on download link
protected void bindDownloadAction(Object sender, GridViewRowEventArgs e)
{
LinkButton lnkDownloadBtn = (LinkButton)e.Row.FindControl("lnkDownloadBtn");
if (lnkDownloadBtn != null)
{
ScriptManager mgr = ScriptManager.GetCurrent(this.Page);
mgr.RegisterPostBackControl(lnkDownloadBtn);
}
}
I have another update panel in master page with timer as below
<asp:UpdatePanel ID="upNotificationAlertUpdatePanel" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:ListView ID="notificationAlertGrid" runat="server">
<LayoutTemplate><ul class="media-list dropdown-content-body width-350 pt-0 blockui-alert-notifications ulNotification"><asp:PlaceHolder ID="itemPlaceholder" runat="server" /></ul></LayoutTemplate>
<ItemTemplate>
<li id="Li5" runat="server" class="media alert-notification">
<div class="media-left cs-media-mini"><span class="btn border-teal text-teal btn-flat cs-media btn-rounded btn-icon btn-sm"><i class='<%# Eval("NotyTypeIcon") %>'></i></span></div>
<div class="media-body">
...
</div>
</li>
</ItemTemplate>
</asp:ListView>
<asp:HiddenField ID="btnCallIntimationPresentHdn" runat="server" Value="" />
<asp:Button ID="btnCallIntimationNotificationAction" class="btn CallIntimationNotificationAction block-ui-click hidden" data-panel="" runat="server" Text=""
OnClick="onClickCallIntimationNotification" ValidationGroup="report" data-pid ="" data-entityrefinfo ="" data-uniqueid ="" data-message=""/>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="RefreshNotificationTimer" EventName="Tick" />
</Triggers>
</asp:UpdatePanel>
<asp:Timer ID="RefreshNotificationTimer" runat="server" Interval="10000" OnTick="autoRefreshNotifications"></asp:Timer>
Problem - When page is loaded first time, download link is working and I am able to download the file. However once timer triggers the tick event, download link does not work and getting below error in browser console.
ScriptResource.axd:885 Uncaught Error: Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed.
at Function.Error$create [as create] (ScriptResource.axd:237)
at Sys$WebForms$PageRequestManager$_createPageRequestManagerParserError [as _createPageRequestManagerParserError] (ScriptResource.axd:665)
at Sys$WebForms$PageRequestManager$_parseDelta [as _parseDelta] (ScriptResource.axd:1435)
at Sys$WebForms$PageRequestManager$_onFormSubmitCompleted [as _onFormSubmitCompleted] (ScriptResource.axd:1314)
at Array.<anonymous> (ScriptResource.axd:47)
at ScriptResource.axd:3484
at Sys$Net$WebRequest$completed [as completed] (ScriptResource.axd:6376)
at XMLHttpRequest.Sys$Net$XMLHttpExecutor._onReadyStateChange (ScriptResource.axd:5996)
NOTE: When I increase the timer interval to 10 seconds to 5 min then I am able to download file till 5 mins.
As per my understanding partial postback call of timer is removing registered postback controls of other updatepanel from scriptmanager despite updatemode is conditional for both.
Any help is really appreciated.
You can try this snippet. It finds the GridView of the nested page and rebinds the PostBack trigger on Timer Tick.
protected void autoRefreshNotifications(object sender, EventArgs e)
{
//find the gridview in the contentplaceholder
GridView gv = ContentPlaceHolder1.FindControl("folderContentGrid") as GridView;
//loop all the rows in the gridview
foreach (GridViewRow row in gv.Rows)
{
//find the linkbutton in the row using findcontrol
LinkButton lnkDownloadBtn = (LinkButton)row.FindControl("lnkDownloadBtn");
if (lnkDownloadBtn != null)
{
//bind the postback trigger to the linkbutton
ScriptManager mgr = ScriptManager.GetCurrent(this.Page);
mgr.RegisterPostBackControl(lnkDownloadBtn);
}
}
}
What also works is placing the binding of folderContentGrid outside the IsPostBack check. Then RowDataBound is calles on every PostBack. But depending on your requirements and other code that could create some problems as well.
I have a anchor tag for the updating the row in the gridview. I have set the checkbox in the gridview. When the user checks the checkbox and click on update button the existing row should open in a pop up..
Right now the pop up is opening but not with the checked rows with the existing data. Please see the code for your reference:-
<a id="popup" onclick="div_show()" class="btn btn-success"><i class="fa fa-plus-circle"></i>Add new</a>
</i>Update
Also see the gridview code for your reference:-
<asp:GridView ID="grdCSRPageData" runat="server" Width="100%" border="1" Style="border: 1px solid #E5E5E5;" CellPadding="3"
AutoGenerateColumns="False" OnDataBound="grdCSRPageData_DataBound" AllowPaging="true" CssClass="hoverTable" EmptyDataText="No Records Found"
OnPageIndexChanging="grdCSRPageData_PageIndexChanging" DataKeyNames="Id" OnRowDeleting="grdCSRPageData_RowDeleting"
PageSize="5" ShowFooter="true" OnRowEditing="grdCSRPageData_RowEditing" OnRowUpdating="grdCSRPageData_RowUpdating"
OnRowCancelingEdit="grdCSRPageData_RowCancelingEdit">
<AlternatingRowStyle CssClass="k-alt" BackColor="#f5f5f5" />
<Columns>
<asp:TemplateField HeaderText="Select" HeaderStyle-Width="5%" HeaderStyle-CssClass="k-grid td">
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" AutoPostBack="false" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="page_title" HeaderText="Page Title" ItemStyle-Width="30" HeaderStyle-CssClass="k-grid td" />
<asp:BoundField DataField="page_description" HeaderText="Page Description" ItemStyle-Width="30" HeaderStyle-CssClass="k-grid td" />
<asp:BoundField DataField="meta_title" HeaderText="Meta Title" ItemStyle-Width="30" HeaderStyle-CssClass="k-grid td" />
<asp:BoundField DataField="meta_keywords" HeaderText="Meta Keywords" ItemStyle-Width="30" HeaderStyle-CssClass="k-grid td" />
<asp:BoundField DataField="meta_description" HeaderText="Meta Description" ItemStyle-Width="30" HeaderStyle-CssClass="k-grid td" />
<asp:BoundField DataField="Active" HeaderText="Active" ItemStyle-Width="30" HeaderStyle-CssClass="k-grid td" />
<asp:TemplateField HeaderText="Action" HeaderStyle-Width="15%" HeaderStyle-CssClass="k-grid td">
<ItemTemplate>
<asp:ImageButton ID="btnDelete" AlternateText="Delete" ImageUrl="~/images/delete.png" runat="server" Width="15" Height="15" CommandName="Delete" CommandArgument='<%# Eval("Id") %>' CausesValidation="false" OnClientClick="return confirm('Are you sure you want to delete this record?')" />
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ButtonType="Image" ItemStyle-Width="15" EditImageUrl="~/images/edit.png" ShowEditButton="True" ControlStyle-Width="15" ControlStyle-Height="15" CancelImageUrl="~/images/close.png" UpdateImageUrl="~/images/update.png">
<ControlStyle Height="20px" Width="20px"></ControlStyle>
</asp:CommandField>
</Columns>
</asp:GridView>
Please help, its been since two days I am stucked but couldn't cracked it.
Code for binding the gridview:-
private void BindGrid()
{
string strQuery = "select Id,page_title,page_description,meta_title,meta_keywords,meta_description,Active from tbl_Pages ORDER By Id DESC";
SqlCommand cmd = new SqlCommand(strQuery);
DataTable dt = GetData(cmd);
grdCSRPageData.DataSource = dt;
grdCSRPageData.DataBind();
}
Also see the Page_load method;-
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}
You can try this using the AjaxControlToolKit.
In your GridView place this event handler:
OnRowCommand="grdCSRPageData_RowCommand"
Place this after your GridView:
<asp:UpdatePanel ID="upModal" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Panel ID="pnlModal" runat="server" BorderWidth="1" Style="display:none;">
<table>
<tr>
<td>page_title</td>
<td><asp:TextBox ID="txtPageTitle" runat="server" /></td>
</tr>
<tr>
<td>page_description</td>
<td><asp:TextBox ID="txtPageDescription" runat="server" /></td>
</tr>
</table>
<asp:Button ID="btnOK" runat="server" Text="OK" />
<asp:Button ID="btnCancel" runat="server" Text="Cancel" />
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
<asp:Button ID="btnModal" runat="server" Style="display:none;"/>
<ajaxToolkit:ModalPopupExtender ID="mpe" runat="server" PopupControlID="pnlModal" TargetControlID="btnModal" OkControlID="btnOK" CancelControlID="btnCancel" />
In code behind:
protected void grdCSRPageData_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Edit")
{
GridViewRow gvRow = grdCSRPageData.Rows[Convert.ToInt32(e.CommandArgument)];
txtPageTitle.Text = gvRow.Cells[0].Text;
txtPageDescription.Text = gvRow.Cells[1].Text;
upModal.Update();
mpe.Show();
}
}
protected void grdCSRPageData_RowEditing(object sender, GridViewEditEventArgs e)
{
grdCSRPageData.EditIndex = -1;
BindGrid();
}
I think you don't need to check which row you want to edit, you already have a CommandField in your GridView. You just click on the edit image and the modal popup gets populated with the data from the GridView (from the row you are editing).
Here is a solution using ajax. When you check a checkbox and click on update button jquery code will look for selected checkbox in gridview and when it finds this will assign values to textboxes which will be in popup.
Also you have to store id in hidden field on the basis of which update query will run or you can use any field on which update will happen.
Now when you click on update button in popup an ajax call will be sent which will take updated values from textboxes and send to webmethod.
In webmethod you will run your update query.And when ajax executes successfully you will empty the values of textboxes in popup and reload the page to see changes in gridview.
Html of popup
<div id="Popup">
<table>
<tr>
<td>
Category
</td>
<td>
<input type="text" id="Category" />
</td>
</tr>
<tr>
<td>
Items
</td>
<td>
<input type="text" id="items" />
</td>
</tr>
<tr>
<td>
<input type="button" value="Update" onclick="Openselected()" />
</td>
<td><input type="hidden" id="hdnID" /></td>
</tr>
</table>
</div>
This is not shown as popup but you can use any plugin to show it in popup like blockui,fancybox jqueryui dialog or any one available.
Jquery Code
This function will assign values of selected row in textboxes and open popup.
function Openselected()
{
$('table[id$=grdTest] tr').each(function () {
if ($(this).find('input[type=checkbox]').is(':checked')) {
$('#Category').val($(this).children('td').eq('02').text());
$('#items').val($(this).children('td').eq('03').text());
$('#hdnID').val($(this).children('td').eq('01').text());
}
});
}
This function will send ajax call with updated values to webmethod and on success empty textboxes of popup and reload page to see changes
function UpdateGrid()
{
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/UpdateDB",
data: JSON.stringify({ category:$('#Category').val() , items: $('#items').val(),id:$('#hdnID').val() }),
dataType: "json",
async: false,
success: function (data) {
$('#Category').val("");
$('#items').val("");
$('#hdnID').val("");
window.location.reload(true);
},
error: function (err) {
alert(err.responseText);
}
});
}
Here is webmethod
[WebMethod]
public static string UpdateDB(string category, string items,int id)
{
//Your logic of updating db.Here i am updating on basis of id you can use any feild of your choice
return "success";
}
This is only for one row as per your requirement.
Check for the rows got selected from gridview in RowDataBound method. Selected rows or in your case check marked rows can be grabed in this method.
Their are lots of references available here.. you can use one
How to check if any row is selected from GridView?
you can take a look at this may be you can use modelpopupextender provided by ajaxcontroltoolkit
go through the ASP.NET How to show AjaxControlToolkit Modal Popup from CheckBox
you can use telerik grid which automatically allow the insertion and editing in form .
<MasterTableView EditMode="PopUp" CommandItemDisplay="Top"><CommandItemSettings ShowAddNewRecordButton="true" ShowRefreshButton="true" />
See Telerik Demo
http://demos.telerik.com/aspnet-ajax/grid/examples/overview/defaultcs.aspx
I have a Datalist on my asp.net page with an ImageButton in the <Item Template>. When an ImageButton is clicked, I use the ItemCommand event to set the border of the data item:
protected void dlProducts_ItemCommand(object source, DataListCommandEventArgs e)
{
e.Item.BorderColor = System.Drawing.ColorTranslator.FromHtml("#ff5800");
e.Item.BackColor = System.Drawing.ColorTranslator.FromHtml("#ffeee5");
}
That works fine, but the border disappears when a postback occurs. I've tried binding my datalist in the page load event like so:
if (!Page.IsPostBack)
{
dlProducts.DataSource = ObjectDataSource4;
dlProducts.DataKeyField = "Product_ID";
dlProducts.DataBind();
}
But the border is gone after a postback. What gives?
Here is the datalist markup:
<asp:DataList ID="dlProducts" runat="server" CellPadding="5" CellSpacing="5"
OnItemCommand="dlProducts_ItemCommand"
RepeatColumns="4" RepeatDirection="Horizontal"
ondatabinding="dlProducts_DataBinding"
onitemdatabound="dlProducts_ItemDataBound" >
<ItemTemplate>
<asp:ImageButton ID="img" ImageAlign="Middle" runat="server"
ImageUrl='<%# "~/uploads/profile/" + DataBinder.Eval(Container.DataItem,"ProfileImageName").ToString() %>'
onclick="img_Click" />
</ItemTemplate>
</asp:DataList><asp:ObjectDataSource ID="ObjectDataSource4" runat="server" SelectMethod="GetAllCompetitorProducts"
TypeName="DalProduct" OldValuesParameterFormatString="original_{0}">
<SelectParameters>
<asp:SessionParameter Name="producttype_id" SessionField="ProductType_id" Type="Int32" DefaultValue="13" />
<asp:SessionParameter DefaultValue="2009" Name="Year" SessionField="Year" Type="Int32" />
</SelectParameters>
</asp:ObjectDataSource>
Try this:
<ItemTemplate>
<div id="divImg" runat="server">
<asp:ImageButton ID="img" ImageAlign="Middle" runat="server"
ImageUrl='<%# "~/uploads/profile/" + DataBinder.Eval(Container.DataItem,"ProfileImageName").ToString() %>'
onclick="img_Click" />
</div>
</ItemTemplate>
In ItemCommand
protected void dlProducts_ItemCommand(object source, DataListCommandEventArgs e)
{
var divImg = (HtmlGenericControl)e.Item.FindControl("divImg");
divImg.Style.Add("background-color", "#ffeee5");
}
As you can see, img control is now wrapped in a server div element so that when postback occurs it automatically restores its state from viewstate. Being said that, it works fine with postback but if you rebind your grid, it would lose its style. For it to persist after the re-bind, on itemcommand store the id's of the img in viewstate and apply the style according.
Also, I would suggest using class attribute for div element instead of applying colors in code-behind.
divImg.Attributes.Add("class", "classnamewhichhasgroundandbordercolor");
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.