Dropdownlist inside Updatepanel not passing selected item - c#

I have a Gridview that has a hide/show panel. Inside the Panel there is a dropdown and a button. On button press I need the selected value of the dropdown, but I keep getting the first item, no matted what is selected.
I have been investigating the issue and it is to do with the panel control. If I place the dropdown outside the panel, everything works as intended. But dropdown only passes the first value when inside the panel.
Here is my code:
ASP Code
<%# Page Language="C#" AutoEventWireup="true" CodeFile="DD.aspx.cs" Inherits="DD" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" />
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<title></title>
<script type="text/javascript">
$(document).on("click", '[src*=plus]', function () {
$(this).closest("tr").after("<tr><td></td><td colspan = '999'>" + $(this).next().html() + "</td></tr>")
$(this).attr("src", "images/minus.png");
});
$(document).on("click", '[src*=minus]', function () {
$(this).attr("src", "images/plus.png");
$(this).closest("tr").next().remove();
})
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager runat="server"></asp:ScriptManager>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:constr %>" SelectCommand="SELECT * FROM [Requests]"></asp:SqlDataSource>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:constr %>" SelectCommand="SELECT [Name] FROM [Staff]"></asp:SqlDataSource>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="RequestID" DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="RequestID" HeaderText="RequestID" InsertVisible="False" ReadOnly="True" SortExpression="RequestID" />
<asp:TemplateField>
<ItemTemplate>
<img runat="server" style="cursor: pointer" src="images/plus.png" />
<asp:UpdatePanel ID="pnlOrders" runat="server" Style="display: none" UpdateMode="Conditional">
<ContentTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDataSource2" DataTextField="Name" DataValueField="Name" AutoPostBack="true">
</asp:DropDownList>
<asp:Button runat="server" ID="test" OnClick="test_Click" />
</ContentTemplate> </asp:UpdatePanel>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</form>
</body>
</html>
C# Code
protected void test_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
GridViewRow gvr = (GridViewRow)btn.NamingContainer;
DropDownList referalDD = gvr.FindControl("DD1") as DropDownList;
string www = referalDD.SelectedItem.Text;
string qqq = referalDD.SelectedItem.Value;
}
Can anyone help me to solve this issue

Ok so I have found a work around / solution. Thanks to Niko for the placeholder suggestion. I got rid of this code:
<img runat="server" style="cursor: pointer" src="images/plus.png" />
and the related Jquery
$(document).on("click", '[src*=plus]', function () {
$(this).closest("tr").after("<tr><td></td><td colspan = '999'>" + $(this).next().html() + "</td></tr>")
$(this).attr("src", "images/minus.png");
});
$(document).on("click", '[src*=minus]', function () {
$(this).attr("src", "images/plus.png");
$(this).closest("tr").next().remove();
})
Added a placeholder around the updatepanel and a Image button
<asp:ImageButton runat="server" ID="ShowHide" ImageUrl="~/images/plus.png" OnClick="ShowHide_Click" />
<asp:PlaceHolder ID="PlaceHolder1" runat="server" Visible="false">
And this code for the button click event.
protected void ShowHide_Click(object sender, EventArgs e)
{
ImageButton btn = (ImageButton)sender;
GridViewRow gvr = (GridViewRow)btn.NamingContainer;
PlaceHolder ph = gvr.FindControl("PlaceHolder1") as PlaceHolder;
if (btn.ImageUrl.ToString() == "~/images/plus.png")
{
ph.Visible = true;
btn.ImageUrl = "~/images/minus.png";
}
else
{
ph.Visible = false;
btn.ImageUrl = "~/images/plus.png";
}
}
Note: After further testing the whole issue was to do with UpdatePanel having this code Style="display: none" As soon as I removed this, everything worked. But I added the placeholder for by show/Hide feature.

Related

Update UI controls outside the updatepanel in asp.net

