Web User Control get parent control ID? - c#

ASCX
<dx:ASPxGridViewExporter ID="ASPxGridViewExporter1" runat="server">
</dx:ASPxGridViewExporter>
<dx:ASPxButton ID="buttonSaveAs" runat="server" ToolTip="Export and save" Style="vertical-align: middle;"
OnClick="buttonSaveAs_Click" Text="Save" Width="51px" />
ASPX that include above ASCX
<div>
//ASCX
</div>
<div>
<dx:ASPxPivotGrid ID="ASPxPivotGridElectricMeterReadings" runat="server" ClientIDMode="AutoID"
DataSourceID="SqlDataSourceElectricMeterReadings" EnableCallBacks="False" Width="1000px">
</dx:ASPxPivotGrid>
</div>
ASCX.cs
protected void buttonSaveAs_Click(object sender, EventArgs e)
{
// I want to get pivotGridId from ASPX
ASPxGridViewExporter1.ASPxPivotGridID = ASPX-PivotGrid-ID
}
How can I pass ASPX control ID to ASCX button_click_event?

Simply add a property to your ascx code behind and populate it in the aspx initialize event.
ASCX.cs
public string PivotGridID { get; set; }
ASPX.cs
if (!IsPostBack)
{
exportPivotGrid.PivotGridID = ASPxPivotGridElectricMeterReadings.ID;
}

Try, declaration of the parent control, in page load event(User Control) and must be outside the postback event.
(this.Parent.Parent).FindControl("ErrLabel") as Label;

Related

Update textbox in UserControl from another UserControl

I hava a MasterPage with 2 UserControls. When something happens in UserControl1.ascx, it has to update a TextBox in UserControl2.ascx.
I tried this inside UserControl1.ascx, but no success:
UserControl userControl = (UserControl)LoadControl("UserControl2.ascx");
var txt = (TextBox) userControl.FindControl("txtTest");
txt.Text = "Hello world";
Thanks for all help :)
The LoadControl is load a new control that is not exist on page...
Lets see this example.
You have a master page that has 2 User Controls.
<form id="form1" runat="server">
<div>
<uc1:WebUserControl ID="WebUserControl1" runat="server" />
<br /><br />
<uc2:WebUserControl ID="WebUserControl2" runat="server" />
<br /><br />
<asp:Button runat="server" ID="btnOk" Text="ok" OnClick="btnOk_Click" />
</div>
</form>
and on code behind this
protected void btnOk_Click(object sender, EventArgs e)
{
WebUserControl1.TextOnMe = WebUserControl2.TextOnMe;
}
Now the user controls have this on html
<asp:TextBox runat="server" ID="txtText"></asp:TextBox>
and on code behind you get and set the Text like that on code behind
public string TextOnMe
{
get
{
return txtText.Text;
}
set
{
txtText.Text = value;
}
}
One Similar Answer
ASP.NET MasterPage only control?

Asp.net repeater control with checkboxlist

Binding data to checkbox list inside a repeater controls ItemDataBound event.
Here is Aspx code:
<asp:Repeater ID="rptrSelectedRcds" runat="server">
<ItemTemplate>
<div id="groupsDiv" runat="server">
<div class="hidden" id="divGroupSelector" runat="server">
<asp:CheckBoxList runat="server" ID="chkLstGroups"
RepeatDirection="Vertical">
</asp:CheckBoxList>
</div>
<asp:Button ID="btnConfirmGroups" runat="server" Text="Confirm" />
</div>
</ItemTemplate>
</asp:Repeater>
Code used inside ItemDataBound to bind data to repeater control:
protected void rptrSelectedRcds_ItemDataBound(object sender, System.Web.UI.WebControls.RepeaterItemEventArgs e)
{
Int32 iProviderID = Convert.ToInt32(((Label)e.Item.FindControl("lblIndividualID")).Text);
HtmlGenericControl selectGroupsDiv = (HtmlGenericControl)e.Item.FindControl("divGroupSelector");
if (divGroupSelector != null)
{
CheckBoxList chkLstGroups = (CheckBoxList)e.Item.FindControl("chkLstGroups");
chkLstGroups.DataSource = GetStateGroupsByProvider(stateValue, iProviderID);
//This code line gives different values for each record
chkLstGroups.DataTextField = "Name";
chkLstGroups.DataValueField = "pkID";
chkLstGroups.DataBind();
}
}
I can see in firebug the ids for chkLstGroups are different, but values bind to it are same.I want different values for each different checkbox id generated as from method - GetStateGroupsByProvider
Please help me out..!
Thanks.!

