Pass Values from a user control to a web form

Hi All, 

I am currently trying to add captcha to my webform.

I have a question on how to pass a number/string from a .ascx to a .aspx page.

The aspx is being used in the .ascx (user control) in an image tag.

<asp:Image ID="imgCaptcha" runat="server" ImageUrl="Image.aspx"/>

The aspx page is being rendered as a jpeg image. So Inorder for the captcha to be displayed with the image, I need to pass the code from the user control to the aspx page.

I have an option to pass the number as a query string or use it in session. But is there any other alternative?

I have tried another option by creating a public property  for the number getting generated and accessing the code in my aspx.

Thanks in advance

Regards

Sri

 


Regards
Sridhar

Please Mark the Posts as Answered if they solve your question :)
0
badri_95
3/31/2009 6:06:45 AM
asp.net.web-forms 93655 articles. 5 followers. Follow

11 Replies
1014 Views

Similar Articles

[PageSpeed] 7

Hi,

Assume there is a user control called UC and there is only a TextBox control inside it. Now drag this user control into a web page, you can use the following code to visit the TextBox control.

((TextBox)UC1.FindControl("TextBox1")).Text = "demo";

Hope It helps

 


Thanks
Avinash Tiwari

Remember to click “Mark as Answer” on the post, if it helps you.
0
qwe123kids
3/31/2009 6:13:22 AM

hi,

Check my blod entry http://codeasp.net/blogs/joydeep157/microsoft.net/80/exposing-usercontrol-events-in-your-page

Also exposing public property in usercontrol and set/get them from the aspx page is another sollution.

badri_95:
I have tried another option by creating a public property  for the number getting generated and accessing the code in my aspx.

 

So, is that not working? What is the problem?


Joydeep Sen
Dotnet Developer

Dont forget to click “Mark as Answer” on the post that helped you.
This credits that member, earns you a point and mark your thread as Resolved for the sake of Future Readers


0
joydeepsen
3/31/2009 6:15:35 AM

Hi,

Thanks for your response, But for the above to work, we have to register the usercontrol in the aspx. Please correct me if I am wrong.

The user control is loading this (.aspx) webpage in a image control. so there is a number that I am generating in my ascx which needs to be passed to this child aspx page.

my user control is being used in a web part.

Any suggestions?

Thanks


Regards
Sridhar

Please Mark the Posts as Answered if they solve your question :)
0
badri_95
3/31/2009 6:19:43 AM

Hi Joy,

I have tried creating a public property for my hidden field which contains the generated number. After the page_load for the ascx is completed the control gets implicitly transferred to the child aspx page. In this child aspx page I want the generated number to be available.

But when I try to access the property by instantiating the ascx class, it gives null and an exception is thrown.

I have already tried out query string and session. Both work fine but are not suitable for my scenario :(

Thanks again


Regards
Sridhar

Please Mark the Posts as Answered if they solve your question :)
0
badri_95
3/31/2009 6:25:37 AM

Any suggestions on how to pass a value from parent ascx to child aspx without the use of session or query string?

Thanks


Regards
Sridhar

Please Mark the Posts as Answered if they solve your question :)
0
badri_95
3/31/2009 8:17:30 AM

How are you loading the UserCOntrol? Did you drag it or dynamically loading it using LoadControl method?

If possible kindly post your code so that we can reproduce the error and we might find some sollution.

Thanks


Joydeep Sen
Dotnet Developer

Dont forget to click “Mark as Answer” on the post that helped you.
This credits that member, earns you a point and mark your thread as Resolved for the sake of Future Readers


0
joydeepsen
3/31/2009 8:19:42 AM

Hi Joy,

there is no error as such. My code is working fine with sessions and query strings.

I have to display the user control in sharepoint page.So I am using a smart part to display this control in the Sharepoint page. 

#region Ask RD Class Definition

public partial class Providers_AskRD : System.Web.UI.UserControl

