autofill textbox based on user input - asp.net

I'm extremely new to ASP.NET and came across a problem I have yet to figure out. On my Default.aspx page, I have a place where users can signup. This just takes to fields - Email and Password. When the submit button is clicked, they are taking to Signup.aspx, which shows a bigger signup form with fields for username, email, password, confirm password, etc. I would like to auto fill my email and password textboxes with those of the Default.aspx page that the user has entered. Is this possible? I'm using Microsoft Visual Web Developer 2010 Express.

There are multiple ways to do that.
One way is to use querystring to navigate to like :
http://example.com/Signup.aspx?email=value1&password=value2
and get value on Signup.aspx Page_Load event like :
String email = Request.QueryString["email"];
String password = Request.QueryString["password"];
and assign to your text box controls like:
txtEmail.text =email;
txtPassword=password;
But posting password as clear text in query string is not good practice.
Other way is to get HTTP POST information from the source page:
In the source page, include a form element that contains HTML elements (such as input or textarea) or ASP.NET server controls (such as TextBox or DropDownList controls) that post values when the form is submitted.
In the target page, read the Form collection, which returns a dictionary of name/value pairs, one pair for each posted value. e.g.
//
void Page_Load(object sender, EventArgs e)
{
System.Text.StringBuilder displayValues =
new System.Text.StringBuilder();
System.Collections.Specialized.NameValueCollection
postedValues = Request.Form;
String nextKey;
for(int i = 0; i < postedValues.AllKeys.Length; i++)
{
nextKey = postedValues.AllKeys[i];
if(nextKey.Substring(0, 2) != "__")
{
displayValues.Append("<br>");
displayValues.Append(nextKey);
displayValues.Append(" = ");
displayValues.Append(postedValues[i]);
}
}
Label1.Text = displayValues.ToString();
}
Best & easiest I think is to use Session:
on Submitbutton_click event of Default.aspx, save values to Session like:
Session["Email"] = txtEmail.text;
Session["Password"]=txtPassword.text;
and retrieve values on Signup.aspx Page_load event like:
string email = (string)(Session["Email"]);
string password = (string)(Session["Password"]);
& assign to your control/textbox like:
txtEmail.text =email;
txtPassword=password;
There are more ways too to retrieve value from previous page like PreviousPage.FindControl("txtEmail") but I never like them.

Related

How to retrieve TextBox value in ViewState from its ID

I am building many textboxes programmatically in my ASP.NET page, after I've clicked a button, I would like to process those values, is there any possibility to retrieve them from their ID in ViewState ?
Here is my code :
Reference of the table in the aspx :
<asp:Table ID="Distances" runat="server" ViewStateMode="Inherit"></asp:Table>
Then in code behind after creating all the rows and cells, I add a textbox into some of them :
Distances.Rows[j].Cells[i].Controls.Add(CreateTB(distance.ToString(), (i + j * rows).ToString(), false));
protected TextBox CreateTB(string text, string id, bool ebanled = true)
{
TextBox tb = new TextBox() { Text = text, ID = id, Enabled = ebanled};
tb.TextChanged += new EventHandler(OnTBChanged);
return tb;
}
ViewState is enabled by default, so it should already work that the Text property is persisted across postbacks.
So you could for example use FindControl("TextBoxID") or enumerate them to get the refernce to the TextBox (assuming that they are added to a container-control like Panel):
foreach(TextBox txt in MyPanel.Controls.OfType<TextBox>())
{
String text = txt.Text;
}
or
TextBox txt = (TextBox)MyPanel.FindControl("TextBox1")
String text = txt.Text;
I assume you're not recreating those TextBoxes on postbacks. Therefore you need to use the same ID as before and recreate them in Page_Load at the latest stage in page's life-cycle. So you can create them in an event, but you cannot recreate them there.
You should show your code where you create them dynamically, then i could be more specific.
TRULY UNDERSTANDING DYNAMIC CONTROLS

Load User control with Query string

My requirement is like i need to load a n number of user controls using asp Repeater.
List<string> userControlList = new List<string>();
userControlList.Add("~/WebUserControl2.ascx");
userControlList.Add("~/WebUserControl.ascx");
Repeater1.DataSource = userControlList;
Repeater1.DataBind();
And in the ItemDataBound, I am loading the user control using Page.LoadControl.
string userControlLink = e.Item.DataItem.ToString();
e.Item.FindControl("ItemPanel").Controls.Add(Page.LoadControl(userControlLink));
Here, I need to send parameters to some user control by which the control will be loaded.
I am not able to use properties because i can't type cast it at run time.
Is there any other way by which i can send some parameters to user control?
I tried with query string, but it resulted in run time exception.

Passing querystring with login control in asp.net 4?

