Only allow one checkbox to be selected in gridview within modalpopup - c#

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>

Related

Dropdownlist inside Updatepanel not passing selected item

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.

asp ModalPopupExtender is getting closed when page is getting postback

I am using asp ModalPopupExtender to display a treeview in asp.net page. When I click a button a ModalPopupExtender will be raised and loads the treeview with checkbox( loading treeview is a usercontrol ascx). In that usercontrol I have written some server side code for when I check a parent node all the child nodes should be checked. Fot this my page will get postback. My problem is when my page gets post back my ModalPopupExtender is getting off and on and my functions are working fine.
here is my treeview in ascx page
<asp:TreeView ID="tvFolderSelect" runat="server" RootNodeStyle-ForeColor="Black"
CssClass="foldertree" LeafNodeStyle-ForeColor="Black" LeafNodeStyle-Font-Bold="false"
ParentNodeStyle-ForeColor="Black" Width="100%" Style="margin: 3px 0 0 -16px;"
OnTreeNodePopulate="tvFolderSelect_TreeNodePopulate" OnTreeNodeCheckChanged="tvFolderSelect_TreeNodeCheckChanged" onclick="postbackOnCheck(event);"
ShowCheckBoxes="All" >
<LeafNodeStyle Font-Bold="False" ForeColor="Black" CssClass="foldertreeleafnode"
ImageUrl="~/images/img_dms/sm_fldr.png" />
<ParentNodeStyle Font-Italic="True" ImageUrl="~/images/img_dms/sm_fldr.png" Font-Underline="True"
CssClass="foldertreeparentnode"/>
<NodeStyle Font-Names="Tahoma" Font-Size="8pt" ForeColor="Black" HorizontalPadding="0px"
NodeSpacing="0px" VerticalPadding="0px" />
<RootNodeStyle ForeColor="Black" CssClass="foldertreerootnode" />
<SelectedNodeStyle Font-Underline="False" HorizontalPadding="0px" VerticalPadding="0px" />
</asp:TreeView>
and here is the javascript function to get postback
function postbackOnCheck(e) {
var evt = e || window.event;
var o = evt.target || evt.srcElement;
if (o.tagName == 'INPUT' && o.type == 'checkbox' && o.name != null && o.name.indexOf('CheckBox') > -1) {
__doPostBack("", "");
}
}
Here is I am using the control
<img id="AddActivity" runat="server" src="../images/plus1.gif" alt="" style="text-align: right;
cursor: pointer; float: right; padding: 1%;" />
<asp:ModalPopupExtender ID="MPEACT" runat="server" TargetControlID="AddActivity"
PopupControlID="ACTDiv" BackgroundCssClass="modalBackground" />
How can I stop getting invisibility of the ajax popup.
here is what I did to re-create your issue. I've created a web page with a modal popup extender.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="ModalPopExample.aspx.cs" Inherits="WebApp.ModalPopup.ModalPopExample" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Test Page</title>
<style type="text/css">
.hide
{
display:block;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<ajaxToolkit:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</ajaxToolkit:ToolkitScriptManager>
<asp:Panel ID="Panel1" CssClass="hide" runat="server" BorderColor="Red" BorderStyle="Dashed" BorderWidth="3px">
Are you sure?
<br />
<asp:Button ID="btnok" runat="server" Text="OK" />
<asp:Button ID="btncancel" runat="server" Text="Cancel" />
</asp:Panel>
<asp:Button ID="btnShow" runat="server" Text="Show Modal" />
<asp:Image ID="Image1" ImageUrl="~/image_loader.ashx" runat="server" />
<ajaxToolkit:ModalPopupExtender ID="btnShow_ModalPopupExtender" DropShadow="true" OkControlID="btnok" CancelControlID="btncancel" PopupControlID="Panel1" runat="server" DynamicServicePath="" Enabled="True" TargetControlID="btnShow">
</ajaxToolkit:ModalPopupExtender>
</form>
<script>
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_pageLoaded(function () {
console.log('loaded');
});
</script>
</body>
</html>
Notice that the image is loaded via a handler file (ashx):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
namespace WebApp.ModalPopup
{
/// <summary>
/// Summary description for image_loader
/// </summary>
public class image_loader : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "image/jpg";
var imagePath = context.Server.MapPath("~/images/windows_xp_bliss-wide.jpg");
Thread.Sleep(20000);
context.Response.TransmitFile(imagePath);
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
The popup flickers for a while. The most simple workaround you can do is hide the element at first itself (via css) and some javascript is required to remove that css when the web page if fully loaded.
<style type="text/css">
.hide
{
display:none;
}
</style>
When you ajax client scripts all finish loading...find the control and remove the above class on the element.
<script>
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_pageLoaded(function () {
console.log('loaded');
var div = document.getElementById('Panel1');
div.className = '';
});
</script>
Hope this helps.
Try to use update panel and refer below link for detail why Modalpopup close on postback?
http://patelshailesh.com/index.php/why-does-modalpopup-close-on-postback
You can use this JavaScript function on button click:
<script>
$("#btn").click(
function () {
window.top.location = "WebForm1.aspx";
});
</script>
I had used this function to auto update a grid on closing the Popup, if you want to see that Article and want to see how I had used this function then you can refer to this link:
http://www.c-sharpcorner.com/UploadFile/cd7c2e/how-to-auto-refresh-grid-view-on-closing-of-popup-menu/
Many other Articles and similar forums can be found on http://www.c-sharpcorner.com/
I used AsyncPostBackTrigger to run the server side code and changed the __DoPostBack method parameters. now my treeview design is
<div id="form" runat="server">
<asp:UpdatePanel ID="updTree" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:TreeView ID="tvFolderSelect" runat="server" RootNodeStyle-ForeColor="Black"
CssClass="foldertree" LeafNodeStyle-ForeColor="Black" LeafNodeStyle-Font-Bold="false"
ParentNodeStyle-ForeColor="Black" Width="100%" Style="margin: 3px 0 0 -16px;"
OnTreeNodePopulate="tvFolderSelect_TreeNodePopulate" OnTreeNodeCheckChanged="tvFolderSelect_TreeNodeCheckChanged"
ShowCheckBoxes="All" onclick="postbackOnCheck(event);">
<LeafNodeStyle Font-Bold="False" ForeColor="Black" CssClass="foldertreeleafnode"
ImageUrl="~/images/img_dms/sm_fldr.png" />
<ParentNodeStyle Font-Italic="True" ImageUrl="~/images/img_dms/sm_fldr.png" Font-Underline="True"
CssClass="foldertreeparentnode" />
<NodeStyle Font-Names="Tahoma" Font-Size="8pt" ForeColor="Black" HorizontalPadding="0px"
NodeSpacing="0px" VerticalPadding="0px" />
<RootNodeStyle ForeColor="Black" CssClass="foldertreerootnode" />
<SelectedNodeStyle Font-Underline="False" HorizontalPadding="0px" VerticalPadding="0px" />
</asp:TreeView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="tvFolderSelect" EventName="TreeNodeCheckChanged" />
</Triggers>
</asp:UpdatePanel>
and the function to postback is
function postbackOnCheck(e) {
var evt = e || window.event;
var o = evt.target || evt.srcElement;
if (o.tagName == 'INPUT' && o.type == 'checkbox' && o.name != null && o.name.indexOf('CheckBox') > -1) {
__doPostBack('<%=updTree.ClientID %>', 'Refresh:0,1,2');
}
}
Now my panel is not closing while getting postback

Enable tabpanel in tabcontainer

I have a tabcontainer with two tabs. The first tab contains a textbox, while the second tab contains a panel.
I want the second tab to be disabled at first page load, and I want it to become enabled as soon as the user enters an input in the textbox in tab1. When textbox in tab1 is emptied again, the second tab should again be disabled.
I tried the following code, but the second tab remains disabled no matter what.
Any help would be appreciated. Thank you!
aspx
<asp:TabContainer ID="TabContainer1" runat="server" ActiveTabIndex="4" HeaderText=""
Height="578px" Width="900px" TabStripPlacement="Top" ScrollBars="None" UseVerticalStripPlacement="false"
VerticalStripWidth="120px" BackColor="White" BorderColor="White" Style="margin-right: 84px">
<asp:TabPanel ID="TabPanel1" runat="server">
<HeaderTemplate>
General
</HeaderTemplate>
<ContentTemplate>
<asp:UpdatePanel ID="TestUpdatePanel" runat="server">
<ContentTemplate>
<table style="height: 247px; width: 100%;">
<tr>
<td>
<asp:TextBox ID="HorizonTextBox" runat="server" OnTextChanged="HorizonTextBox_TextChanged"
AutoPostBack="True"></asp:TextBox>
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
<ContentTemplate>
</asp:TabPanel>
<asp:TabPanel ID="TabPanel2" runat="server">
<HeaderTemplate>
Dashboard
</HeaderTemplate>
<ContentTemplate>
<asp:Button ID="RunSimulationButton" runat="server" Text="Run Simulation" OnClick="RunSimulationButton_OnClick" />
<br />
<br />
<asp:Panel ID="PlotPanel" runat="server">
</asp:Panel>
</ContentTemplate>
</asp:TabPanel>
aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
TabContainer1.ActiveTabIndex = 0;
TabPanel2.Enabled = false;
}
}
protected void HorizonTextBox_TextChanged(object sender, EventArgs e)
{
if(HorizonTextBox.Text != "")
{
TabPanel2.Enabled = true;
}
}
you may need to enclose whole tab container into updatepanel to allow update panel enable/disable child controls

