Showing posts with label modal. Show all posts
Showing posts with label modal. Show all posts

Wednesday, March 28, 2012

dinamically adding a webuser control to a Modal Pop Up Extender

I have a page that has two buttons and a text box on it. It also has a panel named pnlPopUp and an modalpopupextender which has 'pnlPopUp' as the PopupControlID.

If you Click Button1 it will display webusercontrol1 and if you click button2 it will display webusercontrol2.

Each user control has two buttons on tem (btnOK and btnCancel).

The web user controls are added dinamically to the panel when I click button1 or button2 (using Page.LoadControl("~/WebUserControl.ascx") andpnlPopup.Controls.Add(webusercontrol) );

I am trying to fill the text of teh textbox in the page according to which button is clicked on the pop-up (if I click Ok it writes "OK" in the textbox),

but my button events aren′t firing!


P.S.: If I load the controls in the page′s Page_Load and making them visible when I need them it will work fine but I didn′t want to do that because in my actual web site i will have too many user controls.

Here′s the sample code. (I′m using the exact code for both user controls):

==================== Default.aspx=============================

<%@dotnet.itags.org. Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@dotnet.itags.org. Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<%@dotnet.itags.org. Register src="http://pics.10026.com/?src=~/WebUserControl.ascx" TagName="WebUserControl" TagPrefix="wuc" %
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
<link rel="stylesheet" href="http://links.10026.com/?link=back.css" type="text/css" media="screen" />
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server" EnableViewState="true">
<ContentTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

<asp:Button ID="btnPopup" runat="server" Text="PopUp" />

<input type="hidden" runat="server" id="hdnPopUp" />

<asp:Panel ID="pnlPopUp" runat="server" CssClass="modalPopup">
</asp:Panel>

<cc1:ModalPopupExtender ID="mpeTestePopUp" runat="server" TargetControlID="hdnPopUp"
PopupControlID="pnlPopUp" DropShadow="true" BackgroundCssClass="modalBackground">
</cc1:ModalPopupExtender>
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
</html>

===========================================================

==================== Default.aspx.cs============================

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using AjaxControlToolkit;

public partial class _Default : System.Web.UI.Page
{
WebUserControl ucTestePopUp;

protected void Page_Load(object sender, EventArgs e)
{
}

void Page_Init(object sender, EventArgs e)
{
this.btnPopup.Click += new EventHandler(btnPopup_Click);
}

void btnPopup_Click(object sender, EventArgs e)
{
ucTestePopUp = (WebUserControl)Page.LoadControl("~/WebUserControl.ascx");
this.pnlPopUp.Controls.Add(ucTestePopUp);
this.mpeTestePopUp.Show();
}
}

============================================================

==================== WebUserControl.ascx============================

<%@dotnet.itags.org. Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs" Inherits="WebUserControl" %>
<table>
<tr>
<td>
<asp:Button runat="server" ID="btnSim" Text="Sim" />
</td>
<td>
<asp:Button runat="server" ID="btnNao" Text="Nao" />
</td>
</tr>
</table>

==================================================================

==================== WebUserControl.ascx.cs============================

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class WebUserControl : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}

void Page_Init(object sender, EventArgs e)
{
this.btnSim.Click += new EventHandler(btnSim_Click);
this.btnNao.Click += new EventHandler(btnNao_Click);
}

protected void btnNao_Click(object sender, EventArgs e)
{
((TextBox)this.Parent.FindControl("txtTeste")).Text = "Clicou N?o";
}

protected void btnSim_Click(object sender, EventArgs e)
{
((TextBox)this.Parent.FindControl("txtTeste")).Text = "Clicou Sim";
}
}

=================================================================

Hi,

to handle events you need a control with an event handler to instantiated. If you only load your user control once in the click event handler, the button (textbox) in your user control does not exist on the page when postback caused by this button in user control is processed at the server.

Therefore, as you said you need to load your user control in page_load to handle events.

However, you don't need to load all controls. You just need to remeber which control was created last time and create this single control. You can store this information in the ViewState property.

Once you handled events from controls insode user control you can safely remove it from the page.

ALSO: You need to assign ID to your dynamically loaded user control. Otherwise, you will occasionally get problems with events firing from the second click.

-yuriy
http://couldbedone.blogspot.com

Monday, March 26, 2012

DetailsView Inside of a Modal Popup

