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?
Related
In my ASP.Net app, I have a button that launches a modal. The onClick event fires the C# behind code that launches a modal. I am then calling a data table and populating string variables with values from the data table:
protected void uxTicketHistoryButton_Click(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(this.GetType(), "key", "launchModal();", true);
DataTable ticketHist = _dtMgr.GetContactInfoByName(uxContactDropdownList.SelectedValue);
string rName = ticketHist.Rows[0]["RequestorName"].ToString();
string rPhone = ticketHist.Rows[0]["RequestorPhone"].ToString();
string rPhoneExt = ticketHist.Rows[0]["RequestorPhoneExt"].ToString();
string rEmail = ticketHist.Rows[0]["RequestorEmail"].ToString(); ;
string rState = ticketHist.Rows[0]["RequestorState"].ToString();
string rOrg = ticketHist.Rows[0]["RequestorOrg"].ToString();
}
What I want to do now is add those variable values to my modal inside the panel.
<asp:Button ID="uxTicketHistoryButton" runat="server" Text="Show Ticket History" style="color: blue;" OnClick="uxTicketHistoryButton_Click"/>
<!-- ModalPopupExtender-->
<ajaxToolkit:ModalPopupExtender ID="uxTicketHistoryModal" runat="server" PopupControlID="Panel1" TargetControlID="uxTicketHistoryButton"CancelControlID="btnClose" BackgroundCssClass="modalBackground">
</ajaxToolkit:ModalPopupExtender>
<asp:Panel ID="Panel1" runat="server" CssClass="modalPopup" align="center" style = "display:none">
**** Add variable values here ****
<asp:Button ID="btnClose" runat="server" Text="Close" />
</asp:Panel>
How do I add the variables from my .cs file to the modal panel in my .aspx file so that it shows up like this (values in the { } )?
UPDATE
This issue seems to be related to the modal interfering with the _Click event function of my button. I have posted an additional question to resolve this problem first. Then, I believe one of the solutions below may work. Thanks everybody!
Webform:
<asp:Panel ID="Panel1" runat="server" CssClass="modalPopup" align="center" style = "display:none">
Name: <asp:Literal ID="Name" runat="server" /><br>
Organization: <asp:Literal ID="Organization" runat="server" /><br>
etc....
<asp:Button ID="btnClose" runat="server" Text="Close" />
</asp:Panel>
Codebehind:
Name.Text = ticketHist.Rows[0]["RequestorName"].ToString();
Organization.Text = ticketHist.Rows[0]["RequestorOrg"].ToString()
You can use ASP.NET Razor to post your c# variables directly into your html.
For Example
<!-- Single statement block -->
#{ var myMessage = "Hello World"; }
<!-- Inline expression or variable -->
<p>The value of myMessage is: #myMessage</p>
<!-- Multi-statement block -->
#{
var greeting = "Welcome to our site!";
var weekDay = DateTime.Now.DayOfWeek;
var greetingMessage = greeting + " Here in Huston it is: " + weekDay;
}
<p>The greeting is: #greetingMessage</p>
OR
you could use get and set methods to post your variables to the modal from you .cs .
public class yourModalPage
{
public string RequestorName { get; set; }
}
Then you can send values to your modal from your .cs with
yourModalPage.RequestorName = "RequestorName";
I am trying to create a page using Ajax Tabs and user controls. The .aspx page contains a reference to a default control
<%# Register src="~/Controls/DefaultControl.ascx" tagname="DefaultControl" tagprefix="uc1" %>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<uc1:DefaultControl ID="DefaultControl1" runat="server" />
<%--<uc2:CorrespondenceControl ID="CorrespondenceControl" runat="server" />--%>
</asp:Content>
And the DefaultControl.ascx is using Ajax Tabs, one of which contains a child control within an Update Panel
asp:TabPanel ID="tbpnl2" runat="server" HeaderText="Tab With GridView with select buttons" Visible="True">
<ContentTemplate>
<asp:UpdatePanel ID="updpnl2" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<uc2:Control1 ID="Control1" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
</ContentTemplate>
</asp:TabPanel>
The DefaultControl holds a method in the code behind page which is successfully called directly from other tabs (with the markup contained directly in DefaultControl.ascx) on the DefaultControl.ascx page to change the display when Select is clicked on a gridview -
public void ShowPage()
{
gv1.DataBind();
fv1.DataBind();
tbpnl1.Visible = true; //show details tab
tbpnl2.Visible = true;
tab1.ActiveTabIndex = 1; //set details tab as current tab
txt.Text = String.Empty;
updPnl1.Update();
}
I am trying to call this method from the child Control1 when Select on a gridview is selected there, but obviously none of the elements referenced are in Control1.
I have been searching for a way to be able to use the existing method and have seen a number of suggestions including Interfaces, references like ((DefaultControl)this.DefaultControl).ShowPage(); on the code behind Control1
But as I am just starting to program I have no idea how to implement any of these solutions or what the syntax should be to get them to work.
Is there a simple, even if dirty, way to use the method from a parent control in a child control contained in an Ajax tab?
Not sure if this is what you are looking for... Below example shows calling of direct UserControl and nested UserControl method's from Web page
Default.aspx
<%# Register TagPrefix="uc" TagName="WebUserControl" Src="WebUserControl.ascx" %>
<%# Register TagPrefix="uc2" TagName="WebUserControl2" Src="WebUserControl2.ascx" %>
<form runat="server" id="form1">
<uc:WebUserControl ID="control1" runat="server" />
<hr />
<h4>
At Default.aspx</h4>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Call the function" />
</form>
Default.aspx.cs
protected void Button1_Click(object sender, EventArgs e)
{
control1.CallMe();
var control2 = (WebUserControl2)control1.FindControl("control2");
control2.CallMe2();
}
WebUserControl.ascx
<%# Register TagPrefix="uc2" TagName="WebUserControl2" Src="WebUserControl2.ascx" %>
<div runat="server">
<h3>
WebUserControl</h3>
<asp:Label ID="lbl1" Text="I am ready at WebUserControl" runat="server"></asp:Label>
<div runat="server" id="toAdd" style="color: Red;">
</div>
</div>
<hr />
<uc2:WebUserControl2 ID="control2" runat="server" />
WebUserControl.ascx.cs
public void CallMe()
{
Label lbl = new Label();
lbl.Text = "I am at WebUserControl";
toAdd.Controls.Add(lbl);
}
WebUserControl2.ascx
<div runat="server">
<h3>
WebUserControl2</h3>
<asp:Label ID="lbl1" Text="I am ready at WebUserControl2" runat="server"></asp:Label>
<div runat="server" id="toAdd" style="color: Red;">
</div>
</div>
WebUserControl2.ascx.cs
public void CallMe2()
{
Label lbl = new Label();
lbl.Text = "I am at WebUserControl2";
toAdd.Controls.Add(lbl);
}
Hope it helps someone...!!
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;
I have got the Ajax toolkit autocomplete working using the following asp.net and C# code.
<form id="form1" runat="server">
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</asp:ToolkitScriptManager>
<div>
Search our Languages: <asp:TextBox ID="txtLanguage" runat="server"></asp:TextBox>
<asp:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server"
TargetControlID="txtLanguage" MinimumPrefixLength="1"
ServiceMethod="GetCompletionList" UseContextKey="True">
</asp:AutoCompleteExtender>
<br />
<br />
<asp:Button ID="btnAddSelected" runat="server" Text="Add to chosen Languages >"
onclick="btnAddSelected_Click" />
<br />
<br />
<asp:Label ID="lblSelectedLanguages" runat="server" Text=""></asp:Label>
</div>
</form>
This is my codebehind C#:
[System.Web.Services.WebMethodAttribute(), System.Web.Script.Services.ScriptMethodAttribute()]
public static string[] GetCompletionList(string prefixText, int count, string contextKey)
{
// Create array of languages.
string[] languages = { "Afrikaans", "Albanian", "Amharic", "Arabic", "Azerbaijani", "Basque", "Belarusian", "Bengali", "Bosnian", "Bulgarian" };
// Return matching languages.
return (from l in languages where l.StartsWith(prefixText, StringComparison.CurrentCultureIgnoreCase) select l).Take(count).ToArray();
}
protected void btnAddSelected_Click(object sender, EventArgs e)
{
lblSelectedLanguages.Text += txtLanguage.Text += ", ";
}
The selected language is added to the label when the button is clicked, however I would like to remove the button and make the selected item from the autocomplete added to the label automatically, using the partial postback from the Ajax toolkit.
Can someone please advise as to how I can achieve this?
Thanks.
Handle OnClientItemSelected on the AutoCompleteExtender control to run a javascript function
All the javascript does is simply fire off the TextChanged event when the selection is made (works on both Enter and left click)
ASPX:
<head runat="server">
<title></title>
<script type="text/javascript">
function ItemSelected(sender, args) {
__doPostBack(sender.get_element().name, "");
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</asp:ToolkitScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
Search our Languages:
<asp:TextBox ID="txtLanguage" autocomplete="off" runat="server" OnTextChanged="TextChanged" />
<asp:AutoCompleteExtender OnClientItemSelected="ItemSelected" ID="AutoCompleteExtender1"
runat="server" TargetControlID="txtLanguage" MinimumPrefixLength="1" ServiceMethod="GetCompletionList"
UseContextKey="True">
</asp:AutoCompleteExtender>
<br />
<asp:Label ID="lblSelectedLanguages" runat="server"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
Code behind:
protected void TextChanged(object sender, EventArgs e)
{
lblSelectedLanguages.Text += txtLanguage.Text += ", ";
}
It looks like you just need to hook onto the on text changed event of your text box and then put your logic in code benind.Something like this
Markup
<asp:TextBox ID="txtLanguage" OnTextChanged="txtLanguage_textChanged" AutoPostback="true" />
Then in your code behind
protected void txtLanguage_textChanged(object sender, EventArgs e)
{
//use the retrieved text the way you like
lblSelectedLanguages.Text =txtLanguage.Text;
}
Hope this helps.I would also suggest that you try looking into the JQuery autocomplete widget.It has brought me sheer happiness and I surely did divorce the autocomplete extender.
Jquery Autocomplete
For some reason, I cannot get text into any textbox or label!
I'm using Master pages and the code is going in the code behind view. I have created the textbox:
<asp:Textbox ID="whatever" runat="Server">
When I want to add some text I simply add the code in the code behind view like:
whatever.Text = "myText";
I get an error that says:
"System.NullReferenceException:Object reference not set to an instance of an object"
hightlighting this line in red: whatever.Text = "myText";
I guess its because it saying it not there but how can it let me reference the textbox?
Apologies if the answer is on the site, I have searched but found nothing. :)
This is my code in Basket.asp - I've changed the textbox to a label, it's called bskItems
<asp:Content ID="Content3" ContentPlaceHolderID="ContentPlaceHolder3" runat="server">
<asp:Label ID="bskItems" runat="server"></asp:Label>
<div id="cart">
<asp:Button ID="btnCheckout" CssClass="BasketBtnAdd" runat="server" CommandName="checkout" Text="Checkout" />
</div>
</asp:Content>
This is my masterpage, where I'm using a loginView. ContentPlaceHolder3 is where the textbox should be. I only want it to display a count of items.
<asp:LoginView ID="loginView" runat="server">
<LoggedInTemplate>
<asp:LoginName ID="loginName" runat="server" FormatString="Hi, {0}!"/>
(<asp:LoginStatus ID="loginStatus" runat="server" />)
<%
if (HttpContext.Current.User.IsInRole("Admin"))
{
%>
<asp:SiteMapDataSource ID="admin" SiteMapProvider="admin" runat="server" ShowStartingNode="false" />
<asp:Menu ID="Menu" runat="server" DataSourceID="admin">
<StaticItemTemplate>
<%# Eval("Text") %>
</StaticItemTemplate>
</asp:Menu>
<%
}
if (HttpContext.Current.User.IsInRole("Users"))
{
%>
<asp:SiteMapDataSource ID="user" runat="server" SiteMapProvider="user" ShowStartingNode="false" />
<asp:Menu ID="Menu1" runat="server" DataSourceID="user">
<StaticItemTemplate>
<%# Eval("Text") %>
</StaticItemTemplate>
</asp:Menu>
<%
}
%>
<asp:ContentPlaceHolder ID="ContentPlaceHolder2" runat="server"></asp:ContentPlaceHolder>
<asp:ContentPlaceHolder ID="ContentPlaceHolder3" runat="server"></asp:ContentPlaceHolder>
</LoggedInTemplate>
<AnonymousTemplate>
<asp:LoginStatus ID="loginStatus" runat="server" />
<asp:SiteMapDataSource ID="anon" runat="server" SiteMapProvider="anon" ShowStartingNode="false" />
<asp:Menu ID="Menu2" runat="server" DataSourceID="anon">
<StaticItemTemplate>
<%# Eval("Text") %>
</StaticItemTemplate>
</asp:Menu>
</AnonymousTemplate>
</asp:LoginView>
In addition to the other answers, if you're setting the value in Page.OnLoad, remember that the Master page controls haven't been created yet.
Here's a complete layout of the order in which things happen: Complete Lifecycle of an ASP Page
What I usualy do is to make the control visible as a property of my MasterPage.
On the master page (AMasterPage.master):
public TextBox MyTextBox { get { return this.theTextBoxControl; } }
So then, on a child using this masterPage (APage.aspx) :
((AMasterPage)this.Master).MyTextBox.Text = "myText";
When accessing Master Page members from Code-Behind in a Content Place Holder file, I believe you need to do:
this.Master.whatever.Text = "new Text";
Check this link on ASP.NET Master Pages, from MSDN.
You need to do get a reference to the textbox on the master page, then set the text
TextBox tb = Master.Page.FindControl("whatever") as TextBox;
if(tb != null)
{
tb.Text = "myText";
}
Set the ClientIDMode on the textbox to "Static". When the page is rendered it assigns the TextBox's ID to something random. By changing the ClientIDMode to "Static", you should be able to reference the ID because the ID will stay the same and not change.
Or try adding an OnDataBinding event handler and casting the "sender" as a (TextBox). For example:
protected void TextBox_OnDataBinding(object sender, EventArgs e)
{
var txt = (TextBox)sender;
txt.Text = "Something";
}
This should talk to the control directly.