I'm trying to update controls outisde the update panel with the ref. of below link . but its not working. i want to know what i'm missing.in my application can't use these labels inside the update panel.
http://msdn.microsoft.com/en-us/library/bb301423(v=vs.110).aspx
HTML
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="Updatepaneltest._Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<script type="text/javascript" language="javascript">
Sys.WebForms.PageRequestManager.getInstance().add_pageLoading(PageLoadingHandler);
function PageLoadingHandler(sender, args) {
var dataItems = args.get_dataItems();
if ($get('Label1') !== null)
$get('Label1').innerHTML = dataItems['Label1'];
if ($get('Label2') !== null)
$get('Label2').innerHTML = dataItems['Label2'];
}
</script>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
UpdatePanel content.
<asp:Button ID="Button1" Text="Submit" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
<hr />
<asp:Label ID="Label1" Text="hiii" runat="server" /> <br />
<asp:Label ID="Label2" runat="server" />
</div>
</asp:Content>
code behind
protected void Page_Load(object sender, EventArgs e)
{
// ScriptManager ScriptManager1 = ScriptManager.GetCurrent(this.Page);
if (ScriptManager.GetCurrent(this.Page).IsInAsyncPostBack)
{
ScriptManager1.RegisterDataItem(Label1, DateTime.Now.ToString());
ScriptManager1.RegisterDataItem(Label2, DateTime.Now.Year.ToString());
}
}
Control updates inside of updatepanel,
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Button ID="Button1" Text="Submit" runat="server" />
<asp:Label ID="Label1" Text="hiii" runat="server" /> <br />
<asp:Label ID="Label2" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
Control updates outside of updatepanel,
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode=Conditional>
<ContentTemplate>
<asp:Button ID="Button1" Text="Submit" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
<asp:Label ID="Label1" Text="hiii" runat="server" /> <br />
<asp:Label ID="Label2" runat="server" />
Later, write below lines in client side.
var pageInstance = Sys.WebForms.PageRequestManager.getInstance();
pageInstance.add_pageLoaded(UpdateLabelHandler);
function UpdateLabelHandler(sender, args)
{
var ControldataItems = args.get_dataItems();
if ($get('Label1') !== null)
$get('Label1').innerHTML = ControldataItems ['Label1'];
if ($get('Label2') !== null)
$get('Label2').innerHTML = ControldataItems ['Label2'];
}
Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
ScriptManager1.RegisterDataItem(Label1, DateTime.Now.ToString());
ScriptManager1.RegisterDataItem(Label2, DateTime.Now.Year.ToString());
}
Hope this may help you.

Only allow one checkbox to be selected in gridview within modalpopup

