asp.NET how to change Session Language? - asp.net

I am new to this and would like to create a few simple hyperlinks that change the session language parameter.
Then I will test against this parameter to show dynamically different page elements.
I have not been able to find any sort of tutorial discussing a simple solution for this, only full blown tutorials that are in depth with databases and everything.
I was hoping someone here might be able to simply lead me to a beginners tutorial on how to alter the Session language parameter?
Any help appreciated!
thanks in advance

Something along this line?
Thread.CurrentThread.CurrentCulture = new CultureInfo( "pt-BR", false );
You can learn more about it here:
Globalization and localization demystified in ASP.NET 2.0
Edit:
Based on your comment bellow I now understand better what you want to do.
For the link part you can use LinkButton in your .aspx page as:
<asp:LinkButton id="linkButton1"
runat="server"
OnCommand="LinkButton1_Click"
CommandArgument="pt-BR">Click Me for Portuguese from Brazil
</asp:LinkButton>
Now in your code-behind file .cs:
private void LinkButton1_Click(object sender, System.EventArgs e)
{
string language = e.CommandArgument.ToString();
if(language.Equals("pt-BR"))
{
// Place your logic here for Portuguese-Brazil... Show or hide DIV...
}
}
If you wanna use Session, do this:
To store the value in Session:
private void LinkButton1_Click(object sender, System.EventArgs e)
{
string language = e.CommandArgument.ToString();
Session["lang"] = language;
}
To read the value from Session:
if (Session["lang"] != null)
{
if(Session["lang"].ToString().Equals("pt-BR"))
{
// Place your logic here for Portuguese-Brazil... Show or hide DIV...
}
}

Related

Populate form with values then saved modified values with C# using asp.net webforms

My .NET skills aren't great, but I'm stumped by a little issue and I can't find anything that explains this in a way I understand. Basically I'm trying to pre-populate a form with current values from a CMS, and have those values able to be updated when the form is submitted. It's essentially just an 'edit' facility for part of a website.
I have a usercontrol which contains some form inputs like this:
<label for="">Raised by</label>
<asp:TextBox ID="RaisedBy" runat="server"></asp:TextBox>
I then have a code-behind page which pulls values from a CMS and populates this form with the values already stored for this record, like this:
protected void Page_Load(object sender, EventArgs e)
{
// ...Some logic here gets the node from the CMS and I can pull property values from it. This part works fine.
string raisedBy = node.GetProperty("raisedBy").ToString();
// Populate form input with value from CMS. This works.
RaisedBy.Text = raisedBy;
}
So this is fine. But when the form is submitted it calls the following code:
protected void edit_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
// Get edited value of input field
string RaisedByVal = RaisedBy.Text;
// Do some logic here to set up the CMS to be able to save the property - this works although it uses the original value of the form not the modified value if the user has changed it.
pageToEdit.getProperty("raisedBy").Value = RaisedByVal;
}
}
The problem is that the original form values are being saved back to the system rather than the modified values if the user has edited them.
Can anyone suggest what I'm doing wrong and how to get the modified values to be used rather than the original values?
Many thanks.
You have to check whether it is Postback or not in Page_Load() method:
So if you don't do this then on edit button click it will 1st call the Page_Load() and will again reset the original value. Later it will call the Edit click method and you will still see the original data.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// ...Some logic here gets the node from the CMS and I can pull
property values from it. This part works fine.
string raisedBy = node.GetProperty("raisedBy").ToString();
// Populate form input with value from CMS. This works.
RaisedBy.Text = raisedBy;
}
}
Typically I found the answer right after posting! :)
I needed to wrap the 'pre-populate form values' logic inside a:
if (!IsPostBack)
{
}
block.

extending ASP.NET Page using MasterPage attributes as properties

I have an authentication roles-based system: different roles are redirected to different folders and in each folder there is a web.config that allows the access only to a particular username.
Few roles have the default page in common with a gridview that react in different ways depending on the role(different columns are shown, events trigger different methods, etc.).
so my problem is that everytime I need to make minor changes to a page I need to copy/paste the same changes to all the others default pages in the other folders.
In terms of code I solved by creating a DefaultFather class which extends System.Web.UI.Page and every other Default class inherits from DefaultFather. In this way, if I dont declare a Page-life-method, the DefaultFather method will be triggered.
but what about the graphic part(html, javascript, asp components, etc...)??
I created a NestedMasterPage just for the Default pages but everytime I need to change the appearance/behaviour of controls(gridview, buttons, linkbuttons) I must use the FindControl() method.
there isnt really another way to solve this problem?
Im thinking of using the Page_Load() method to search for each control with FindControl() and save them into attributes for later usage but it doesnt really look like a good solution.
It would be nice if I could use the masterpage components as properties but I think that in order to do that I should create public properties and I dont know if it will cause some kind of security problem.
any suggestion?
btw, if masterpage is the solution, should I remove the DefaultFather class and place the code directly into the masterpage? or is it a good idea to have another class just for the code?
I'd say there's nothing wrong with having both a master page and a base class for your page. They serve different purposes. The master page is generally all about layout, and the base class would be about page functionality.
If you want to manipulate the markup on your master page, rather than accessing the fields directly, I'd say create a logical function which does what you need it to do, and let the master page do it.
// Site.Master.cs
public void HideSubmitButton()
{
btnSubmit.Visible = false;
}
// Default.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
((SiteMaster)Master).HideSubmitButton();
}
I'd probably wrap that cast so you can use it more easily - that is something that would belong in your base class:
// DefaultFather.cs
protected new SiteMaster Master { get { return (SiteMaster)base.Master; } }
// Default.aspx.cs
Master.HideSubmitButton();
EDIT
Per your comment about attaching event handlers - if you need to attach events to objects that live on the master (which may not be a good idea - ideally the event handler for something living on the master lives on the master - but if you really need it) you can expose methods to do that as well, like:
// Site.Master.cs
public void AttachEventHandlerToGoButton(EventHandler eventHandler)
{
btnGo.Click += eventHandler;
}
// Default.aspx.cs
Master.AttachEventHandlerToGoButton(DoMyThing);
private void DoMyThing(object sender, EventArgs e) { }
or if you want to get fancy, write a wrapper event:
// Site.Master
<asp:Button ID="btnGo" runat="server" OnClick="btnGo_Click" />
// Site.Master.cs
public event EventHandler GoButtonClick;
protected void btnGo_Click(object sender, EventArgs e) {
if (GoButtonClick != null) {
GoButtonClick(sender, e);
}
}
// Default.aspx.cs
Master.GoButtonClick += DoMyThing;
private void DoMyThing(object sender, EventArgs e) { }
Also see my edit on the Master wrapper - you need the base. there to avoid a stack overflow.

