update linkbutton text dynamically in asp.net - c#

I am trying to change the text for the link-button dynamically based on if the user is logged in or not. The text should be Log-out if user is logged in and vice versa. It is always showing Login. I am not sure what I am doing wrong here.
<p><asp:LinkButton ID="MyLnkButton" runat="server" EnableViewState = "False" onClick="MyLnkButton_Click" Text="" ForeColor="Red"/></p>
code behind
if (!Page.IsPostBack)
{
if (Session["USRID"] != null)
{
lblWLC.Text = (string)Session["USRID"];
MyLnkButton.Text = "Logout";
Bind_GV();
}
else
MyLnkButton.Text = "Login";
}

I would reverse the logic question is do you need to call Bind_GV regardless of post back.. if so I will depict in my code below
if (Page.IsPostBack && !string.IsNullOrEmpty((string)Session["USRID"]))
{
MyLnkButton.Text = "Login";
}
else
{
lblWLC.Text = (string)Session["USRID"];
MyLnkButton.Text = "Logout";
Bind_GV();
}

Related

How to enable disable fields using Java Script in Webform

I have created a web page "Default.aspx" in which I have taken fields:
First Name, Last Name, Account Titling, Titling(radio button list), AccountNumber and AccountFormat
under the "Default.aspx" page, I have used a radio button list also, whose values are Yes and No. If I choose Yes, then the following fields visibility should set to false:
First Name, Last Name
If I choose "NO", then the following fields visibility should set to true:
Account Titling, Account number
For this, I have written the below Java Script code in "Default.aspx"
function EnableDisableTaxID() {
if (document.getElementById("<%=rdOpeningSubAccount.ClientID %>") != null) {
var openSubAccountList = document.getElementById('<%= rdOpeningSubAccount.ClientID %>');
var fbo1RadioList = document.getElementById('<%=fbo1RadioButtonList.ClientID %>').value;
var isOpenSubAccount;
if (openSubAccountList != null) {
var openSubAccount = openSubAccountList.getElementsByTagName("input");
for (var i = 0; i < openSubAccount.length; i++) {
if (openSubAccount[i].checked) {
isOpenSubAccount = openSubAccount[i].value;
alert("Print" + isOpenSubAccount);
}
}
}
alert(typeof(isOpenSubAccount));
if (isOpenSubAccount == 'true') {
FirstName.visible = true;
LastName.visible = false;
AccountTitling.visible = true;
lblFirstName.visible=false;
lblLastName.visible=false;
}
else if (isOpenSubAccount == 'false') {
AccountTitling.visible = true;
AccountNumber.visible = false;
lblAccountTitling.visible = true;
lblAccountNumber.visible = false;
}
}
}
However, I am getting the required value from the Radio button list, however, when I go to check if the selected value of the radiobuttonlist is true, then the code above does not work. I dont know what am I missing. I know that directly using the below code will not work:
if (isOpenSubAccount == 'true') {
FirstName.visible = true;
LastName.visible = false;
AccountTitling.visible = true;
lblFirstName.visible=false;
lblLastName.visible=false;
}
Please help as I m stuck here...
For Visible = false;
document.getElementById('FirstName').style.visibility="hidden";
For Visible = true;
document.getElementById('FirstName').style.visibility="visible";
To Enable:
document.getElementById('FirstName').disabled = false;
To Disable:
document.getElementById('FirstName').disabled = true;
Following can be done for
Non Visible
document.getElementById('id-name').style.display='none';
Visible
document.getElementById('id-name').style.display='block';
Disable
document.getElementById('id-name').setAttribute('disabled', 'disabled');
Enable
document.getElementById('id-name').removeAttribute('disabled');
No; document.getElementById will only get the element with the ID you specify (the HTML spec is quite clear that only one element on a page can have a specific ID).
Each radio button has a different ID attribute, but if you look at the HTML source of a page, you will see that all radio buttons in the list have the same NAME attribute. This is what you should use "the name of the radio button".
onclick="GetRadioButtonValue('<%= radiobuttonlist1.ClientID %>')"
function GetRadioButtonValue(id)
{
var radio = document.getElementsByName(id);
for (var j = 0; j < radio.length; j++)
{
if (radio[j].checked)
alert(radio[j].value);
}
}

trouble wih validation inside of asp wizard

