ImageButton ASP.Net changing Image URL in a control - c#

I'm setting up a Web User Control in ASP 4. The control itself works correctly, and the code for the onload even is the same as used in my standard aspx pages.
protected void GetTranslationImage(object sender, EventArgs e)
{
ImageButton image = (ImageButton)sender;
objTranslation = new TranslationsHelper();
string sTranslationID = image.ImageUrl.ToString();
string lang = ((NRMaster)this.Master).Language;
lang = lang == null ? "en-gb" : lang;
image.ImageUrl = objTranslation.GetTranslation(sTranslationID, lang);
}
When the object is passed through onLoad it doesn't contain the default URL during GetTranslationImage. The object changes to the translation required however it reverts back following in the HTML on the page load.
The definition of the ImageButton is as follows:
<asp:ImageButton ID="btnSearch" runat="server" name="Search" value="Search" class="Search" src="/_resources/img/BTN_search.gif" onclick="btnSearch_Click" onLoad="GetTranslationImage" />
Does the control alter the time this function needs to be run.
Any help would be greatly appreciated.
Thank You
James

Why are you setting src="/_resources/img/BTN_search.gif" if you are overwriting it in OnLoad?
1: Remove it
Or
2: Change it to:
ImageUrl="/_resources/img/BTN_search.gif"

What if you made the transition method public from within the usercontrol and you simply call out to that method in your page load?
page_load()
{
myusercontrol.StartImageTransition();
}
Public Methods inside User control c# .net

Related

Accessing the ID of an HTML element in a different aspx file to then be used in the other file's code-behind file

I have 2 aspx files. Let's call the first P1 and the second P2. In P1, I have an HTML element with ID "date". I want to access date in P2's code-behind C# file, but am unsure how to do this. I'm using Visual Studio.
Must I use "using P1.aspx" in P2's code-behind file? Must I declare an object of P1 in P2's code-behind file?
For example, in P2's code-behind file, why can't I do the following:
P1 object = new P1();
object.date = ...;
As of now I can't get P1 to be recognized by P2 in any way. Any help would be appreciated. Thanks!
This can be achieve using CrossPagePostBack...for More Info..You can refer this Link..
https://learn.microsoft.com/en-us/previous-versions/ms178139(v=vs.140)?redirectedfrom=MSDN
For Example:-
P1.aspx
<asp:Label ID="lblDate" runat="server" Text="Date"></asp:Label>
<asp:TextBox ID="txtDate" runat="server"></asp:TextBox>
<asp:Button ID="btnRedirect" runat="server" Text="Redirect" OnClick="btnRedirect_Click"/>
protected void btnRedirect_Click(object sender, EventArgs e)
{
Server.Transfer("~/P2.aspx");
}
Suppose...Your P1 page contain TextBox(txtDate) thats you want to access in P2.aspx Page
You can redirect to other page using CrossPagePostBack...
In P2.aspx Page on Page Load event you can easily find out Previous Page Control..
if (this.Page.PreviousPage != null)
{
TextBox txtDate = (TextBox)this.Page.PreviousPage.FindControl("txtDate");
}
For More Info....
Suppose your PreviousPage i.e. P1.aspx have master control Page Property...then you can use this..on P2.aspx Page...
if (this.Page.PreviousPage != null)
{
Control ContentPlaceHolder1 = this.Page.PreviousPage.Master.FindControl("ContentPlaceHolder1");
TextBox txtDate = (TextBox)ContentPlaceHolder1.FindControl("txtDate");
}

Getting Javascript values from client on page load