Uncaught Sys.InvalidOperationException: Sys.InvalidOperationException: Could not find UpdatePanel

I`m building a dashboard application using ASP.NET where users can change positions of the widgets; i used jquery sortables for that. The widgets are ascx (asp.net usercontrols) which are added dynamically to the page. Every event in the widget works fine on if the user have not changed the positions of the widgets but if the position is changed i get this error.
Uncaught Sys.InvalidOperationException: Sys.InvalidOperationException: Could not find UpdatePanel with ID 'xxx'. If it is being updated dynamically then it must be inside another UpdatePanel.
Here is the code of one of the widgets and user can add multiple instances of it.
<asp:UpdatePanel ID="UpdatePanel1" runat="server" >
<ContentTemplate>
<div class="setting" >
<asp:TextBox ID="txtwidgettitle" runat="server"></asp:TextBox>
<div id="settingfooter">
<asp:LinkButton ID="lnkbtnSave" runat="server" onclick="lnkbtnSave_Click">Save</asp:LinkButton>
<asp:LinkButton ID="lnkbtncancel" runat="server" CssClass="btn ui-state-default ui-corner-all">Cancel</asp:LinkButton>
</div>
</div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="lnkbtnSave" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
<div class="pcontent">
<asp:Literal ID="ltrtwcontent" runat="server"></asp:Literal>
</div>
And the code behind
protected void Page_Load(object sender, EventArgs e)
{
ltrtwcontent.Text = jqPlotHelper.RenderChart(CurrentWidgetInstance.Id.ToString());
}
protected void lnkbtnSave_Click(object sender, EventArgs e)
{
DashboardServices d = new DashboardServices();
CurrentWidgetInstance.Title = txtwidgettitle.Text;
CurrentWidgetInstance.LastUpdate = DateTime.Now;
d.SaveOrUpdateWidgetInstance(CurrentWidgetInstance);
}
on the aspx page loading the controls i first have a container which is added dynamically and the container will add the the widget instances (the ascx controls)
Code on the page
protected void Page_Init(object sender, EventArgs e)
{
this.SetBasePageVAR(DashboredPageGuid);
if (this.UsrPage != null)
{
phltabs.Controls.Add(LoadDashboardTab());
}
}
public HtmlGenericControl LoadDashboardTab()
{
HtmlGenericControl mainList = new HtmlGenericControl("div");
mainList.Attributes["Id"] = "tabs";
foreach (WidgetInstance widgetInst in CurrentDashboardTab.WidgetInstances)
{
HtmlGenericControl headerList = new HtmlGenericControl("ul");
WidgetContainerBaseControl widgetContainer = LoadControl("~/Dashboard/WidgetContainer.ascx") as WidgetContainerBaseControl;
widgetContainer.SetControlVAR(widgetInst);
headerList.Controls.Add(widgetContainer);
mainList.Controls.Add(headerList);
}
return mainList;
}
and on WidgetContainer.ascx
protected void Page_Init(object sender, EventArgs e)
{
LoadWidgetInstance();
}
public void LoadWidgetInstance()
{
WidgetControl widget = LoadControl(CurrentWidgetInstance.Widget.Url) as WidgetControl;
widget.ID = "wid_" + CurrentWidgetInstance.Id;
this.phlcontent.Controls.Add(div);
}
try this: Add trigger Like this and Remove the one in Asps Page
ScriptManager sm = (ScriptManager)Page.Master.FindControl("ScriptManager1");
sm.RegisterPostBackControl(Button);

Refreshing UpdatePanel after click event of a Button inside a modalpopup inside a UserControl

I have a page with a listbox and a user control placed inside an update panel like this:
<%# Register TagPrefix="uc1" TagName="CMessage" Src="~/Controls/CMessage.ascx" %>
<ajaxToolkit:ToolkitScriptManager runat="server" ID="ToolkitScriptManager1" EnableScriptGlobalization="true" EnableScriptLocalization="true" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:ListBox ID="lbox" runat="server"></asp:ListBox>
<asp:Button ID="btnDelete" OnClick="btnDelete_Click" runat="server" Text="Delete selected item" Enabled="True"></asp:Button>
<uc1:CMessage ID="CMessage1" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
The page codebehind is like this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
lbox.Items.Add("test1");
lbox.Items.Add("test2");
}
}
protected void btnDelete_Click(object sender, EventArgs e)
{
CMessage.MessageConfirm("Delete item?", "Yes", "No", DeleteItem);
}
protected void DeleteItem()
{
lbox.Items.Remove(lbox.SelectedItem);
CMessage.Message("Item deleted succesfully!");
}
The user control is like this:
<%# Control Language="C#" AutoEventWireup="true" CodeFile="CMessage.ascx.cs" Inherits="Controles.CMessage" %>
<table id="tableMessage" runat="server" style="display: none" class="modalPopup">
<tr>
<td>
<asp:Label ID="lb5" runat="server" Text="Message"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:Label ID="lbMessage" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:Button ID="btnOk" runat="server" Text="Ok" OnClick="btnOk_Click" />
<asp:Button ID="btnCancel" runat="server" Text="Cancel" OnClick="btnCancel_Click" />
</td>
</tr>
</table>
<asp:Button ID="btnOKError" runat="server" Text="OK" style="display: none" />
<ajaxToolkit:ModalPopupExtender ID="ModalPopupMessage" runat="server" TargetControlID="btnOKError" PopupControlID="tableMessage" OkControlID="btnOKError" CancelControlID="btnOKError"></ajaxToolkit:ModalPopupExtender>
The usercontrol codebehind is like this:
public partial class CMensaje : UserControl
{
public delegate void FunctionButtonPressed();
private FunctionButtonPressed FunctionButtonPressedOk
{
get { return (FunctionButtonPressed)Session["FunctionButtonPressedOk"]; }
set { Session["FunctionButtonPressedOk"]= value; }
}
protected void btnOk_Click(object sender, EventArgs e)
{
ModalPopupMenssage.Hide();
if (FunctionButtonPressedOk!= null)
{
FunctionButtonPressedOk();
}
}
protected void btnCancel_Click(object sender, EventArgs e)
{
ModalPopupMessage.Hide();
}
public void Mensaje(string message)
{
lbMessage.Text = message;
FunctionButtonPressedOk= null;
btnCancel.Visible = false;
ModalPopupMessage.Show();
}
public void MessageConfirm(string message, FunctionButtonPressed FunButtonOkx)
{
lbMessage.Text = message;
FunctionButtonPressedOk= FunBotonAceptarx;
btnCancel.Visible = true;
ModalPopupMensaje.Show();
}
}
Everything works, the popup is shown, the function to call from the page is passed to the usercontrol to trigger it if the user presses ok and triggers correctly etc. But in that last function DeleteItem() the changes done to the page (in this example the item removed from the listbox and the notification message launched) doesnt work.
Its like the updatepanel doesnt refresh. I cant call manually UpdatePanel1.Update() because i have the updatemode as always. In theory in this part of the pagecycle it should refresh the pages with the changes...
I tried adding in the user control pageload the OK button as a PostBackTrigger of the UpdatePanel with no avail and as an AsyncPostBackTrigger.
Keep in mind that this is an slimmed down version of the page and the user control so people can focus on the problem at hand so if you need any more details ask me...
The code flow is like this:
User clicks in the delete item button and triggers the
btnDelete_Click() in the page (first postback)
btnDelete_Click() calls the usercontrol CMessage.MessageConfirm passing DeleteItem as
argument
At the usercontrol MessageConfirm() shows the modalpopup and saves
the argument function DeleteItem() in order to call it later(end of
first postback)
After displaying the modalpopup the user clicks its Ok button and
triggers the btnOk_Click() in the usercontrol (second postback)
At the usercontrol btnOk_Click() calls the DeleteItem() function
that was saved previously
At the page DeleteItem() removes the item from the ListBox (lets say
i dont call the second message to simplify, this would be the end of
the second postback, and the update panel hasnt refreshed :S)
I think i have isolated the problem, moved all the controls and functions from the usercontrol to the page, the problem persisted, but if i called the DeleteItem() function directly instead of his delegate it worked (keep in mind that in both cases the breakpoint at DeleteItem() triggered so the function code was executing correctly):
protected void btnOk_Click(object sender, EventArgs e)
{
ModalPopupMenssage.Hide();
/*if (FunctionButtonPressedOk!= null)
{
FunctionButtonPressedOk();
}*/
DeleteItem(); //page updates correctly! why?
}
Is there some incompatibility with delegates?
In the end i solved it changing the following lines:
if (FunctionButtonPressedOk!= null)
{
//FunctionButtonPressedOk();
Page.GetType().InvokeMember(FunctionButtonPressedOk.Method.Name, BindingFlags.InvokeMethod, null, Page, new []{sender, e});
}
Why it works this way?Whats the difference internally?

Firing an event from an ascx control in order to update some controls in the container

I am firing an event from an ascx control in order to update some controls in the container to which the ascx control belongs.
The ascx control is displayed via a modal popup extender. When I click a button inside the ascx, I fire an event to which the container containing the ascx control is subscribes.
The event delegate is fired and the expected logic is run in the container's code behind, the problem is that any changes made to controls inside not the container aren't updated despite the event logic having been processed. The expected changes are not reflected on the page when the results of the postback is rendered.
Are there any pitfalls I should know of?
The markup for the container
<asp:Panel ID="panelTreeViewAttributesTitle" runat="server">
<asp:Label ID="someLabel" runat="server" Text="Hello Governor" />
<asp:LinkButton ID="LinkButtonEdit" runat="server" Text="(Edit)" />
<ajax:ModalPopupExtender BackgroundCssClass="modalBackground" Enabled="True"
ID="btnEdit_ModalPopupExtender" PopupControlID="modalPanel" runat="server"
TargetControlID="LinkButtonEdit" />
</asp:Panel>
<asp:Panel ID="modalPanel" runat="server" CssClass="modalPopUp" Style="display: none">
<xxx:customControl runat="server" ID="myCustomControl" />
</asp:Panel>
The code behind for the container
protected void Page_Load(object sender, EventArgs e)
{
myCustomControl.Updated += eventCaptured;
if (IsPostBack) return;
...
}
void eventCaptured(object sender, EventArgs e)
{
someLabel.Text = "Goodbye Governor";
}
The custom control
<script type="text/javascript">
function Update() {
var ajaxManager = $find("<%= RadAjaxManager.GetCurrent(Page).ClientID %>");
if (ajaxManager != null)
ajaxManager.ajaxRequest("");
}
</script>
<asp:Panel ID="panelEditPanel" runat="server">
<asp:Label ID="lblCMA" runat="server" Text="Call me Arnooold." />
</asp:Panel>
<asp:Button ID="btnUpdate" runat="server" Text="Update" OnClientClick="Update()" />
<asp:Button ID="btnCancel" runat="server" Text="Cancel" />
The custom control's code behind
public event EventHandler Updated;
protected void AjaxManager_AjaxRequest(object sender, AjaxRequestEventArgs e)
{
//Some DB backend logic
UpdateFinished();
}
private void UpdateFinished()
{
if (Updated == null) return;
Updated(this, null);
}
Maybe the button click is causing a partial post back instead of a normal, full-page post back. If this is the case, the entire life cycle would run on the server side (including your event handler) but only part of the HTML would be updated on the client side when the response comes back to the browser. "someLabel" could be outside the region that gets updated on the client side.

Categories

Resources