I have a group of 5 textboxes and I am using an asp:wizard. I want to check to see if all of the textboxes are empty I want to fire a label named lblItemBlock. Nothing I have tried has worked so far and so i tried cutting it down even smaller to test. I made the label visible on the page and on the active step tried to set the visible property to false. and for whatever reason it does not work
here is what I have:
protected void OnActiveStepChanged(object sender, EventArgs e)
{
if (Wizard1.ActiveStepIndex == Wizard1.WizardSteps.IndexOf(this.WizardStep3))
{
lblItemBlock.Visible = false;
}
}
Use the textbox/input validator in asp.net
Use a custom validator with client side script. There is probably a better method with 5 inputs but I use this when I need to validate multiple inputs in unison. The following checks that at least one of the text boxes has content:
function searchValidate(oSrc, args) {
var fName = document.getElementById('<%= txtFName.ClientID %>').value;
var mName = document.getElementById('<%= txtMName.ClientID %>').value;
var lName = document.getElementById('<%= txtName.ClientID %>').value;
if (fName == "" && mName == "" && lName == "") {
args.IsValid = false;
} else {
args.IsValid = true;
}
}

Launching a Edit Form from a GridButtonColumn

I have a class that defines a Hierarchical RadGrid that I will be using application wide. This grid has many column so this is the best implementation for me, as I will be overriding specific characteristics of the grid based om implementation.
The grid will function in a different manner based on the access level of the user. On a 'basic user level' they will have a Add New Item/Edit Item on the parent grid and Edit, Reject(delete), Approve(Update) on the Child Grid
The next level will be a 'Approver' role. They will NOT have Add New Item/Edit Item on the parent grid and will only have Reject(Edit) on the child. The edit action that the user will take in this role when rejecting an item is that they will be required to enter a comment through a user control that will be launched when the click the reject button. The problem that I am having is that the custom user control is not displaying for a DetailTableView.EditFormSettings when using a GridButtonColumn as the firing event. Any thoughts? TIA
private void SubmittedBatchesRadGrid_ItemDataBound(object sender, GridItemEventArgs e)
{
GridDataItem _dataItem = e.Item as GridDataItem;
if (_dataItem == null) return;
if (e.Item.OwnerTableView.Name == "SubmittedBatchesRadGrid_ChildGrid")
{
SetChildGridCommandColumns(sender, e);
return;
}
if (_dataItem.KeyValues == "{}") { return; }
SetMasterGridCommandColumns(sender, e, _dataItem);
}
private static void SetChildGridCommandColumns(object sender, GridItemEventArgs e)
{
const string _jqueryCode = "if(!$find('{0}').confirm('{1}', event, '{2}'))return false;";
const string _confirmText = "<p>Rejecting this adjustment will mean that you will have to also reject the batch when you are done processing these items.</p><p>Are you sure you want to reject this adjustment?</p>";
((ImageButton)(((GridEditableItem)e.Item)["PolicyEditRecord"].Controls[0])).ImageUrl = "/controls/styles/images/editpencil.png";
ImageButton _btnReject = (ImageButton)((GridDataItem)e.Item)["DeleteTransaction"].Controls[0];
_btnReject.CommandName = "Update";
_btnReject.ImageUrl = "/controls/styles/images/decline.png";
_btnReject.ToolTip = "Reject this item";
//_btnReject.Attributes["onclick"] = string.Format(_jqueryCode, ((Control)sender).ClientID, _confirmText, "Reject Adjustment");
}
private void SubmittedBatchesRadGrid_DetailTableDataBind(object sender, GridDetailTableDataBindEventArgs e)
{
e.DetailTableView.EditFormSettings.EditFormType = GridEditFormType.WebUserControl;
e.DetailTableView.EditFormSettings.UserControlName = "/Controls/RejectedAdjustmentComment.ascx";
e.DetailTableView.EditMode = GridEditMode.PopUp;
e.DetailTableView.CommandItemSettings.ShowAddNewRecordButton = false;
GridDataItem _dataItem = e.DetailTableView.ParentItem;
e.DetailTableView.DataSource = AdjustmentAPI.GetAdjustmentsByBatch(Convert.ToInt32(_dataItem.GetDataKeyValue("BatchID").ToString()), PolicyClaimManualAdjustmentCode);
}
It looks like you just need to use OnClientClick instead, and return the value of the confirm dialog.
_btnReject.OnClientClick = "return confirm(\"Are you sure you?\");"
RadAjax has a little quirk when it comes to confirm dialogs, so you may need to use this instead:
_btnReject.OnClientClick = "if (!confirm(\"Are you sure?\")) return false;"
So I thought I would share my solution in case anyone else needs it.
I was barking up the wrong tree with the edit control. Even though a comment is part of the dataset in the RadGrid I don't want to edit the existing record. I decided to create a usercontrol to handle the process. The RadWindow does not take .ascx pages directly so I started with a .aspx wrapper page and inserted the control there. Then I changed the OnClientClick event to launch the RadWindow loading the new aspx file passing the parameters I needed to the usercontrol. The usercontrol saves the comment to the database and updates the record status and then closes.
I modified this section from above:
private static void SetChildGridCommandColumns(object sender, GridItemEventArgs e)
{
((ImageButton)(((GridEditableItem)e.Item)["PolicyEditRecord"].Controls[0])).ImageUrl = "/controls/styles/images/editpencil.png";
ImageButton _btnReject = (ImageButton)((GridDataItem)e.Item)["DeleteTransaction"].Controls[0];
int _manualAdjustmentId = Convert.ToInt32(((GridDataItem)e.Item)["ManualAdjustmentId"].Text);
int _manualAdjustmentBatchId = Convert.ToInt32(((GridDataItem)e.Item)["ManualAdjustmentBatchId"].Text);
_btnReject.ImageUrl = "/controls/styles/images/decline.png";
_btnReject.ToolTip = "Reject this item";
_btnReject.OnClientClick = String.Format("OpenRadWindow('/controls/RejectedAdjustmentComment.aspx?manualAdjustmentId={0}&manualAdjustmentBatchId={1}', 'CommentDialog');return false;", _manualAdjustmentId, _manualAdjustmentBatchId);
}
private void SubmittedBatchesRadGrid_DetailTableDataBind(object sender, GridDetailTableDataBindEventArgs e)
{
//I deleted this section
e.DetailTableView.EditFormSettings.EditFormType = GridEditFormType.WebUserControl;
e.DetailTableView.EditFormSettings.UserControlName = "/Controls/RejectedAdjustmentComment.ascx";
e.DetailTableView.EditMode = GridEditMode.PopUp;
//
e.DetailTableView.CommandItemSettings.ShowAddNewRecordButton = false;
GridDataItem _dataItem = e.DetailTableView.ParentItem;
e.DetailTableView.DataSource = AdjustmentAPI.GetAdjustmentsByBatch(Convert.ToInt32(_dataItem.GetDataKeyValue("BatchID").ToString()), PolicyClaimManualAdjustmentCode);
}
I added this to the page with the datagrid:
<telerik:RadWindowManager ID="SubmittedBatchesWindow" runat="server">
<windows>
<telerik:RadWindow ID="CommentDialog" runat="server" Title="Rejected Agjustment Comment Dialog"
Height="350px" Width="440" Left="250px" ReloadOnShow="false" ShowContentDuringLoad="false"
Modal="true" VisibleStatusbar="false" />
</windows>
</telerik:RadWindowManager>
I created a new aspx file and inserted the new ascx control inside
<form id="form1" runat="server">
<telerik:RadScriptManager ID="RadScriptManager1" runat="server">
</telerik:RadScriptManager>
<uc:RejectedComment id="RejectionComment1" runat="server" />
</form>
I added my code behind for the update in the ascx file, the javascript for the front end
<script language ="javascript" type ="text/javascript" >
//<![CDATA[
function GetRadWindow() {
var oWindow = null;
if (window.radWindow) oWindow = window.radWindow; //Will work in Moz in all cases, including clasic dialog
else if (window.frameElement.radWindow) oWindow = window.frameElement.radWindow; //IE (and Moz as well)
return oWindow;
}
function CancelEdit() {
GetRadWindow().close();
}
//]]>
</script>
and last but not least closing the window after a successful update in the button click event;
Page.ClientScript.RegisterStartupScript(Page.GetType(), "", "CancelEdit();", true);
I hope someone else finds this useful. It took me several hours hunting the telerik site to find this piece by piece.

