How to pass parameters from one page to another? - c#

I have the following code behind:
public partial class _Default : System.Web.UI.Page
{
List<GlassesCollection> gc= BL.Example.GetCategory() ;
protected void Page_Load(object sender, EventArgs e)
{
rpt1.DataSource = gc;
rpt1.DataBind();
}
protected void rpt1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
Button btn = (Button)e.Item.FindControl("btn1");
btn.CommandArgument = DataBinder.Eval(e.Item.DataItem,"CollectionID").ToString();
}
}
I want to pass the content of the btn.CommandArgument to Label's event that placed in another ASPX.CS file.
Is there any way to implement this?
Thank you in advance!

You need to use Session. Put value in Session and read it in another page.
Session["key"]=value;

You can use QueryStrings. For example, your url will can look like:
string url = String.Format("http://www.example.com/somepage.aspx?labeltext={0}",btn.CommandArgument);
Then, in your somepage.aspx, you can have:
//"labeltext" is the same name we used above as the ID
string lblText = Request.QueryString["labeltext"];
if (lblText != null)
{
myLabel.Text = lblText;
}
If there's a chance that the text might not be suitable for passing in a URL, you can encode it with HttpServerUtility.UrlEncode and then decode it with HttpServerUtility.UrlDecode before assigning it to the label.

Use the query string for that:
Response.Redirect("AnotherPage.aspx?CommandArgument=SomeArgument");
Then read the QueryString on AnotherPage.aspx
string commArgument = Request.QueryString["CommandArgument"];

Related

Eliminate repeating lines by calling function