I'm using a DetailsView to insert new records into a database as well as edit existing records. The Modal is called via ModalPopupExtender.Show() when a LinkButton is clicked and then hidden when the LinkButtons on the DetailsView are clicked. The Functions of the modal popup seem to work fine as well as the Insert() Update() methods of the DetailsView. The problem I'm having is with updating the Text property of the LinkButton at the bottom of the DetailsView to change it from "Add" to "Save" depending on the DetailsView.CurrentMode that I'm changing to/from. I've tried using Update Panels around the LinkButtons only in the DetailsView and then I added an AsyncPostBack trigger for the LinkButton that pops the modal DetailsView in Insert mode and an AsyncPostBack that pops the modal DetailsView in Edit mode from the GridView I have on the page. Then I added a PostBack trigger to handle clicks of the LinkButton on the DetailsView for Insert/Update (depending on the mode) and then Cancel. Both of the postbacks close the modal successfully, it's the AsyncPostBacks that are not updating the Modal DetailsView to show the right Text on the one LinkButton I'm trying to update. Any help would be appreciated. Here is the code:

1protected void Page_Load(object sender, EventArgs e)2 {34 }5protected void AddCategory_OnClick(object sender, EventArgs e)6 {7 ModalPopupExtender1.Show();8 CategoryDetailsView.ChangeMode(DetailsViewMode.Insert);910 }11protected void UpdateInsert_OnClick(object sender, EventArgs e)12 {13if (CategoryDetailsView.CurrentMode == DetailsViewMode.Insert)14 {15 CategoryDetailsView.InsertItem(true);16 }17if (CategoryDetailsView.CurrentMode == DetailsViewMode.Edit)18 {19 CategoryDetailsView.UpdateItem(true);20 }21 }22protected void Cancel_OnClick(object sender, EventArgs e)23 {24 ModalPopupExtender1.Hide();25 CategoryDetailsView.ChangeMode(DetailsViewMode.ReadOnly);2627 }28private LinkButton updateinsertbtn29 {30get31 {32 LinkButton udtisrtbtn;33 udtisrtbtn = (LinkButton)CategoryDetailsView.FindControl("UpdateInsertLinkBtn");34return udtisrtbtn;35 }36 }37private int index38 {39get40 {41return CategoryGridView.SelectedIndex;42 }43 }44protected void CategoryGridView_OnSelectedIndexChanged(object sender, EventArgs e)45 {46 CategoryDetailsView.ChangeMode(DetailsViewMode.Edit);47if (index != -1)48 {49 ModalPopupExtender1.Show();50 CategoryGridView.DataSourceID =null;51 CategoryTableAdapter categoryAdapter =new CategoryTableAdapter();52 CategoryGridView.DataSource = categoryAdapter.GetCategories();53 CategoryGridView.SelectedIndex = index;54int categoryid = Convert.ToInt32(((Categories.CategoryDataTable)CategoryGridView.DataSource).Rows[CategoryGridView.SelectedRow.DataItemIndex]["CategoryID"]);55 SqlDataSource1.SelectCommand ="Select CategoryName, CategoryDescription, CategoryID from Category where CategoryID = " + categoryid;5657 CategoryDetailsView.DataBind();58 CategoryGridView.DataSource =null;59 CategoryGridView.DataSourceID ="SqlDataSource1";60 SqlDataSource1.SelectCommand ="Select CategoryID, CategoryName, CategoryDescription from Category Order by CategoryName";61 CategoryGridView.DataBind();6263 }64 }

<asp:ContentID="Content1"ContentPlaceHolderID="maincontent"Runat="Server">
<script>
function okScript()
{
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm._doPostBack('UpdatePanel1','');
}
</script>
<asp:ScriptManagerid="ScriptManager1"runat="server"></asp:ScriptManager>
<table>
<tr>
<tdvalign="top"style="padding:5px;line-height:1.6em;">

<asp:HyperLinkID="AddCatLinkButton"runat="server"Text="Add New Category"NavigateUrl="javascript:NewCategory('addCategory.aspx');"></asp:HyperLink><br/>

<asp:LinkButtonID="AddCategoryLinkButton"runat="server"Text="Add New Category"OnClick="AddCategory_OnClick"></asp:LinkButton>

</td>

<tdvalign="top">

<asp:UpdatePanelid="UpdatePanel1"runat="server"UpdateMode="Conditional">

<contenttemplate>

<asp:GridViewid="CategoryGridView"runat="server"DataSourceID="SqlDataSource1"CellPadding="3"DataKeyNames="CategoryID"AutoGenerateColumns="False"OnSelectedIndexChanged="CategoryGridView_OnSelectedIndexChanged">

<Columns>

<asp:CommandFieldHeaderText="Edit"ShowSelectButton="true"SelectText="Edit"/>

<asp:BoundFieldDataField="CategoryID"HeaderText="CategoryID"InsertVisible="False"ReadOnly="True"SortExpression="CategoryID"Visible="False"/>

<asp:BoundFieldDataField="CategoryName"HeaderText="Name"SortExpression="CategoryName"/>

<asp:BoundFieldDataField="CategoryDescription"HeaderText="Description"SortExpression="CategoryDescription"/>

<asp:TemplateFieldHeaderText="Remove Category">

<ItemTemplate>