I'm trying to determine the client window size on pageload, to use in creating a bitmap using c#. From reading on SO and elsewhere, I know that one method would be to:
Write a Javascript function to get the relevant values;
Store these in hidden fields;
Read the value using the code behind (c#) and then do stuff with it.
However, I'm getting tripped up by the execution sequence that runs code behind BEFORE any Javascript, even though I've set <body onload... to get and set the relevant values. (see below)
I know the rest of my code works, because, when I execute, the page shows the word "by" and the button. Then, after I have clicked the button and the page reloads, it can now suddenly read the two hidden values.
My question is, how can I get my c# Page_Load code to get those two hidden values from the client side, before it executes the rest of my code, and without the need for user action like clicking a button?
My page:
<body onload="getScreenSize()">
<form id="form1" runat="server">
<input type="hidden" name="hiddenW" ID="hiddenW" runat="server" />
<input type="hidden" name="hiddenH" ID="hiddenH" runat="server" />
<script>
function getScreenSize() {
var myW = document.getElementById("hiddenW");
myW.value = window.innerWidth;
var myH = document.getElementById("hiddenH");
myH.value = window.innerHeight;
}
</script>
<asp:Button ID="Button1" runat="server" Text="Button" />
</form>
</body>
Code behind:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(hiddenW.Value+" by " +hiddenH.Value);
}
}
On first run (when I need those values), it shows
and after I click the button, it proves the Javascript works:
The question then, is how do I get those values before the rest of my Page_Load code runs, so that I can go straight into generating and displaying my image?
You cannot get the client window size before the C# Page_Load() executes because the page is rendered to the client after the C# code execution is complete.
The window size may change during page load, hence you have to get the window size only after page load is complete.
Solution:
You can use ajax to send the values to the back-end, after the page has loaded completely.
OR
You can cause a post-back using java-script after you get the correct value, this way:
JQuery:
$(function() {
var width = window.innerWidth ||
document.documentElement.clientWidth ||
document.body.clientWidth;
var height = window.innerHeight ||
document.documentElement.clientHeight ||
document.body.clientHeight;
$('#hdn_width').val(width);
$('#hdn_height').val(height);
$('#your_form').submit();
});
C#:
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (IsPostBack)
{
// Use hdn_width and hdn_height here
}
}
catch (Exception ex)
{
}
}
Use the IsPostBack property
This would solve your problem
For Example
if(!Page.IsPostBack)
{
//Control Initialization
//Your code goes here
}
I used a timer to postback once and two none-displayed textboxes to store the window-values width and height. the textboxes are filled with a javascript:
document.getElementById('<%=TxWd.ClientID %>').value = window.innerWidth;
document.getElementById('<%=TxHt.ClientID %>').value = window.innerHeight;
In code behind (VB.NET):
Protected Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Session("seswidth") = Val(TxWd.Text)
Session("sesheigth") = Val(TxHt.Text)
Timer1.Enabled = False
End Sub

How to set dynamic parameter values to custom control from web page

I have one image button in the custom control like below.
public string SearchTableName = string.Empty;
public string SearchColumnName = string.Empty;
public string SiteURL = string.Empty;
ImageButton _imgbtn;
protected override void OnInit(EventArgs e)
{
_imgbtn = new ImageButton();
_imgbtn.ImageUrl = ImageURL;
_imgbtn.OnClientClick = "ShowSearchBox('" + SiteURL +"/_layouts/CustomSearch/SearchPage/Searchpage.aspx?table_name=" + SearchTableName + " &column_name=" + SearchColumnName + "')";
}
On Clicking of the image button I want to migrate to the another window which is a popup. For this I written a javascript function. I am setting the SearchTableName and SearchColumnName in the web page in which we are consuming this custom control like below. Before consuming I registered this control in web page with register tag.
<ncc:SearchControl runat="server" ID="txtSearchControl" /> In code behind file of this webpage I am using following code to set the values.
protected void Page_Load(object sender, EventArgs e)
{
txtSearchControl.ImageURL = "_layouts/Images/settingsicon.gif";
txtSearchControl.SearchTableName = "Employees";
txtSearchControl.SearchColumnName = "LastName";
txtSearchControl.SiteURL = "http://Sp2010:8787";
}
Now coming to the problem, when I click the image button the SearchTableName and SearchColumnName values are not coming. I think I am calling OnClientClick function, thats why the values are not being set. But how to set the values for the custom control based on the values setting in the webpage. If I use the Click function will it serve my purpose? If so, how to call that javascript function from this click event.
Finally got solution. I am initializing the values in the page init method in the custom control. Thats why the values i am setting in the visual webpart page are not being captured. Now I changed the initializing the values in CreateChildControl method. Now it works perfectly. Thank you.

