Get selected Row in a pop up for Edit and Update - c#

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

Related

How to disable checkbox inside gridview?

Hi I am developing one application. I have one multiselect dropdownlist box. Whenever i select one value in dropdownlistbox corresponding value in gridview will be having checkbox in below gridview. I want to disable that checkbox. I am basically mvc developer and finding hard times to fix this. I am trying my level best to fix this. For example, whever i select some value in dropdown I am getting ID using jquery as below.
<script>
$(function() {
$('.limitedNumbSelect2').change(function (e) {
var selected = $(e.target).val();
});
});
This is my gridview.
<asp:GridView ID="gdvRegretletter" CssClass="tableform" runat="server" AutoGenerateColumns="False" DataKeyNames="Vendor_ID"
EmptyDataText="No records found !" ShowHeaderWhenEmpty="true" AllowPaging="true" OnPageIndexChanging="gdvRegretletter_PageIndexChanging">
<Columns>
<asp:TemplateField ShowHeader="true" HeaderText="Select All">
<HeaderTemplate>
<asp:CheckBox ID="checkAll" runat="server" Text="Check All" onclick="checkAll(this);" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkselect" runat="server" onclick="Check_Click(this)" />
<asp:HiddenField ID="id" runat="server" Value='<%#Eval("Vendor_ID")%>' />
</ItemTemplate>
<HeaderStyle Width="8%" />
<ItemStyle VerticalAlign="Top" Width="8%" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Username">
<ItemTemplate>
<asp:Label ID="lblUsername" runat="server" Text='<%#Eval("Username") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%#Eval("Name") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Email Id">
<ItemTemplate>
<asp:Label ID="lblEmail" runat="server" Text='<%#Eval("Email") %>' />
</ItemTemplate>
</asp:TemplateField>
</asp:GridView>
Whenecer i select some value from multiselect dropdownlist box I get id in a variable selected. As soon as I get ID in a variable selected i want to disable that checkbox in gridview. May i have some suggestions on this! Thank you all
Furthur i tried as below.
This is jquery code to hide checkbox
$('.limitedNumbSelect2').change(function (e) {
selected = $(e.target).val();
`$(".disablechk[Text='selected']").prop("disabled", true);`
This is my checkbox code inside gridview.
<asp:CheckBox ID="chkselect" runat="server" onclick="Check_Click(this)" Text='<%#Eval("Vendor_ID")%>' class="disablechk"/>
I am trying to do whenever i get some value from dropdown slected i want to disable that particular checkbox.
If you are getting comma separated string then split it and make an array
var temp = new Array();
temp = selected.split(",");
then loop through it
$.each(temp, function( index, value ) {
$(".disablechk[Text='" + value + "']").prop("disabled", true);
});
You can loop the GridView HiddenField values and disable the checkbox accordingly.
<script type="text/javascript">
$(function() {
$('.limitedNumbSelect2').change(function (e) {
checkGridView($(e.target).val());
});
});
function checkGridView(selected) {
$('#<%= gdvRegretletter.ClientID %> input[type="hidden"]').each(function () {
if ($(this).val() == selected) {
var checkbox = $(this).prev();
checkbox.prop("disabled", true);
}
});
}
</script>

How to download a pdf from a panel in an update panel

I have a site that uses master pages.
One of my content pages is basically a large UpdatePanel. Inside that UpdatePanel is a regular Panel. Inside the regular Panel is a Gridview. Inside the Gridview is a Linkbutton that points to a pdf stored in my database.
When I click the Linkbutton to retrieve the pdf, nothing happens.
I have this working on another page that has no UpdatePanel.
I have already tried firing an 'external' button from the Linkbutton and registering this button as a PostBack event. The page posts back when I click the Linkbutton but the pdf is not being sent to the user.
Here is some sample code:
<asp:UpdatePanel ID="UpdatePanelClaims" runat="server">
<ContentTemplate>
<asp:Panel ID="upClaimAttachment" runat="server" Visible="false" >
<table id="gridClaimAttachmentTable" runat="server" class="table" >
<tr>
<td >
<asp:GridView ID="grdClaimAttachment" runat="server" AllowPaging="True" AllowSorting="True"
AutoGenerateColumns="False" CssClass="table table-striped table-bordered table-condensed table-hover" EmptyDataText="No Attachments for this Claim."
EnableTheming="False" onpageindexchanging="grdClaimAttachment_PageIndexChanging" PageSize="15" OnRowCommand="grdClaimAttachment_RowCommand"
OnRowDataBound="grdClaimAttachment_RowDataBound" >
<PagerStyle CssClass="bs-pagination" />
<AlternatingRowStyle CssClass="alternateColor" />
<RowStyle CssClass="rowsStyle" />
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" ItemStyle-CssClass="hideColumn" HeaderStyle-CssClass="hideColumn" >
<HeaderStyle HorizontalAlign="Left" />
<ItemStyle HorizontalAlign="Right" />
</asp:BoundField>
<asp:TemplateField HeaderText="File Name">
<ItemTemplate>
<asp:LinkButton ID="btnViewAttachment" Text='<%#Eval("FileName") %>' CommandName="ViewAttachment"
CommandArgument="<%# Container.DataItemIndex %>" runat="server"></asp:LinkButton></ItemTemplate>
</asp:TemplateField>
<asp:ButtonField ButtonType="Button" CommandName="btnDelete" Text="Delete">
<ControlStyle CssClass="btn btn-info btn-xs " />
</asp:ButtonField>
</Columns>
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>
</td>
</tr>
<tr >
<td>
<div class="container">
<div class="form-group form-group-sm form-groupNoSpace">
<div class="row">
<div class=" col-xs-4 col-xs-offset-4 text-right">
<asp:Button ID="btnClaimAttachmentAdd" runat="server" CssClass="btn btn-primary btn-sm btn-block" Text="Add Attachment" OnClick="btnClaimAttachmentAdd_Click"/>
</div>
</div>
</div>
</div>
</td>
</tr>
</table>
</asp:Panel> <%-- Attachment Update Panel --%>
<asp:Button ID="btnClickMe" runat="server" OnClick="btnClickMe_Click" Visible="false" />
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="btnClickMe" />
</Triggers>
</asp:UpdatePanel> <%-- UpdatePanelClaims --%>
In the code behind I have this:
protected void btnClickMe_Click(object sender, EventArgs e, ClaimAttachment objAttachment)
{
ViewAttachment(objAttachment);
}
private void ViewAttachment(ClaimAttachment objAttachment)
{
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/pdf";
Response.AppendHeader("content-disposition", "attachment;filename=" + objAttachment.FileName);
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite(objAttachment.Attachment);
Response.Flush();
Response.End();
}
UPDATE: Forgot some critical code!
protected void grdClaimAttachment_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
int index = Convert.ToInt32(e.CommandArgument);
if (index >= grdClaimAttachment.Rows.Count)
return;
int IDkey = Convert.ToInt32(grdClaimAttachment.Rows[index].Cells[0].Text);
ClaimAttachment objClaimAttachment = ClaimAttachment.RetrieveById((string)Session["Username"], IDkey);
if (e.CommandName == "btnDelete")
{
ltlDeleteID.Text = IDkey.ToString();
ltlRecordType.Text = "attachment";
confirmDialog(string.Format("DELETE Attachment: {0} ?", objClaimAttachment.FileName));
}
else if (e.CommandName == "ViewAttachment")
{
//btnClickMe.CommandArgument = IDkey.ToString();
//btnClickMe_Click(sender, e);
btnClickMe.Click += new EventHandler((s1, e1) => btnClickMe_Click(s1, e1, objClaimAttachment));
btnClickMe_Click(sender, e, objClaimAttachment);
}
}
catch (BLException be)
{
errDialog(be.Message);
}
}
The Linkbutton in the grid is actually calling the Click event of an external button to perform the pdf download...
What am I missing?? Like I said, this works if I remove all UpdatePanels but I need them for other things...
thx!
The PostBackTrigger class is key to your solution, as it can be used to trigger the full page reload required for the download reponse to work. Downloads simply will not work from a partial postback.
However, as the buttons that should trigger the postback are inside your grid, using a single PostBackTrigger in the page markup is not enough, you need a specific trigger for each button / row.
Use something like this (call it from your Page_Load)
private void RegisterPostBackControls()
{
foreach (GridViewRow row in grdClaimAttachment.Rows)
{
LinkButton button = row.FindControl("btnViewAttachment") as LinkButton;
ScriptManager.GetCurrent(this).RegisterPostBackControl(button);
}
}