I have a modal popup that has a gridview, this gridview has a number of rows, I only want the user to be able to select one row. So if they select another it will deselect the previous one.
I have tried a number of methods but can't get the oncheckedchanged event to fire.
Please can someone assist
Cheers
<asp:button id="btnShowPopupOW" style="display: none" runat="server" />
<asp:modalpopupextender id="mpeOW" behaviorid="mpeOW" runat="server" targetcontrolid="btnShowPopupOW"
popupcontrolid="pnlpopupOW" cancelcontrolid="imgOWCancel" backgroundcssclass="modalBackground" />
<asp:panel id="pnlpopupOW" runat="server" width="600px" style="display: none;" class="ModalPanel">
<div style="position: relative; min-height: 490px;">
<asp:UpdatePanel ID="upExisting" runat="server" ChildrenAsTriggers="true">
<ContentTemplate>
<table style="width: 600px;">
<tr height="25px">
<td>
<asp:Panel ID="pnlPrev" runat="server" Height="200px" ScrollBars="Auto" HorizontalAlign="Center">
<asp:GridView ID="grdPrevious" runat="server" ClientIDMode="Static" AutoGenerateColumns="false" Width="100%"
ShowFooter="false" ShowHeaderWhenEmpty="false" DataKeyNames="ID" >
<Columns>
<asp:BoundField DataField="dates" HeaderText="Dates" />
<asp:BoundField DataField="Prev" HeaderText="Previous" />
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="ChkSelect" runat="server" OnCheckedChanged="ChkSelect_OnCheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</asp:Panel>
</td>
</tr>
</table>
</ContentTemplate>
<Triggers>
</Triggers>
</asp:UpdatePanel>
</div>
</asp:panel>
with the following in the codebehind
protected void ChkSelect_OnCheckedChanged(object sender, EventArgs e)
{
CheckBox activeCheckBox = sender as CheckBox;
foreach (GridViewRow rw in grdPrevious.Rows)
{
CheckBox chkBx = (CheckBox)rw.FindControl("ChkSelect");
if (chkBx != activeCheckBox)
{
chkBx.Checked = false;
}
else
{
chkBx.Checked = true;
}
}
}
You can do it like this. With single check box selection using jquery....
<ItemTemplate>
<asp:CheckBox ID="ChkSelect" runat="server" onclick="CheckOne(this)" />
</ItemTemplate>
function CheckOne(obj) {
var grid = obj.parentNode.parentNode.parentNode;
var inputs = grid.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == "checkbox") {
if (obj.checked && inputs[i] != obj && inputs[i].checked) {
inputs[i].checked = false;
}
}
}
}
you want to a single checked in check box . i think Using this you will be able to select only one check box at a time. Put the following java script code in the head section of the web page
<script type="text/javascript">
function SingleCheckboxCheck(ob)
{
var gridvalue = ob.parentNode.parentNode.parentNode;
var inputs = gridvalue.getElementsByTagName("input");
for(var i=0;i<inputs.length;i++)
{
if (inputs[i].type =="checkbox")
{
if(ob.checked && inputs[i] != ob && inputs[i].checked)
{
inputs[i].checked = false;
}
}
}
}
</script>
Here checkbox as a TemplateField of the GridView inside just call the above javascript function to make it single checkable.
onclick ="SingleCheckboxCheck(this)"
What you need is probably a (RadioButton)[http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.radiobutton(v=vs.110).aspx] instead of a CheckBox.
You can group the RadioButton's together which then allows the user to only select one item and automatically deselects the previous selected - or: exactly the behavior you want for your application.
This example code is taken from the linked MSDN Documentation. Note the GroupName attribute
<%# Page Language="C#" AutoEventWireup="True" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>RadioButton Example</title>
<script language="C#" runat="server">
void SubmitBtn_Click(Object Sender, EventArgs e) {
if (Radio1.Checked) {
Label1.Text = "You selected " + Radio1.Text;
}
else if (Radio2.Checked) {
Label1.Text = "You selected " + Radio2.Text;
}
else if (Radio3.Checked) {
Label1.Text = "You selected " + Radio3.Text;
}
}
</script>
</head>
<body>
<h3>RadioButton Example</h3>
<form id="form1" runat="server">
<h4>Select the type of installation you want to perform:</h4>
<asp:RadioButton id="Radio1" Text="Typical" Checked="True" GroupName="RadioGroup1" runat="server" />
<br />
This option installs the features most typically used. <i>Requires 1.2 MB disk space.</i><br />
<asp:RadioButton id="Radio2" Text="Compact" GroupName="RadioGroup1" runat="server"/>
<br />
This option installs the minimum files required to run the product. <i>Requires 350 KB disk space.</i>
<br />
<asp:RadioButton id="Radio3" runat="server" Text="Full" GroupName="RadioGroup1" />
<br />
This option installs all features for the product. <i>Requires 4.3 MB disk space.</i>
<br />
<asp:button text="Submit" OnClick="SubmitBtn_Click" runat="server"/>
<asp:Label id="Label1" font-bold="true" runat="server" />
</form>

How to get values from GridView in jQuery Dialog in C#