{

private string strCode;

Property to access the text box code 

public String Code

{

get

{

return txtCode.Text;

}

}

private Random random = new Random();

protected TextBox CodeNumberTextBox = new TextBox();

protected TextBox txtCode = new TextBox();

protected Label MessageLabel = new Label();

protected TextBox txtEmailAddress = new TextBox();

protected TextBox txtFirstName = new TextBox();

protected TextBox txtMemberID = new TextBox();

protected TextBox txtTelephoneNumber = new TextBox();

protected TextBox txtYourQuestion = new TextBox();

protected RadioButtonList rblNickName = new RadioButtonList();

protected DropDownList ddlCountry = new DropDownList();

protected System.Web.UI.WebControls.Image imgCaptcha = new System.Web.UI.WebControls.Image();

public HiddenField hdCaptchaValue=new HiddenField();

public string s;



#region Page Load event 

protected void Page_Load(object sender, EventArgs e)

{





if (!this.Page.IsPostBack)

{

hdCaptchaValue.Value = GenerateRandomCode();

strCode = hdCaptchaValue.Value;

txtCode.Text = hdCaptchaValue.Value;


imgCaptcha.ImageUrl = "JpegImage.aspx";
}

else

{



if (this.CodeNumberTextBox.Text == Convert.ToString(hdCaptchaValue.Value))

{

// Display an informational message. 


this.MessageLabel.CssClass = "info";
this.MessageLabel.Text = "Correct!";

}

else

{

// Display an error message.

this.MessageLabel.CssClass = "error";

this.MessageLabel.Text = "ERROR: Incorrect, try again.";

// Clear the input and create a new random code.

this.CodeNumberTextBox.Text = "";

hdCaptchaValue.Value = GenerateRandomCode();

strCode = hdCaptchaValue.Value;

imgCaptcha.ImageUrl = "JpegImage.aspx;

}

}

}

#endregion

#region

private string GenerateRandomCode()

{

string strCode = "";

for (int i = 0; i < 6; i++)

strCode = String.Concat(strCode, this.random.Next(10).ToString());

return strCode;

}

#endregion

}

#endregion

//JPEG Image Code
private void Page_Load(object sender, System.EventArgs e)
        {
            try
            {
                if(bFlag ==false)
                {
                    Providers_AskRD oProvidersAskRD = new Providers_AskRD();
                    //Here I have to get the textbox value set during the page load of ascx
                    //But I get null here
                    string strCode=oProvidersAskRD.Code;
                    // Create a CAPTCHA image using the text stored in the Session object.
                    CaptchaImage1 ci = new CaptchaImage1(Convert.ToString(strCode), 200, 50, "Century Schoolbook");

                    // Change the response headers to output a JPEG image.
                    this.Response.Clear();
                    this.Response.ContentType = "image/jpeg";

                    // Write the image to the response stream in JPEG format.
                    ci.Image.Save(this.Response.OutputStream, ImageFormat.Jpeg);
                    bFlag = true;
                    
                    //providers.hdCaptchaValue.Value=Convert.ToString(strCode);
                    // Dispose of the CAPTCHA image object.
                    ci.Dispose();
                
                }
            }
            catch (Exception ex)
            {

            }
        }
Thanks in Advance
 
Regards
Sridhar

Please Mark the Posts as Answered if they solve your question :)
0
badri_95
3/31/2009 8:30:10 AM

badri_95:

Any suggestions on how to pass a value from parent ascx to child aspx without the use of session or query string?

Thanks

Based on your description, It seems that you want to get the Captcha from User control in parent page. If in this case, I suggest you expose a public property in user control for calling by others. Such as:

    private string _strCaptcha;
    public string StrCaptcha
    {
        get {
            return (ViewState["Captcha"] == null) ? string.Empty : ViewState["Captcha"].ToString(); 
        }
        set
        {
            ViewState["Captcha"] = value;
        }
    }
 

Gary yang - MSFT
Microsoft Online Community Support

Please remember to mark the replies as answers if they help and unmark them if they provide no help.
0
Gary
4/2/2009 4:50:42 AM

Hi Gary,

It appeared far too complex to use a user control. So we have decided to use a aspx page instead.

Source Page:

Public Property 

public
string JpegCode

{

get

{

//hdCaptchaValue is a hidden control where I am storing the value that must be passed to JpegImage.aspx page.

return Convert.ToString(hdCaptchaValue.Value);

}

}

Page Load event

if (!this.Page.IsPostBack)

{

hdCaptchaValue.Value = oGenerate.GenerateRandomCode();

imgCaptcha.ImageUrl =
"JpegImage.aspx;

}

Child Page (JpegImage.aspx)

In the aspx, I have added this PreviousPageType tag to add a reference to the Members Parent Page

<%@ PreviousPageType VirtualPath="Members.aspx" %>

JpegImage.aspx.cs

if (Page.PreviousPage != null)

{

string str = PreviousPage.JpegCode;

}

The PreviousPage object is always null. Not sure where am I going wrong :(

Any suggestions?

Thanks


Regards
Sridhar

Please Mark the Posts as Answered if they solve your question :)
0
badri_95
4/6/2009 11:02:31 AM

.


Regards
Sridhar

Please Mark the Posts as Answered if they solve your question :)
0
badri_95
4/6/2009 11:04:10 AM