Check a checkbox of a gridview using jquery

I have a gridview with two check box columns. One is for selection and the other for setting a property something like "add to favorite". This gridview is loaded code behind and the check boxes are defined inside Item Template. The problem is that it is not very user friendly to have someone check two boxes for the same row, when they could have just selected "add to favorite" and this should automatically check the selection check box too. I understand this could be easily done using jquery as I do not think making a postback for these selections is a good user experience. I am very new to jquery and so any help would be appreciated.
The checkboxes on the same row follow the same convention for id, so if select is cbSelect_0, the other one will be cbfavorite_0. I also gave all the cbFavorite checkboxes the same class "cbMul" and then I wrote a function
function checkUncheck() {
$(".cbMul").checked(function() {
if ( $(this).attr('checked')) {
$('#myCheckbox').attr('checked', false);
} else {
$('#myCheckbox').attr('checked', 'checked');
}
});
}
Now, I do not understand how do I get the attributes of the checkbox that was checked, replace the the name and get the id of the checkbox if select and then check that one?
Here is the gridview:
<asp:GridView ID="gvEnvironments" EmptyDataText="--- No Data ---" runat="server" AutoGenerateColumns="false"
DataKeyNames="Id" >
<Columns>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="cbSelectEnvironments" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Id" HeaderText="ID" InsertVisible="false" ReadOnly="true" SortExpression="Id" />
<asp:TemplateField HeaderText="Multi">
<ItemTemplate>
<asp:CheckBox ID="cbFav" runat="server" Checked="false" CssClass="cbMul" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="Description" HeaderText="Description" HeaderStyle-Width="300px" SortExpression="Description" />
</Columns>
Here is a fiddle: http://jsfiddle.net/FyDEk/
HTML:
<table>
<tr>
<td>
<input class="cb1" type="checkbox" />
</td>
<td>
<div id="dd">text</div>
</td>
<td>
<input class="cb2" type="checkbox" />
</td>
</tr>
</table>
JS:
$(function () {
$(".cb2").on("change", function () {
var cb = $(this),
cbIsChecked = cb.is(":checked"),
cbPrev = cb.parent().parent().find(".cb1");
if(cbIsChecked)
cbPrev.prop("checked", true);
else
cbPrev.prop("checked", false);
});
});
Add appropriate classes to your CheckBoxes.