There is a jQuery Dialog with a GridView inside it in my aspx page. also have a button as Save on jQuery Dialog. I need to get values in GridView after click on this button in C#. I have tried as below. But not worked. I changed value in TextBox and click Save button. But it is not gave me edited value. nothing returned.
ASPX Page
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
/* Java scripts and style sheets are here */
<script type="text/javascript">
function showDialog() {
$('#dialogDiv').dialog('open');
}
$(document).ready(function () {
$('#dialogDiv').dialog({
autoOpen: false,
resizable: true,
width: 300,
height: 'auto',
buttons: {
"Save": function () {
$('#' + '<%= btnSaveType.ClientID %>').trigger("click");
}
}
});
});
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>
<div id="dialogDiv" title="Type" style="overflow: hidden">
<div id="TypeDiv" class="divTable">
<div class="divRow">
<div class="divColumn">
<div>
<asp:UpdatePanel runat="server" ID="UpdatePanel1" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="open" EventName="Click" />
</Triggers>
<ContentTemplate>
<asp:GridView ID="Type_GV" runat="server" ShowFooter="True" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="Type">
<ItemTemplate>
<asp:TextBox ID="txtType" runat="server" Text='<%# Bind("Type") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</div>
</div>
</div>
</div>
<asp:Button ID="open" runat="server" Text="Open dialog" OnClick="open_Clicked" OnClientClick="showDialog()" />
<br />
<p>
<asp:Button ID="btnSaveType" runat="server" OnClick="btnSaveType_Clicked" Style="visibility: hidden;
display: none;" />
</p>
</asp:Content>
Code Behind
protected void Page_Load(object sender, EventArgs e)
{
}
protected void open_Clicked(object sender, EventArgs e)
{
VehicleType vTypeObject = new VehicleType();
Type_GV.DataSource = vTypeObject.GetTypeList();
Type_GV.DataBind();
}
protected void btnSaveType_Clicked(object sender, EventArgs e)
{
foreach (GridViewRow gvr in Type_GV.Rows)
{
TextBox type = (TextBox)gvr.FindControl("txtType");
Debug.WriteLine("type : " + type.Text);
// when debug, print as type :
// nothing print for type.Text
}
}
}
public class VehicleType
{
public string Type { get; set; }
public List<VehicleType> GetTypeList()
{
List<VehicleType> list = new List<VehicleType>()
{
new VehicleType{Type="Type1"}
};
return list;
}
}
How can i solve this ?

Calling C# getter from UpdatePanel / javascript - never get updated data