<asp:LinkButtonID="DeleteButton"runat="server"Text="Remove"CommandName="Delete"></asp:LinkButton>

</ItemTemplate>

<ItemStyleHorizontalAlign="Center"/>

</asp:TemplateField>

</Columns>

<EmptyDataTemplate>

There are no categories to display.

</EmptyDataTemplate>

</asp:GridView>

</contenttemplate>

</asp:UpdatePanel>

</td>

</tr> </table>

<asp:PanelID="CategoryPanel"runat="server"GroupingText="Product Category"Style="display:none;"CssClass="modalPopup">

<asp:DetailsViewID="CategoryDetailsView"runat="server"AutoGenerateRows="False"DataKeyNames="CategoryID"DefaultMode="ReadOnly"

DataSourceID="SqlDataSource1"CellPadding="3"CssClass="TextBox"OnModeChanged="CategoryDetailsView_OnModeChanged">

<Fields>

<asp:BoundFieldDataField="CategoryID"HeaderText="CategoryID"InsertVisible="False"

ReadOnly="True"SortExpression="CategoryID"Visible="False"/>

<asp:BoundFieldDataField="CategoryName"HeaderText="Name"SortExpression="Name"/>

<asp:BoundFieldDataField="CategoryDescription"HeaderText="Description"

SortExpression="Description"/>

</Fields>

<FooterTemplate>

<asp:UpdatePanelID="LinkUpdate"runat="server"EnableViewState="true"UpdateMode="Always"RenderMode="Inline">

<ContentTemplate>

<asp:LinkButtonID="UpdateInsertLinkBtn"runat="server"Text="Test"OnClick="UpdateInsert_OnClick"></asp:LinkButton>

</ContentTemplate>

<Triggers>

<asp:AsyncPostBackTriggerControlID="AddCategoryLinkButton"EventName="Click"/>

<asp:AsyncPostBackTriggerControlID="CategoryGridView"EventName="SelectedIndexChanged"/>

<asp:PostBackTriggerControlID="UpdateInsertLinkBtn"/>

<asp:PostBackTriggerControlID="CancelButton1"/>

</Triggers>

</asp:UpdatePanel>

<asp:LinkButtonID="CancelButton1"runat="server"Text="Cancel"OnClick="Cancel_OnClick"></asp:LinkButton>

</FooterTemplate>

</asp:DetailsView>

<divalign="center">

<asp:LinkButtonID="OkButton"runat="server"></asp:LinkButton> <asp:LinkButtonID="CancelButton"runat="server"></asp:LinkButton>

</div>

</asp:Panel>

<ajaxToolkit:ModalPopupExtenderID="ModalPopupExtender1"runat="server"TargetControlID="AddCatLinkButton"CancelControlID="CancelButton"OkControlID="Okbutton"

PopupControlID="CategoryPanel"OnOkScript="okScript()"BackgroundCssClass="modalBackground"DropShadow="true">

</ajaxToolkit:ModalPopupExtender>

<asp:SqlDataSourceID="SqlDataSource1"runat="server"ConnectionString="<%$ ConnectionStrings:IT_ASSETDbase %>"

DeleteCommand="DELETE FROM [Category] WHERE [CategoryID] = @dotnet.itags.org.CategoryID"

InsertCommand="INSERT INTO [Category] ([CategoryName], [CategoryDescription]) VALUES (@dotnet.itags.org.CategoryName, @dotnet.itags.org.CategoryDescription)"

SelectCommand="SELECT 'javascript:NewCategory(''editCategory.aspx?CategoryID=' + CAST(CategoryID AS nvarchar) + ''');' AS URL, CategoryID, CategoryName, CategoryDescription FROM Category"

UpdateCommand="UPDATE [Category] SET [CategoryName] = @dotnet.itags.org.CategoryName, [CategoryDescription] = @dotnet.itags.org.CategoryDescription WHERE [CategoryID] = @dotnet.itags.org.CategoryID">

<DeleteParameters>

<asp:ControlParameterControlID="CategoryGridView"Name="CategoryID"PropertyName="SelectedValue"Type="Int32"/>

</DeleteParameters>

<UpdateParameters>

<asp:ParameterName="CategoryName"Type="String"/>

<asp:ParameterName="CategoryDescription"Type="String"/>

<asp:ParameterName="CategoryID"Type="Int32"/>

</UpdateParameters>

<InsertParameters>

<asp:ParameterName="CategoryName"Type="String"/>

<asp:ParameterName="CategoryDescription"Type="String"/>

</InsertParameters>

</asp:SqlDataSource>

</asp:Content>

">

I was unable to accomplish changing the Text property value to what I wanted but I ended up modifying the code to remove the Update Panels in order to get modal DetailsView to Insert and Edit records and then update the GridView control by calling GridView.DataBind() after the Update() or Insert() methods were called for the DetailsView. Not exactly what I wanted but works.