Passing a value from a User Control to code behind - c#

I'm trying to pass a value from a User Control to a code behind without luck. I can write the correct value (IDuser_uc) on the aspx page but I can't pass it to the code behind. Any tips?
User Control
protected void FormView_IDuser_DataBound(object sender, EventArgs e)
{
Label IDuserText = FormView_IDuser.FindControl("IDuserLabel") as Label;
IDuser_uc = Convert.ToString(IDuserText.Text);
}
ASPX page
<uc4:IDuser id="IDuser" runat="server" />
<% Response.Write(IDuser.IDuser_uc); // Here correct value %>
Code Behind
protected void Page_Load(object sender, EventArgs e)
{
SqlDataSource_userConnections.SelectParameters["IDuser_par"].DefaultValue = IDuser.IDuser_uc ; // Here NO value
Response.Write("Connections :" + IDuser.IDuser_uc); // Here NO value
}
UPDATE
The problem was due to the fact that the User Control is run after the PageLoad which explains why I got an empty string. To solve the problem I used Page_PreRender instead of Page_Load on the code behind page.

Create a public method in your user control. When you post back the page have the Parent.aspx page call the user control method. Example....
In your User Control:
Public string GetUserControlValue()
{
return Label IDuserText;
}
In your Parent ASPX Pgae
var UserControlString = IDuser_uc.GetUserControlValue();

Related

Label Text Not Showing Outside of Page_Load

I have a Grid and on top of the grid, I like am showing a label as such:
<asp:Label ID="lblMsg" runat="server" ForeColor="Red"></asp:Label>
On delete of a row in my grid I have the following code:
protected void RadGrid1_DeleteCommand(object sender, GridCommandEventArgs e)
{
if (!(User.IsInRole("Administrator")))
{
lblMsg.Text = "Must be an Admin in delete.";
return;
}
NOTE: The debugger does go to where I have the label text displayed but it simply does not display on the page. :
lblMsg.Text = "Must be an Admin in delete.";
NOTE: If I have the same code in the page load, the label text shows up fine on the page Also DO NOT have (!IsPostBack){} in my code.
Therein lies your issue. When your page is posting back the label is getting assigned the value:
lblMsg.Text = "Must be an Admin in delete.";
But Page_Load gets called again. So your Page_Load should look like this
protected void Page_Load(object sender, EventArgs e) {
if(!IsPostBack) {
//Populate my page
}
}
This will hold true for almost every page you write in ASP.NET

Load usercontrol on postback and load data based on parent page textbox value c#

This is probably really simple, but I cant seem to get my values picked up at all from the parent page?
Aspx page is within a master page and ContentPwith the code for example
<asp:Content ID="Content3" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:TextBox ID="tbFromDate" runat="server" ></asp:TextBox>
<asp:Button ID="butDisplayInfo" runat="server" Text="Display info" OnClick="butDisplayInfo_Click"
CssClass="button-gray" />
<asp:PlaceHolder ID="placeHolderContent" runat="server">
</asp:PlaceHolder>
What I want is when the button is pressed it loads the UserControl and loads data based on the date put in the text box which I can then use to load data to the control?
.aspx.cs
protected void butDisplayInfo_Click(object sender, EventArgs e)
{
var ctrl = LoadControl("~/Controls/DailyShiftStats.ascx");
ctrl.ID = "ucUserCtrl1";
placeHolderContent.Controls.Add(ctrl);
}
Usercontrol ascx.cs
protected void Page_Load(object sender, EventArgs e)
{
TextBox tb = (TextBox)this.Parent.Page.FindControl("ContentPlaceHolder1").FindControl("tbFromDate");
Response.Write(tb.Text);
}
public void getShiftInfo(DateTime shiftDate)
{
//load my data
}
As per my comment - you would be better defining a property in your control and then have the page pass this in, I have not done this in a while but the basic idea is -
In your control
public DateTime? ShiftDate
{
set { this.shiftDate = value; }
}
private DateTime? shiftDate;
Then you can use shiftDate anywhere in your control where it is needed, if you make it Nullable as above then you can check to see if it has been set and throw an error (or whatever is appropriate) if not.
In your page when creating your control you would then have (Note: you need to cast your control to correct type)
var ctrl = (DailyShiftStats)LoadControl("~/Controls/DailyShiftStats.ascx");
ctrl.ID = "ucUserCtrl1";
//TODO: Handle an invalid date
DateTime shiftDate;
if (DateTime.TryParse(tbFromDate.Text, out shiftDate))
{
ctrl.ShiftDate = shiftDate;
}
placeHolderContent.Controls.Add(ctrl);

asp.net normal html input runat="server" return non-updated value in code-behind

I have edit server detail page called editServer.aspx. On page load, I retrieve data from database and set value to textbox. When user clicks save button, the value from textbox is empty or not updated to new value that users key in.
part of code in .aspx
<input type="text" class="form-control" id="serverRemarksTB" name="serverRemarksTB"
placeholder="general server remarks" runat="server"/>
<asp:Button ID="editPhysicalServerBtn" runat="server" Text="Save" class="btn btn-success"
style="padding-left:30px; padding-right:30px;" onclick="editPhysicalServerBtn_Click" />
in .aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
//code to retrieve data from database and store in server instance
serverRemarksTB.Value = server.remarks;
}
protected void editPhysicalServerBtn_Click(object sender, EventArgs e)
{
string remarks = serverRemarksTB.Value; //this is not updated.
}
For example, in database the server remarks is "do not shutdown". So when I open the .aspx page, I will see the textbox with "do not shutdown". When I change the value to "can shutdown" and click Save button, in aspx.cs server remarks value remains the same - "do not shutdown".
It's because everytime you load the page you override the value of the input with this line of code...
serverRemarksTB.Value = server.remarks;
and based on the ASP.NET Pipeline Lifecycle, Page_Load is executed first and then controls' event handlers. To avoid that you will need to run the above mentioned line of code only when the page first load...on a GET request and not on a POST request. You can change the Page_Load event handler like this...
protected void Page_Load(object sender, EventArgs e)
{
//code to retrieve data from database and store in server instance
if(!IsPostBack)
serverRemarksTB.Value = server.remarks;
}
Use IsPostBack clause or every time your page loads your textbox will be populated from database value .
When you click save button , it causes postback which causes your serverRemarksTB value again to
"do not shutdown".
if(!Page.IsPostBack)
{
serverRemarksTB.Value = server.remarks;
}
That's because your page_Load serverRemarksTB.Value = server.remarks;code is not wrapped in IsPostback block. So when you post your form back the value of the text box gets updated to database value. You should put your database code inside IsPostback check. Like
if(!IsPostBack)
{
serverRemarksTB.Value = server.remarks;
}
in the Page_Load method.