Identifying all asp:Image controls in code behind

I am trying to find all asp:Image controls in the vb.net code behind to dynamically set the ImageUrl to the same image file. This I can do seperately for each control, but writing 10+
imgQuestion.ImageUrl = cdn.Uri.ToString & "images/question.png" lines seems a little silly. I do not need to skip any image controls - every single one on the page will be changed. Is there any way to identify all of them without specifying each ID?
The IDs are not all named something similar, such as "Image1", "Image2" but rather "PaymentNote", "search", etc so I cannot loop through all the numbers with something like FindControl("Image" & controlNumber)
Is there another way to do this? I'd prefer to keep the image control IDs as something meaningful.
You can recursively use FindControl, starting from the Page and for each control check if it's an <asp:Image...
My own preferred language of choice is C#, so I won't be able to show a VB example. But here's a C# example:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ChangeImageUrls(Page);
}
private void ChangeImageUrls(Control ctrl)
{
foreach (Control subCtrl in ctrl.Controls)
{
if (subCtrl is Image)
{
((Image)subCtrl).ImageUrl = "...";
}
if (subCtrl.HasControls())
ChangeImageUrls(subCtrl);
}
}
}

asp.net treeview programmatically setting node color

I want to set the node colors of a treeview at runtime. I populate the treeview from a collection that has the parentid, childid, and description, and I've added a property representing the color I want applied to the node. FWIW the source is a database, the app is C#.
In a gridview I use RowDataBound() to programmatically affect the control. Im not sure how to do so in the treeview, including which event to use (DataBound()? TreeViewDataBound()?). My research has not been fruitful so far. A code snippet would be very useful.
Hopefully this will give you a raging clue.
When setting a node text, instead of setting
Node Text
set as
<div style='color: red'>Node Text</a>
you can use Prerender event:
protected void TreeView1_PreRender(object sender, EventArgs e)
{
if (IsPostBack) return;
foreach (TreeNode t in TreeView1.Nodes)
{
if (t.Value.EndsWith("1")) //Some Condition
{
string s = t.Text;
string fs = "<span style=\"color: #CC0000\">" + s + "</span>";
t.Text = fs;
}
}
}
Since .NET Framework 4.5 you can use these style properties:
TreeView.LevelStyles Property - represent the node styles at the
individual levels of the tree
TreeView.RootNodeStyle Property
TreeView.ParentNodeStyle Property
TreeView.LeafNodeStyle
Property
Assuming you are dealing with the standard TreeView control, you can do this in the TreeDataBound Event.
A brief example (not tested):
<asp:TreeView runat="server"
ID="tvMyTreeView"
OnTreeNodeDataBound="tvMyTreeView_TreeNodeDataBound"
/>
And the backend:
protected void tvMyTreeView_TreeNodeDataBound(object sender, TreeNodeEventArgs e)
{
DataRowView dr = (DataRowView)e.Node.DataItem;
e.Node.Style.Add("color", dr["COLOR"].ToString());
}
If you are using the Telerik RadTreeView, then the event name is NodeDataBound
You will probably have to tweak the example to better fit your needs, but hopefully this will get you started.

Retrieving and updating server control values in a ListView

In the past I've used jQuery Ajax to create a shopping cart. This time around I'm using the list view server control.
If I have a qty text box in each row and I want to update the quantity on a button click is this the most elegant way to achieve this?
protected void Button1_Click(object sender, EventArgs e)
{
foreach(ListViewItem item in ListViewCart.Items)
{
foreach (Control con in item.Controls)
{
if (con.GetType() == typeof(TextBox))
{
//Do Work.
}
}
}
}
I'm guessing that I would need to store the productID in a custom attribute for each textbox and use it when updating the database. (Or write more code to find that value somewhere else in the row.)
More importantly, is there a different server control I might want to use instead? I don't want to use the gridview.
I guess you could shorten it a little bit like this
foreach (TextBox txtBox in
ListViewCart.Items.SelectMany(item => item.Controls.OfType<TextBox>()))
{
//do work like - txtBox.Text = "foo";
}

Resources