Get Textbox Value from Masterpage using c#

I have a search textbox situated on a masterpage like so:
<asp:TextBox ID="frmSearch" runat="server" CssClass="searchbox"></asp:TextBox>
<asp:LinkButton ID="searchGo" PostBackUrl="search.aspx" runat="server">GO</asp:LinkButton>
The code behind for the search page has the following to pick up the textbox value (snippet):
if (PreviousPage != null && PreviousPage.IsCrossPagePostBack)
{
Page previousPage = PreviousPage;
TextBox tbSearch = (TextBox)PreviousPage.Master.FindControl("frmSearch");
searchValue.Text = tbSearch.Text;
//more code here...
}
All works great. BUT not if you enter a value whilst actually on search.aspx, which obviously isn't a previous page. How can I get round this dead end I've put myself in?
If you use the #MasterType in the page directive, then you will have a strongly-typed master page, meaning you can access exposed properties, controls, et cetera, without the need the do lookups:
<%# MasterType VirtualPath="MasterSourceType.master" %>
searchValue.Text = PreviousPage.Master.frmSearch.Text;
EDIT: In order to help stretch your imagination a little, consider an extremely simple property exposed by the master page:
public string SearchQuery
{
get { return frmSearch.Text; }
set { frmSearch.Text = value; }
}
Then, through no stroke of ingenuity whatsoever, it can be seen that we can access it like so:
searchValue.Text = PreviousPage.Master.SearchQuery;
Or,
PreviousPage.Master.SearchQuery = "a query";
Here is a solution (but I guess its old now):
{
if (PreviousPage == null)
{
TextBox tbSearch = (TextBox)Master.FindControl("txtSearch");
searchValue.Value = tbSearch.Text;
}
else
{
TextBox tbSearch = (TextBox)PreviousPage.Master.FindControl("txtSearch");
searchValue.Value = tbSearch.Text;
}
}