Scenario:
I am doing project in C# ASP.NET 4.
I have a page of question. When somebody clicks on question (ie a Link Button) he is redirected to page where user can give answer but first he needs to login. So I put Login to Answer button that redirects user to GuestLogin.aspx with question id like this :
protected void LoginToAnswwer_Click(object sender, EventArgs e)
{
int qidrequest = int.Parse(Request.QueryString["qid"]);
Response.Redirect("~/GuestLogin.aspx?qid=" + qidrequest);
//This is working OK
}
And then when I am redirected to GuestLogin.aspx, I am putting below code in LoginButton of built in Login Control.
protected void LoginButton_Click(object sender, EventArgs e)
{
int qidrequest = int.Parse(Request.QueryString["qid"]);
Response.Redirect("QDisplay.aspx?qid=" + qidrequest);
}
Which is not working.
Question:
How to pass querystring with login button of built login control in asp.net 4 ?
You could pass a return URL to the login page, like this:
Response.Redirect(String.Format("/auth/login.aspx?return={0}", Server.UrlEncode(Request.Url.AbsoluteUri)));
In the login page, after authenticating the user:
Response.Redirect(Request.QueryString["return"]);
Pass Parameters from One Page to Another Page using QueryString :
//Set the Querystring parameters
Note: Maximum length of the
string that can be passed through QueryString is 255.
string URL =“QueryString.aspx?Name=” + txtFirstName.Text + “&Address=” + txtAddress.Text + “&City=” + txtCity.Text ;
//After Setting the Querystring Paramter values Use Response.Redirect to navigate the page
Response.Redirect(URL);
In the Page Load Event of the Navigated
Page,You can access the querystring parameter values like below :
lblName.Text = Request.QueryString["Name"].ToString();
lblAddress.Text = Request.QueryString["Address"].ToString();
lblCity.Text= Request.QueryString["City"].ToString();
That's how you have to use QueryString for passing parameters

to display username on all aspx pages

How to Dispaly the username on all aspx pages....?
Can any one help me in this context.....
am thinking that by using "session object" we can able to do this...bt am not sure
Can any send the code or links
Assuming that you have a mechanism you can use to obtain the current user's username, you could fetch that and add code to your master page(s) to display the name. There's not really much more that can be said from your question. (Ask a vague question, get a vague answer.)
And also, if you aren't using master pages, you should be using master pages.
You can use a master page if you want to display the username on all pages.
Username can be stored in a cookie, session, etc.
Code sample:
lblUsername.Text = Session["Username"]
System.Security.Principal.IPrincipal user;
user = System.Web.HttpContext.Current.User;
System.Security.Principal.IIdentity identity;
identity = user.Identity;
lblUserName.Text = identity.Name.Substring(identity.Name.IndexOf(#"\") + 1); ToString();
In First Page (Login page), store the value in Session
Session["Username"] = txtusername.text;
And rest of the pages, where you want to display the UserName
lblUser.Text = Session["Username"].Tostring();
For Logout
Session["Username"] = null;

Asp.Net on refresh, a duplicate post is inserted...should only be one post

I have a asp:textbox that allows a user to enter information. When the user clicks the asp:button, it inserts the text from the textbox into my sql database, and then redirects back to the page. If the user hits refresh, the event from the button gets called again. I need to rectify this so that it no longer gets called or it doesn't repost the information.
protected void PostButton_Click(object sender, EventArgs e)
{
if (txtWallPost.Text.Length > 0)
{
string strCon = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["SocialSiteConnectionString"].ConnectionString;
using (SqlConnection conn = new SqlConnection(strCon))
{
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "INSERT INTO [WallTable] ([UserId], [FriendId], [WallPost]) VALUES (#UserId, #FriendId, #WallPost)";
cmd.Parameters.AddWithValue("#UserId", User.Identity.Name);
cmd.Parameters.AddWithValue("#FriendId", User.Identity.Name);
cmd.Parameters.AddWithValue("#WallPost", txtWallPost.Text);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
txtWallPost.Text = "";
LoadWallPosts();
Response.Redirect("~/UserPages/UserProfile.aspx?view="+"wall");
}
}
}
return;
}
Classic problem, with a classic solution: Redirect After Post. You just need to redirect the user to another page (or the same page...) after processing the POST - that way when they hit refresh, the last request (and the one to be repeated) will be a GET.
See:
Refresh the page after a postback action in asp.net
How do I use the “Post/Redirect/Get” a.k.a. “Redirect after Post” with asp.net
Page Refresh Causes Duplicate POST in ASP.NET Applications
Curing the “Back Button Blues”
I ended up just adding a session id for the wall post text. In the post method, it checks to make sure the textbox text, is different from that of the session text. On refresh it clears out the session and therefore works fine.

Resources