Data lost in the postback

I need a way for a piece of data to presist across postbacks. Is there a way besides, cookies, and sessions?
I've got a listbox, when clicked, the selected index changed event takes a session which contains user id and feeds it to a method that fetches user's name, etc. Then I use FindControl method to locate a button inside the form view. I set the button's text property with data just fetched such as first and last name.
It works on the initial load, but if I click on other records in the listbox second time the text property is not set.
I did not write this code - I'm trying to make chages.
Here is the list box:
<asp:ListBox ID="lbxUpcommingEvents" runat="server" DataSourceID="odsUpcommingEvents"
Rows="6" DataTextField="Title" DataValueField="id" AutoPostBack="true"
Width="206px" OnSelectedIndexChanged="lbxUpcommingEvents_OnSelectedIndexChanged" />
Listbox'x on selected index changed:
protected void lbxUpcommingEvents_OnSelectedIndexChanged(object sender, EventArgs e)
{
pnlEventsSignUp.Visible = true;
string _selectedItemValue = lbxUpcommingEvents.SelectedValue.ToString();
LoadName();
}
protected void LoadName()
{
MembershipUser user = Membership.GetUser();
DataSetTableAdapters.MemberInfoTableAdapter da = new DataSetTableAdapters.MemberInfoTableAdapter();
Guid _memberId = Guid.Empty;
_memberId = new Guid(Session["myId"].ToString());
DataSet.MemberInfoDataTable dt = da.GetMember(_memberId);
if (dt.Rows.Count == 1)
{
DataSet.MemberInfoRow mr = dt[0];
RolloverLink rlnkSignUp = (RolloverLink)(fvEventSignUp.FindControl("rlnkSignUp"));
rlnkSignUp.Text = "I, " + mr.firstname + " " + mr.lastname + " will be attending this event.";
}
}
Here is markup for the form view where I set the RolloverLinkButton's text property.
<asp:Panel runat="server" ID="pnlEventsSignUp" visible="false">
<div class="dashedline" ></div>
<asp:FormView ID="fvEventSignUp" runat="server" DataSourceID="SqlDataSource1"
DataKeyNames="id" Width="100%" >
<ItemTemplate>
<h2>
<asp:Label Text='<%# Eval("title") %>' runat="server" ID="titleLabel" />
</h2>
<div class="itemdetails">
<br />
location:
<h3>
<asp:Label ID="locationLabel" runat="server" Text='<%# ShowLocationLink(Eval("locationname"),Eval("location")) %>' />
</h3>
<p>
<asp:Label Text='<%# Eval("starttime","{0:D}") %>' runat="server" ID="itemdateLabel" CssClass="GeneralText" />
<asp:Label Text='<%# ShowDuration(Eval("starttime"),Eval("endtime")) %>' runat="server" ID="Label1" CssClass="GeneralText" />
</p>
</div>
<div class="downloadevent">
<a href="#">
<img src="images/icon_download_event.gif" alt="Download this event to your personal calendar"
width="15" height="26" /></a><a href='<%# "events_download.ashx?EventID=" + Convert.ToString(Eval("id")) %>'>Add
this event to your personal calendar</a>
</div>
<Club:ImageThumbnail ID="thumb1" runat="server" ImageSize="Large" PhotoID='<%# Eval("photo") %>' />
<p>
<asp:Label Text='<%# Eval("description") %>' runat="server" ID="descriptionLabel" />
</p>
<div class="dashedline" ></div>
<asp:Panel ID="panel1" runat="server" CssClass="actionbuttons" Visible='<%#User.IsInRole("Administrators") %>'>
<table border="0" cellpadding="2" cellspacing="2">
<tr>
<td>
<asp:Label runat="server" ID="Label2" Text="Action<br />Required" Width="80px" />
</td>
<td>
<img src="images/RedArrow.jpg" alt="Red Arrow Right" />
</td>
<td>
<asp:CheckBox runat="server" ID="cbxCert" Height="30px" Text="Check to Confirm Attendance" /><br />
<asp:CustomValidator runat="server" ID="rfvConfirm"
ErrorMessage="You must check the box to continue" Font-Bold="true"
ForeColor="#cc0000" ClientValidationFunction="ensureChecked" /> <br />
<Club:RolloverLink ID="rlnkSignUp" runat="server"
/>
</td>
</tr>
</table>
</asp:Panel>
</ItemTemplate>
</asp:FormView>
</asp:Panel>
You can use ViewState. Since you are dynamically looking up the button, setting a property is quicker and we can then let Asp.Net find the button and set its text via one of the two methods I explain below:
public string rlnkSignUpText
{
get { return Convert.ToString(ViewState["rlnkSignUpText"] ?? "default value"); }
set { ViewState["rlnkSignUpText"] = value; }
}
Replace your code that searches for the button and assigns the text with:
rlnkSignUpText = "I, " + mr.firstname + " " + mr.lastname + " will be attending this event.";
Then use one of these methods to set the text to the control:
1) Use the control's OnPreRender event:
To render it, add OnPreRender="rlnkSignUp_PreRender" to your xaml like this:
<Club:RolloverLink ID="rlnkSignUp" runat="server" OnPreRender="rlnkSignUp_PreRender" />
Then in your codebehind:
protected void rlnkSignUp_PreRender(object sender, EventArgs e)
{
RolloverLink rlnkSignUp = (RolloverLink)sender;
rlnkSignUp.Text = rlnkSignUpText;
}
2) Bind the property and control together:
Instead of using the control's PreRender you can bind to the property with:
<Club:RolloverLink ID="rlnkSignUp" runat="server" Text='<%# rlnkSignUpText %>' />
You then need to call DataBind in your Page_PreRender() like so:
void Page_PreRender(object sender, EventArgs e)
{
DataBind();
}
Have you enabled ViewState in the control.
Enable View State

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