Remove individual rows of a grid view only on the client side

I have a drop down list. On changing the index of the dropdownlist , I populate an asp.net gridview.
I have a requirement where the user should be able to remove individual rows of the gridview on the screen .
At the end of each row, I intend to have a remove button. On clicking the button the row should
disappear . But this should be only on the screen. There should be no changes done in the database.
I have my code below right now :
aspx
<table>
<tr>
<td>
<div>
<asp:Label ID="lblClient" runat="server" Text="Client :" CssClass="label" ForeColor="Black"></asp:Label>
<asp:DropDownList ID="ddlClient" runat="server" AppendDataBoundItems="true" AutoPostBack="true" OnSelectedIndexChanged="ddlClient_SelectedIndexChanged">
<asp:ListItem Text="ALL" Value="0"></asp:ListItem>
</asp:DropDownList>
</div>
</td>
</tr>
<tr>
<td>
<asp:GridView ID="gvMainLog" runat="server" Visible="true" AllowSorting="True" AutoGenerateColumns="False"AllowPaging="true">
<Columns>
<asp:BoundField DataField="Instruction" HeaderText="Instruction" />
<asp:BoundField DataField="ProviderId" HeaderText="Id" />
</Columns>
</asp:GridView>
<div>
<asp:TextBox ID="txtEditMin" runat="server"></asp:TextBox>
</div>
</td>
</tr>
</table>
aspx.cs
protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
gvMainLog.DataSource = GetSetupUtility(1);
gvMainLog.DataBind();
}
In the GridView add the remove command like this
<Columns>
<asp:BoundField DataField="Instruction" HeaderText="Instruction" />
<asp:BoundField DataField="ProviderId" HeaderText="Id" />
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:Button ID="Button1" runat="server" CausesValidation="false" CommandName="Remove"
Text="Remove" CommandArgument='<%# Eval("id") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
In the action of the remove button use the DeleteRow method
void gvMainLog_RowCommand(Object sender, GridViewCommandEventArgs e)
{
if(e.CommandName=="Remove")
{
var id = Int32.Parse(e.CommandArgument);
gvMainLog.DeleteRow(id);
}
}
You need somthing like this:
Use TemplateField in gridview.
<script>
function deleteRow(rowId) {
$("#" + rowId).remove();
}
</script>
<asp:GridView ID="GridView1" runat="server" EnableModelValidation="True">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<div id='<%# "myRow" + Container.DataItemIndex %>'> contents <img src="deleteImageUrl" onclick='<%# "deleteRow(\"myRow" + Container.DataItemIndex+"\")" %>'/> </div>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

Radiobuttonlist event not always firing

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.

Categories