I have this property in my code-behind.
public string LocationOptions
{
get { return Session["LocationOptions"].ToString(); }
set { Session["LocationOptions"] = value; }
}
On the front-end, I have this javascript.
<script type="text/javascript">
function pageLoad(sender, args) {
InitLocationsAutoComplete();
}
</script>
<asp:UpdatePanel ID="upScript" runat="server">
<ContentTemplate>
<script type="text/javascript">
function InitLocationsAutoComplete() {
var locationsJson = '<%= LocationOptions %>';
alert(locationsJson);
}
</script>
</ContentTemplate>
</asp:UpdatePanel>
I'm setting a breakpoint on my getter and setter in the C# code.
I'm using MVP and the setter gets called from a presenter.
On first page load, things work as expected. The breakpoint on the setter gets hit first. Then the breakpoint on the getter. Finally, I get a javascript alert with the value I expect to see.
I'm running into problems on partial postbacks that are triggered by other update panels. On those, my setter breakpoint hits with a new value. My getter breakpoint gets hit next, and if I quick watch Session["LocationOptions"] I see the new value there. But when I get the javascript alert, it still alerts the initial value from the first page load.
If it still calls the property in C#, then I don't see why the updated value doesn't come through to the javascript. Why am I stuck with the initial value from first page load?
As far as I know, javascript in the partially updated content is not re-executed/re-evaluated. My understanding is that the partial update will essentially edit the DOM to update a part of the page, but this does not allow one to dynamically upate javascript on the page. You can use ScriptManager.RegisterClientScriptBlock on the server-side to register your updated javascript during the partial postback.
I've had the same issue in the past.
The issue is due to the fact that the dom is only partially updated, i've personally corrected this by registering the script in the ScriptManager.
An example of this is here: ScriptManager.RegisterClientScriptBlock Method (Control, Type, String, String, Boolean)
<%# Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void Page_PreRender(object sender, EventArgs e)
{
string script = #"
function ToggleItem(id)
{
var elem = $get('div'+id);
if (elem)
{
if (elem.style.display != 'block')
{
elem.style.display = 'block';
elem.style.visibility = 'visible';
}
else
{
elem.style.display = 'none';
elem.style.visibility = 'hidden';
}
}
}
";
ScriptManager.RegisterClientScriptBlock(
this,
typeof(Page),
"ToggleScript",
script,
true);
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>ScriptManager RegisterClientScriptInclude</title>
</head>
<body>
<form id="Form1" runat="server">
<div>
<br />
<asp:ScriptManager ID="ScriptManager1"
EnablePartialRendering="true"
runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1"
UpdateMode="Conditional"
runat="server">
<ContentTemplate>
<asp:XmlDataSource ID="XmlDataSource1"
DataFile="~/App_Data/Contacts.xml"
XPath="Contacts/Contact"
runat="server"/>
<asp:DataList ID="DataList1" DataSourceID="XmlDataSource1"
BackColor="White" BorderColor="#E7E7FF" BorderStyle="None"
BorderWidth="1px" CellPadding="3" GridLines="Horizontal"
runat="server">
<ItemTemplate>
<div style="font-size:larger; font-weight:bold; cursor:pointer;"
onclick='ToggleItem(<%# Eval("ID") %>);'>
<span><%# Eval("Name") %></span>
</div>
<div id='div<%# Eval("ID") %>'
style="display: block; visibility: visible;">
<span><%# Eval("Company") %></span>
<br />
<a href='<%# Eval("URL") %>'
target="_blank"
title='<%# Eval("Name", "Link to the {0} Web site") %>'>
<%# Eval("URL") %></a>
</asp:LinkButton>
<hr />
</div>
</ItemTemplate>
<FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" />
<SelectedItemStyle BackColor="#738A9C" Font-Bold="True" ForeColor="#F7F7F7" />
<AlternatingItemStyle BackColor="#F7F7F7" />
<ItemStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" />
<HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#F7F7F7" />
</asp:DataList>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
i hope this helps.

Asp.net buttons inside control inside gridview not working

I need to display a list of clients, but display them differently based on a parameter.
To do this, I have a gridvew, and inside there is a user control. That control has an "if" based on the type.
My problems:
If I add a button inside the control, when it is pressed I get a button validation error.
If I disable validation errors (enableEventValidation="false"), I get button commands to work, but I'm not able to change values on the control either with full postbacks or an updatepanel.
<asp:GridView ID="gvClients" runat="server" AutoGenerateColumns="False" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<xxx:ClientListGridItem ID="ClientListItem1" runat="server" Client='<%# ((Client) Container.DataItem) %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
ClientListGridItem.ascx :
<% if (Client.Style >= 100)
{
%>
<div class="ClientListItem1">
...
<%
}
else
{
%>
<div class="ClientListItem2">
<asp:Button ID="Button2" runat="server" onclick="Button1_Click" Text="Button" />
...
<%
}
%>
I'm sure there is prettier, more object oriented way to do this too...
Changing ClientListGridItem.ascx into:
<asp:Panel id="Div1" CssClass="ClientListItem1" runat="server">
...
</asp:Panel>
<asp:Panel id="Div2" CssClass="ClientListItem2" runat="server">
<asp:Button ID="Button2" runat="server" onclick="Button1_Click" CausesValidation="false" Text="Button" />
..
</asp:Panel>
<script runat="server">
override void OnDataBinding(EventArgs e) {
Div1.Visible = Client.Style >= 100;
Div2.Visible = ! Div1.Visible;
}
</script>
should work.

Categories

Resources