masterpage initializeculture no suitable method found to override error?

I'm trying to develop a MultiLanguage web site using ASP.NET with C#
My problem is: I want to make my MasterPage support switching among languages, but when i put the "InitializeCulture()" inside the masterpage.cs, I got this error.
this is my code:
public partial class BasicMasterPage : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
if (e.Day.IsToday)
{
e.Cell.Style.Add("background-color", "#3556bf");
e.Cell.Style.Add("font-weight", "bold");
}
}
Dictionary<string, System.Globalization.Calendar> Calendars =
new Dictionary<string, System.Globalization.Calendar>()
{
{"GregorianCalendar", new GregorianCalendar()},
{"HebrewCalendar", new HebrewCalendar()},
{"HijriCalendar", new HijriCalendar()},
{"JapaneseCalendar", new JapaneseCalendar()},
{"JulianCalendar", new JulianCalendar()},
{"KoreanCalendar", new KoreanCalendar()},
{"TaiwanCalendar", new TaiwanCalendar()},
{"ThaiBuddhistCalendar", new ThaiBuddhistCalendar ()}
};
protected override void InitializeCulture()
{
if (Request.Form["LocaleChoice"] != null)
{
string selected = Request.Form["LocaleChoice"];
string[] calendarSetting = selected.Split('|');
string selectedLanguage = calendarSetting[0];
CultureInfo culture = CultureInfo.CreateSpecificCulture(selectedLanguage);
if (calendarSetting.Length > 1)
{
string selectedCalendar = calendarSetting[1];
var cal = culture.Calendar;
if (Calendars.TryGetValue(selectedCalendar, out cal))
culture.DateTimeFormat.Calendar = cal;
}
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture;
}
base.InitializeCulture();
}
}
How can I create a Base class?
The method InitializeCulture() exists only on the Page class, not the MasterPage class, and that's why you get that error.
To fix this, you could create a BasePage that all your specific pages inherit:
Create a new Class (not Webform), call it BasePage, or whatever you want.
Make it inherit System.Web.UI.Page.
Make all your other pages inherit the BasePage.
Here's an example:
public class BasePage : System.Web.UI.Page
{
protected override void InitializeCulture()
{
//Do the logic you want for all pages that inherit the BasePage.
}
}
And the specific pages should look something like this:
public partial class _Default : BasePage //Instead of it System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Your logic.
}
//Your logic.
}
There is an alternate solution that DOES NOT require you to create a BasePage.
The problem with 'Culture' is that it gets set very very early on the page life cycle, so the Page.InitializeCulture event is one of the early events on the page (if not the only one) where we can hook up to change the Thread.CurrentThread.CurrentUICulture. But what if we do that even earlier, as soon as the Request begins on the server.
I do that on the Application_BeginRequest event on the Global.asax file which is called on every request.
protected void Application_BeginRequest(Object sender, EventArgs e)
{
HttpCookie cookie = Request.Cookies["langCookie"];
if (cookie != null && !string.IsNullOrEmpty(cookie.Value))
{
Thread.CurrentThread.CurrentUICulture = new CultureInfo(cookie.Value);
}
}
There I check for the existence of a cookie that holds the culture I want to use. If there's no cookie, then the default culture will be used.
To change the language on my application I just need a control that changes the cookie value client-side and then do a simple postback to the server. It doesn't matter if such control is on the Content Page or in the Master Page, it doesn't even need any code on the server-side, because all the processing is done on the method above, and the cookie gets set on the client-side even before the page is posted.
I've used a simple LinkButton (which is styled as a Mexican Flag), but you can use any other control that do a postback when clicked/changed.
<asp:LinkButton ID="btnSpanish" runat="server" OnClientClick="SetLanguageCookie('es')" CausesValidation="false" CssClass="mxFlag" />
Right before this button posts back to the server, it runs the client-side click event which updates the cookie value I want to set, and voila!
I have the javascript code that sets the cookie at the Master Page head section:
function SetLanguageCookie(selectedLanguage) {
var expDate = new Date();
expDate.setDate(expDate.getDate() + 20); // Expiration 20 days from today
document.cookie = "langCookie=" + selectedLanguage + "; expires=" + expDate.toUTCString() + "; path=/";
};
That's it!! The Thread.CurrentThread.CurrentUICulture gets changed and no BasePage class is needed nor overriding the Page.InitializeCulture method. There's even the side effect that the language selected is remembered on following visits since it's stored on a cookie.
If you want to use a DropDownList instead of a LinkButton, just make sure to set the AutoPostBack="true" and, since there is no OnClientChanged property for the DropDownList, you must hardcode the onchange attribute on the DropDownList and pass the selected value to the same javascript function.
<asp:DropDownList ID="ddlLanguage" runat="server" AutoPostBack="true" onchange="SetLanguageCookie(this.options[this.selectedIndex].value)">
<asp:ListItem Text="English" Value="en" />
<asp:ListItem Text="Español" Value="es" />
<asp:ListItem Text="Français" Value="fr" />
</asp:DropDownList>
The onchange attribute is not part of the DropDownList properties, however, since the DropDownList is an analog control of the <select> control, the attribute is just placed 'as is' when the rendering happens, and it's rendered before the postback mechanism code. Here's the HTML rendered by the DropDownList above:
<select name="ctl00$cph1$ddlLanguage" onchange="SetLanguageCookie(this.options[this.selectedIndex].value);setTimeout('__doPostBack(\'ctl00$cph1$ddlLanguage\',\'\')', 0)" id="cph1_ddlLanguage">
<option value="en">English</option>
<option value="es">Español</option>
<option value="fr">Français</option>
</select>
Hope someone finds this approach as useful as I do. :)