badri_95:
The PreviousPage object is always null. Not sure where am I going wrong :(

Based on my ecperience, I suggest you set PostBackUrl property so as to make the PreviousPage class is not null. Such as:

//Parent

<asp:Button ID="btPostBack" runat="server" Text="Button" PostBackUrl="~/PostBackDemo/RequestUrl.aspx" />
//Child
<%@ PreviousPageType VirtualPath="~/PostBackDemo/ResponseUrl.aspx" %>
 

Gary yang - MSFT
Microsoft Online Community Support

Please remember to mark the replies as answers if they help and unmark them if they provide no help.
0
Gary
4/7/2009 5:55:28 AM
Reply:

Similar Artilces:

Passing Values from a Web Form to Another Web Form
Hello All! I am trying to pass values from one web form to another web form. I know that there are 3 ways of doing this: queryString, Server.Transfer and Session. I am using the Server.Transfer method. But I am not able to create, in my 2nd web form, an instance of my 1st web form. My 1st Web form is named CallTrack.aspx and my 2nd is named Export.aspx. What I mean is something like this: Public value as CallTrack. I can't create it in my 2nd web form because when the intellisense is displayed, there's no CallTrack in the options. Thanks!   How about using cross-...

Pass data from Web User Control to Web Form
I have a Web Form that contains a Web User Control. The WUC displays dynamic content. I want to change the TITLE property of the Web Form, based on the contents of the WUC. For example, if the WUC displays information about Horses, I want to change the page title to "HORSES" by passing the string to the parent Web Form. I have tried playing with parameters and such, but I can't remember how I did this in the past. PLEASE HELP!~o0 Spin-Monkey Oo~ The best way to do this is by creating a public property on your web user control and accessing that from your web form. Check ...

Retreiving a value from a web form within a web user control
Hi  I have a page (web form) that retreives some data from a database. To be more specific: at some point when user clicks a button (in the web form) there is some ID number retreived from a database in code behind. At the same time the Visible property of the nestet web user control is chamged to true. I want than forward the ID to the web user control so that a grid view can load data from a database for that ID. How can I access that data (the ID) within a web user control context nested in that page?  Kind regards   Check this ;ink  http://www.codeproject.com/K...

Web Form and Web User Control
Hello, I have a Web User Control (ascx) that includes a button. This button has an onclick event method. This Web User control is included into a Web Form. (thru LoadControl). However, when I click on the button, the event method is not executed. What should I include in order it works fine? Thanks in advance. GAA. Using Loadcontrol is using dynamic controls and when using dynamic controls you must recreate the same dynamic controls ono postback to econstruct the page control tree. It is best if you do this during the Page PreInit event. How complex are your controls ...

How to access a control on a web form from anoter web form
hi all I have this scenarios i have two web forms, one called form1 and the other called form2 form1 has a label with id "lbl1" is it possible to access lbl1 from form2, change its text permenantly? thanks.   refer: http://dotnetslackers.com/Community/blogs/haissam/archive/2007/11/26/ways-to-pass-data-between-webforms.aspxSSNPlease remember to click "Mark as Answer" on the post that helps you. MinaSamy: hi all I have this scenarios i have two web forms, one called form1 and the other called form2 form1 has a label with id "lbl1" is it p...

Clearing Web Controls Values from a Web Form
I have a web form and after a user submit it I want to clear the form so that they may submit another entry. I have seen examples in VB of how to loop thru a web form and clear the controls, but I need a C# solution. I have tried the following code, while it does not give me an error, it does not clear the controls on the form. Any suggestions? Thanks! foreach (Control parent in Page.Controls)         {             foreach (Control child in parent.Controls)           ...

custom web user control and web form
Guys,          I am trying to develop a context menu control for all of my pages. what i am trying to do is that i want the control to pick a datasource from the markup and then check whether its an xml file or a datatable. I created a class called datasource.   /**************************DataSource Class****************************/  public class DataSource { /// <summary> /// This is to identify unique elements from the markup /// </summary>protected string _ID; /// <summary> /// This will be the Datasource ID e...

Web User Control Not rendering in Web Form
I have created a Web User control that is made up of a Multiview with 2 views inside the Multiview. I have buttons on both views and a gridview on 1 view. My question is when I drop this Web User Control on a Web Form all I see is [MultiView"MultiView1"] and when I view the from in the browser I dont see the Web User Control. I was wondering if someone could please tell me why the Web User Control is not displaying or rendering.     Thanks In Advance Hi, Please check your aspx file for correct reference, like following example: TestControl.ascx:<%@ Control ...

Solution for web forms that look just like paper forms ? User controls ? Adobe fillable forms ?
 I am looking at ways to web-enable a series of company forms that need to have the form itself look just like the paper version.  It would be great if I could use an image of the form itself as a background, and then draw the UI components on top of this.  Then there is the question of printing these forms complete with the data that was filled in.   What are some options for doing this kind of application ?  Im open to 3rd party solutions as well.  Our company currently has a desktop application which does this, but I want to come up with a web based solu...

Interaction between Web User Control & Web form
Ok, I want to create my first Web User Control which is used for file uploading. It's very simple, consist only of the <asp:FileUpload> and <asp:Button> control. The button has one server side event which is resizing the uploaded image to two different images (stored as byte[] in the cs file). So, my question is how I can send these two arrays of type byte to the Web form where the web user control is inside. I thought it should be possible to write something like this in the Web form:<uc1:FileUploader ID="uploader" runat="server" OnUploaded="recieveImages" />So that means ...

validate Textbox in Web User Control from web form?
ASP.NET 2.0 I have a web user control that contains a textbox.  I need to add some validation (like requiredfieldvalidator, comparevalidator, etc). I would normally add the validator to my web user control by placing the validator next to my textbox.  However, I need the validation message somewhere else on my web form, not near the user control. So how would I associate a validation control on my web form with the text box inside my web user control?  Can this be done; any alternatives out there? Thanks!   The error message should occur wherever you place the vali...

Access SqlDataSource on Web Form from a Web User Control...
Hello, I want to access a SqlDataSource on a Web Form fromout. a Web User Control. To do this, I have in my code behind of the Web User Control the folowing code: DropDownList1.DataSource = (this.Page.FindControl("SqlDataSource3") as SqlDataSource);DropDownList1.DataTextField = "Name;DropDownList1.DataValueField = "NameIDropDownList1.DataBind(); But, the control (ic. SqlDataSource3) is not found. Even other controls like labels and buttons are not found with the FindControl. What am I doing wrong? Thanks Andromedaris     This is not much of a surprise,...

Access a Web User Control Method from a Web Form
I'm trying to pass the Selected Index value from a web user control in a web form to the user controls selectedIndexchanged Sub.  I can't seem to figure out how to pass the information that I need to the user control and have it execute the sub routine. In the SelectedInedxChanged Sub I have a switch Statement and I want to get the index value from the web form where the user control is located and compare it to each case and then to have it execute the code for the case that it matches. What do I need to do? Hi, I am not sure if I understood your question correctly. I su...

Web forms and mobile web forms
Hey everyone, I am looking to develope a web site that depending on the device connecting to it, it will display a certain page. In this case im looking to create a web and wap version of the same project. I have the Web forms version finished using ASP.NET and C# and I am wondering how to create the mobile web form and incorporate it in the project. In the project folder, can I just add a mobile web??? But what about displaying device specific pages?? Cheers -Dudach Yes, you can add mobile web forms and controls to your Web Application project. No problem. For device/br...

Web resources about - Pass Values from a user control to a web form - asp.net.web-forms

Control - Wikipedia, the free encyclopedia
Text is available under the Creative Commons Attribution-ShareAlike License ;additional terms may apply. By using this site, you agree to the ...

Control chaos while Devouring Stars in this strategy game
Devouring Stars Control chaos while Devouring Stars in this strategy game is a story by AppAdvice.com AppAdvice - iPhone, iPad, iPod, App Reviews ...

Nuance’s voice control going where Siri, Google Now and Cortana fall short
... for Samsung's S Voice and Apple’s Siri, is ready to go where no other digital assistant has gone before. The company wants to bring voice control ...

EU Acts on Refugees, Terrorism With Tougher Border Controls
Beset by the refugee crisis and fears of terrorism, the European Union floated plans to stiffen its external border controls for Europeans and ...

Sandy Hook parents assess victories, defeats in gun control mission
CBS News Sandy Hook parents assess victories, defeats in gun control mission CBS News NEWTOWN, Conn. Three years ago on Monday, a gunman opened ...

Apple is about to take even more control
... be about to get tough for some Apple partners as the company invests in top secret display technology development labs and increases its control ...

Google Updates BigQuery With New Cost Controls
Enterprises using BigQuery to run analytics against large data sets can now set a daily query quota on a project-wide or an individual basis. ...

After losing control of Parliament, Venezuelan socialists create a new one
After losing control of Parliament, Venezuelan socialists create a new one

Battle to control key Taiwan chip group
ASE makes $4bn takeover offer for local rival to thwart approach by China’s Tsinghua Unigroup

Anti-Terror: Visa Control, Airstrikes Seen as Most Effective
Americans are most likely to see overhauling the nation's visa waiver program and intensifying airstrikes against the Islamic State as effective ...

Resources last updated: 12/17/2015 7:26:16 AM