Is there any possible way to eliminate repeated lines by calling a function for many buttons in (aspx.cs) asp.net. I have tried through class, but elements of WebForm cannot be called. Is there any other way?
txtDescription.Text = "";
txtProjectDate.Text = "";
rblProjectStatus.SelectedIndex = -1;
txtProjectName.Text = "";
txtWebsiteUrl.Text = "";
calProjectDate.Visible = false;
chkProject1.Selected = false;
chkProject2.Selected = false;
ddlCompanyName.Items.Insert(0, new ListItem("--Select Name--"));
This code have to be inserted into a function, so that I can call the function wherever necessary. Is it possible ?
partial class MyPage
{
protected override void MyButton_Click(object sender, EventArgs e)
{
ResetControls();
}
protected override void MyOtherButton_Click(object sender, EventArgs e)
{
ResetControls();
}
private void ResetControls()
{
// do your business here
}
}
Alternatively you can hook both buttons to the same handler if they are to have identical behavior.
Looks like you are trying to reset the form. You should do this way (a button on web page):
<input type="reset" />
Another alternative is to redirect to the current url (from your C# code):
Page.Response.Redirect(Page.Request.Url.RawUrl)

using C# solution for Listview label

I want to use this solution to convert URLs to link in a listview label.
private string ConvertUrlsToLinks(string text)
{
string regex = #"((www\.|(http|https|ftp|news|file)+\:\/\/)[_.a-z0-9-]+\.[a-z0-9\/_:#=.+?,##%&~_-]*[^.|\'|\# |!|\(|?|,| |>|<|;|\)])";
System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(regex, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
return r.Replace(text, "$1").Replace("href=\"www", "href=\"http://www");
}
I have tried this in the listview databound but its not working.
protected void ProjectRecentActiviyListView_ItemDataBound(object sender, ListViewItemEventArgs e)
{
Label ProjectPostLabel = (Label)e.Item.FindControl("ProjectPostLabel");
ProjectPostLabel = ConvertUrlsToLinks({0});
}
Thank you
According to your code you are using ASP.NET Web Forms, not MVC.
You must use your ProjectPostLabel instance with Text property - no need to create a new label that is not assign to anywhere.
From your event you must retrieve Url property, not the label control. I have used NorthwindEmployee class with URL property in my ListView. You must cast it to your own class that is used in the list view.
protected void ProjectRecentActiviyListView_ItemDataBound(object sender, ListViewItemEventArgs e)
{
ProjectPostLabel.Text = ConvertUrlsToLinks(((NorthwindEmployee)e.Item.DataItem).URL);
}
And you must remember that only the last item from your list view will be displayed in the label (unless you expect that behavior). If you want to list of URLs from the list you can write this:
protected void Page_Load(object sender, EventArgs e)
{
ProjectPostLabel.Text = string.Empty;
}
protected void ProjectRecentActiviyListView_ItemDataBound(object sender, ListViewItemEventArgs e)
{
ProjectPostLabel.Text += string.Format("{0}<br/>", ConvertUrlsToLinks(((NorthwindEmployee)e.Item.DataItem).URL));
}

Get href value with onServerClick

I'm working with asp.net and c#
I got a list of link and i want to get the href value in the code behind.
So far I have:
<li>Room 101</li>
<li>Room 102</li>
<li>Room 103</li>
protected void room_click(object sender, EventArgs e)
{
}
The problem is I can't find a solution to get the href value, I tried the anchor or regex but it doesn't work.
You have to cast the sender to an HtmlAnchor so you can access the property:
public void room_click(object sender, EventArgs e)
{
var href = ((System.Web.UI.HtmlControls.HtmlAnchor)sender).HRef;
}
protected void room_click(object sender, EventArgs e)
{
var anchor = sender as HtmlAnchor;
if (anchor == null)
return;
var href = anchor.HRef;
//--do something
}
Your onServerClick is going to override your href anyway and instead cause a postback... so I'd recommend just removing it all and simply have:
<li>Room 101</li>
<li>Room 102</li>
<li>Room 103</li>
And then in your code behind:
protected void Page_Load(object sender, EventArgs e)
{
RoomClick();
}
private void RoomClick()
{
int roomId = 0;
//check to see if the id in the querystring exists and that it parses as an int.
if (!String.IsNullOrEmpty(Request.QueryString["id"]) && Int32.TryParse((Request.QueryString["id"]), out roomId))
{
//do something with roomId
}
}
This way seems more straightforward / easier to use, in my opinion. Jason's answer will work for you as well. I think that route is confusing though because although you can read the href and get that value, you can't read a # value from a URL... and this just isn't a standard way of accomplishing what you want to accomplish. Plus, how were you planning on easily getting the Room # out of that href?
The other reason I like this route is you can link someone directly to a room without telling them to click something first... if the id is there, it will load the room info or whatever you are doing.
UPDATE: If you don't want the room info in the URL and still want a "PostBack" approach, my recommendation is still a different route. Instead use a LinkButton which would be a more "traditional" way (in ASP.NET Web Forms) to do a PostBack and pass data:
So instead, have markup like:
<li><asp:LinkButton ID="_room104" OnCommand="RoomCommand" CommandArgument="104" Text="Room 104" runat="server"></asp:LinkButton></li>
<li><asp:LinkButton ID="_room105" OnCommand="RoomCommand" CommandArgument="105" Text="Room 105" runat="server"></asp:LinkButton></li>
and then code behind like:
protected void RoomCommand(object sender, CommandEventArgs e)
{
int roomId = 0;
if (Int32.TryParse((string)e.CommandArgument, out roomId)) {
//do something with roomId
}
}

session,cookies in asp.net c#

i want to pass a string value from one page to another.Also i have some text boxes and the values entered in it needs to be passed to a new page.How do i do it?
I have a string S
String S = Editor1.Content.ToString();
i want to pass value in string S onto a new page i.e Default2.aspx how can i do this in ASP.net C#
You can achieve it using Session or by QueryString
By Session
In your first page:
String S = Editor1.Content.ToString();
Session["Editor"] = S;
Then in your next page access the session using:
protected void Page_Load(object sender, EventArgs e)
{
String editor = String.Empty;
if(!String.IsNullOrEmpty(Session["Editor"].ToString()))
{
editor = Session["Editor"].ToString();
// do Something();
}
else
{
// do Something();
}
}
-
By QueryString
In your first page:
// or other events
private void button1_Click(object sender, EventArgs e)
{
String S = Editor1.Content.ToString();
Response.Redirect("SecondPage.aspx?editor" + S)
}
In your second page:
protected void Page_Load(object sender, EventArgs e)
{
string editor = Request.QueryString["editor"].ToString();
// do Something();
}
Depends on what the value is. If it is just a parameter and is ok to be viewed by the user then it can be passed through QueryString.
e.g.
Response.Redirect("Default2.aspx?s=value")
And then accessed from the Default2 page like
string s = Request.QueryString["s"];
If it needs to be more secure then consider using session, but I wouldn't recommend using the Session excessively as it can have issues, especially if you are storing the session InProc which is ASP.NET default.
You can have a state server or database but, it might be better to have your own database based session based on the authenticated user, and have it cached in the website if need be.
Use Session["content"]=Editor1.Content.ToString() in page1...
in page2 use...string s = Session["content"]

How to access usercontrol's values from page?

Hi I've created user control named test.ascs with one textbox. Now I added this user control in my default.aspx page. How can i access that textbox value from my default.aspx page?
is there any chance?
I usually expose the textbox's text property directly in test.ascx code behind like this:
public string Text
{
get { return txtBox1.Text; }
set { txtBox1.Text = value; }
}
Then you can get and set that textbox from the code behind of default.aspx like:
usrControl.Text = "something";
var text = usrControl.Text;
From your default page try to find the TextBox using your user control.
TextBox myTextBox = userControl.FindControl("YourTextBox") as TextBox;
string text = myTextBox.text;
If this is the purpose of the control, then create a public property on your user control that exposes this value, you can then access that from your page:
string textBoxValue = myUserControl.GetTheValue;
How to access the value of a textbox from an USERCONTROL in a page which is using this usercontrol
step 1: in user control make an event handler
public event EventHandler evt;
protected void Page_Load(object sender, EventArgs e)
{
txtTest.Text = "text123";
evt(this, e);
}
2: in page call the eventhandler
protected void Page_Load(object sender, EventArgs e)
{
userCntrl.evt += new EventHandler(userCntrl_evt);
}
void userCntrl_evt(object sender, EventArgs e)
{
TextBox txt = (TextBox)userCntrl.FindControl("txtTest");
string s = txt.Text;
}

Categories