Get variable & keep changes after postback

This question is related to: Hide div on clientside click
The issue I am having is that after postback event from asp.net happens onClick any clientside changes made reset how can I keep the client side changes I am making.
Second question how can I get a variable from code behind and pass it into my javascript to perform a comparison.
Html:
<div runat="server" id="someDiv1" enableviewstate="true" >
<asp:LinkButton OnClientClick="Show_Hide_Display()"
ID="lbtnDiv1"
runat="server"
CausesValidation="true"
OnClick="lbtn_onClickServer">
</asp:LinkButton>
</div>
<div runat="server" class="tick" id="div2" style="display:none;" enableviewstate="true">
</div>
Javascript:
<script type="text/javascript">
function Show_Hide_Display() {
var div1 = document.getElementById("<%=someDiv1.ClientID%>");
var div2 = document.getElementById("<%=div2.ClientID %>");
if (div1.style.display == "" || div1.style.display == "block") {
div1.style.display = "none";
div2.style.display = "block";
}
else {
div1.style.display = "block";
div2.style.display = "none";
}
}
</script>
The OnClick event causes a postback like it should, on this occassion it checks if users, chosen username is available.
If it is available show a tick, if it isn't error.
I got the error working and am trying to program the tick on client side.
So OnClientClick I am able to toggle between some text and a tick. So I need to:
Get the bool result from code behind
After postback keep tick (if username is available)
I am almost there but can't quite figure the last two points out.
If you are using an UpdatePanel in your page, and assuming that div which you are trying to toggle is outside the control, you can always inject javascript on a partial postback:
Like for e.g. on your button's click event which executes on a partial postback make a call to ScriptManager.RegisterClientScriptBlock() --> How to retain script block on a partial postback?
Alternatively, you can append an end request handler. This is some javascript which should run after the partial postback. --> ASP.NET Register Script After Partial Page Postback (UpdatePanel)
The answer for the both questions lies of checking the boolean value send from the code behind.
1-----.in code-behind c#
protected void Page_Load(object sender, System.EventArgs e)
{
var linkbtn = (Button)Page.FindControl("lbtnDiv1");
linkbtn .Attributes.Add("onClick", "Show_Hide_Display('" + parameter+ "')");
}
2------- change your javascript
function Show_Hide_Display(parameter)
{
if( paramater=='true')
{
----your logic---
}
else
{
----your logic
}
}

Categories

Resources