How I turn label in asp red

Hi I would like to turn label red in .aspx when user enters wrong answer into textbox.
but not know how, hw I can do this?
You can do this using javascript (call this code from onchange of the textbox):
<label for="myTextBox" id="myLabel">For my textbox</label>
<input id="myTextBox" onchange="ValidateAnswer();">
function ValidateAnswer() {
var txtBox = document.getElementById('myTextBox');
if(txtBox.value != "answer") {
document.getElementById('myLabel').style.color = 'red';
}
}
You can also use the Validator controls if you're using ASP.Net:
<asp:CustomValidator runat="server" ID="cvAnswer"
ControlToValidate="myTextBox"
ErrorMessage="required"
ClientValidationFunction="ValidateAnswer"
ValidateEmptyText="true"
Display="Dynamic"
ValidationGroup="First"
ForeColor="red" >
</asp:CustomValidator>
function ValidateAnswer(sender, args) {
args.IsValid = args.Value != "" && args.Value == "answer here";
if(!args.IsValid) {
document.getElementById('myLabel').style.color = 'red';
}
return;
}
From the server side code:
if(this.txtBox.Text.Length == 0)
{
//no value entered
lblMyLabel.BackColor = Color.Red;
lblMyLabel.Text = "Invalid entry";
}
Client side you can do this:
Markup:
<asp:TextBox onchange="Validate();" runat="server" id="myTextBox"/>
JS:
function Validate()
{
var t = document.getElementByID("myTextBox");
var l = document.getElementByID("myLabel");
if (t.Length == 0)
{
l.style.backgroundColor='red';
}
}
There are multiple options, some server side, and some client side, but in both cases it involves validation. Essentially you are looking to change a css class or other style property on the label.
C# code behind:
if(yourConditionText != "YourExpectedValue")
{
youTextBox.BackColor = System.Drawing.Color.Red;
}
In the Server side button click event (which will be automatically generated when you double click on the button in Design view of the aspx page):
protected void Button_Click(...)
{
if(txtYourTextBox.Text != "YourDesiredValue")
{
lblYourLabel.ForeColor = Color.Red;
}
}
Better still, you could use String.Compare (recommended) as below:
if(string.Compare(txtYourTextBox.Text, "YourDesiredValue") != 0) //0 = Match
{
lblYourLabel.ForeColor = Color.Red; //For backColor set BackColor property
}
Hope it helps!

Categories