DropDownList not accepting the SelectedIndex im trying to assign

I'm having a hard time figuring this out and I hope you guys would help me.
I have a page called Index.aspx with a DropDownList that is a separate UserControl class (because it will be used in other pages). Here's the code for that:
UcSelecionarLocal.ascx:
<%# Control Language="C#" AutoEventWireup="true"
CodeBehind="UcSelecionarLocal.ascx.cs"
Inherits="QuickMassage.uc.UcSelecionarLocal" %>
<asp:DropDownList ID="ddlLocais" runat="server"
CssClass="span4 dropdown-toggle" AutoPostBack="true">
</asp:DropDownList>
UcSelecionarLocal.ascx.cs:
public partial class UcSelecionarLocal : UserControl {
protected void Page_Load(object sender, EventArgs e) {
if (!this.IsPostBack) {
PreencherLocais();
}
}
private void PreencherLocais() {
ddlLocais.Items.Clear();
ddlLocais.Items.Add(new ListItem("Selecione", "0"));
ControleLocal controle = new ControleLocal();
DataTable tab = controle.ListarLocais();
foreach (DataRow row in tab.Rows) {
ddlLocais.Items.Add(new ListItem(row["Descricao"].ToString(),
row["ID"].ToString()));
}
}
}
This control is placed in Index.aspx and loads its values correctly. The form that it's contained in, has the action set to agendamentos.aspx. When I change the ddlist, the page is submitted to the forms action page, as it should be.
On the other page the problems begin: I get the parameters posted to this page and one of them is the ddlist value. In the immediate window, I check the value and it's there, let's say that it is 1.
To make long story short, I have this code:
agendamentos.aspx.cs:
protected void Page_Load(object sender, EventArgs e) {
DropDownList locais = ObterComponenteListaLocais();
try {
locais.SelectedIndex =
int.Parse(HttpContext.Current.Request["ucSelLocal$ddlLocais"]);
}
While debugging, I see that locais.SelectedIndex is -1. After the assignment it remains -1. The page loads and then I change the ddlist value again to 2. When debugging the same code above, I see that the locais.SelectedIndex is now 1. Again, setting it to 2, as it would normally be, produces no effect. If I change the ddlist again to 3, the SelectedIndex becomes 2 and does not take the value 3.
In other words: the value of the index in a newly loaded page is the value of the page that was loaded before.
Could you guys help me?
This is because the Page_Load event is firing in your page before the user control is loading. Do this:
public partial class UcSelecionarLocal : UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
public void PreencherLocais()
{
ddlLocais.Items.Clear();
ddlLocais.Items.Add(new ListItem("Selecione", "0"));
ControleLocal controle = new ControleLocal();
DataTable tab = controle.ListarLocais();
foreach (DataRow row in tab.Rows)
{
ddlLocais.Items.Add(new ListItem(row["Descricao"].ToString(), row["ID"].ToString()));
}
}
}
Then in your aspx page:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
this.idOfYourUserControl.PreencherLocais();
DropDownList locais = ObterComponenteListaLocais();
try {
locais.SelectedIndex =
int.Parse(HttpContext.Current.Request["ucSelLocal$ddlLocais"]);
}
}
Also because your question is a little confusing, an important note is that Page_Load fires before data is captured from controls that post back data. So that's a bad place to get their information because it will be what it was previously. That's why you need to create a function that fires on something like a button click that will execute after the controls data have been loaded.

Trouble getting a master page control in a page that uses it

I have a Label in my mater page which i want to access in a page which uses the same mater page.
I tried..
string text = ((Label)Master.FindControl("myLabel")).Text; //Always returns empty string
P.S i have included <%# MasterType virtualpath="~/Masters/Master1.master" %>
still not working
As Waqas Raja mentioned in comments, the problem is in event sequence: master's Load event occurs after page's Load event. So you could just use Page.LoadComplete event in your page:
protected void Page_LoadComplete(object sender, EventArgs e)
{
string text = ((Label)Master.FindControl("myLabel")).Text;
}
and it should give you desired value of the textbox.
i thing you label in master page reside in content place holder. so
ContentPlaceHolder mpContentPlaceHolder =
(ContentPlaceHolder)Master.FindControl("ContentPlaceHolder1");
string TextBoxvalue =
((TextBox) mpContentPlaceHolder.FindControl("TextBox1")).Text;

Categories

Resources