Javascript for disabling dropdown in ASP.NET - asp.net

I am using JScript in ASP.NET 2005. I have a page with a checkbox and a dropdown list. When the checkbox is checked, the dropdown is to be disabled. During Postback of the page, this behavior should be retained. I am using a javascript function as follows
if((chkOwner[1].checked==true))
{
document.getElementById(ddlClientID).disabled=true;
document.getElementById(ddlClientID).className = "form-disabled";
document.getElementById(ddlClientID).selectedIndex = 0;
}
else
{
document.getElementById(ddlClientID).disabled=false;
document.getElementById(ddlClientID).className = "form-input";
document.getElementById(ddlClientID).selectedIndex = 0;
}
This works, almost. However, the dropdown selection is not retained after postback (when checkbox is not selected). [It goes to zero index's value]
Apprently the solution is to remove the last line, i.e, in the else part, remove the selectedIndex =0 .
But, when I do that the disabling of dropdown (when check box is checked) is not working after post back.
Could you please help me on this?
More Info: I am using ClientScript.RegisterStartupScript for checking this at each page load.
Thanks
Lijo
--CODE-----
Following is what I am trying. (This is a sample application I created just now. It does not work. This can only show what I am trying to achieve.)
function ManageInputsFor()
{
if((document.getElementById(chbx).checked==true))
{
document.getElementById(ddlClientID).disabled=true;
document.getElementById(ddlClientID).className = "form-disabled";
document.getElementById(ddlClientID).selectedIndex = 0;
}
else
{
document.getElementById(ddlClientID).disabled=false;
document.getElementById(ddlClientID).className = "form-input";
document.getElementById(ddlClientID).selectedIndex = 0;
}
}
protected void Page_Load(object sender, EventArgs e)
{
ClientScript.RegisterClientScriptBlock(Page.GetType(), "chbx", #"<script language=""javascript"" type=""text/javascript"">var chbx ='" + CheckBox1.ClientID + "'</script>");
ClientScript.RegisterClientScriptBlock(Page.GetType(), "ddl", #"<script language=""javascript"" type=""text/javascript"">var ddlClientID ='" + DropDownList1.ClientID + "'</script>");
ClientScript.RegisterStartupScript(Page.GetType(), "onLoadCallForManageInputs", #"<script language=""javascript"" type=""text/javascript"">ManageInputsFor();</script>");
CheckBox1.Attributes.Add("onclick", "ManageInputsFor();");
}

you'll have to do a server side evaluation of the checkbox during the pastback, and set the dropdownlist enabled or not. the disabled attribute of the drop down isn't sent to the server during the post operation (neither is the value of the control when it's disabled,btw).
edit: to retain the value in the drop down across a postback, you can copy the selected value to another control which will be posted back, and then assign the value back to the drop down during server processing.

Basically, your problem is happening bc when you use javascript to change the state of an ASP control, that stat is not posted back to the server. You have to figure out a way to send it. Using a hidden control, or adding a parameter to the querystring are two such methods.

Related

jqgrid asp.net webforms Server side SelectedRow property empty

I am trying to get this sample to work
Get Selected Row (on server)
but for me the SelectedRow property is always empty.
The only difference being that I am using the Page_load event to populate my grid.
When i press a button on my form, it does a postback, and repopulates the grid losing the row selection.
sample code:
if (!Page.IsPostBack )
{
UserBusinessObject userBO = new UserBusinessObject();
GRDUsers.DataSource = userBO.GetUsersbyProfileID(SessionFacade.Id);
GRDUsers.DataBind();
}
protected void btnEdit_Click(object sender, EventArgs e)
{
if (String.IsNullOrEmpty(GRDUsers.SelectedRow))
{
lblError.Visible = true;
}
else
{
Response.Redirect(string.Format("~/Manage/EditUserRoles.aspx?username={0}",GRDUsers.SelectedRow));
}
}
I Have also noticed that on button click, my Page Load fires twice (1st time postback is true, 2nd time it is false) According to jqgrid posts this is intentional. but i think this might be causing my grief.
You always must set the DataSource because is not saved on ViewState or anywhere else. So the code must be as:
UserBusinessObject userBO = new UserBusinessObject();
GRDUsers.DataSource = userBO.GetUsersbyProfileID(SessionFacade.Id);
if (!Page.IsPostBack )
{
GRDUsers.DataBind();
}
working with the guys at JQGrid, we have resolved the problem. It is a bug in their grid that has been fixed in v4.5.0.0
see here for details
i can confirm that this fixes the bug, and all is right with the world again

Maintaining TabContainer active tab after postback from within the tabs (with AutoPostBack='false')

I have an AjaxToolkit TabContainer control with a number TabPanels. Each TabPanel has a different UserControl in it to display some information. Some of these UserControls have either a LinkButton or a GridView with a command button in them. The TabContainer has AutoPostBack="false" and this is how I would like to keep it.
When you click on the LinkButton or command button in the GridView the expected events fire and the code runs. But when the page is returned the initial tab is selected again (and not the tab the user was previously viewing).
So my question is: Is there a way to maintain the selected tab when some child control causes a postback?
Some constraints:
I do not way to turn AutoPostBack on. This means the linked solution for this question question is no good in this case.
The UserControls are not always used in a TabContainer/TabPanel so the solution can not assume that this is the case.
The solution needs to be fairly robust and straightforward as there could be different devs working on this code.
I solved this problem by creating my own control that inherits from TabContainer, then overriding LoadClientState() like this:
protected override void LoadClientState(string clientState)
{
base.LoadClientState(clientState);
// If post back was caused by control on a tab, make that tab the active one
if (!string.IsNullOrEmpty(this.Page.Request.Params["__EVENTTARGET"]))
{
foreach (string ctlName in this.Page.Request.Params["__EVENTTARGET"].Split('$'))
{
if (this.FindControl(ctlName) is TabPanel && this.Tabs.Contains(this.FindControl(ctlName) as TabPanel))
{
this.ActiveTab = (this.FindControl(ctlName) as TabPanel);
break;
}
}
}
}
This finds the TabPanel on which the control causing the postback resides, then makes that the active panel.
I got this from another forum. You set this in the pageload. I don't know if that would help with them being set to AutoPostBack=false, but if you haven't given up on it yet, I hope this helps
if (ViewState("ActiveTabIdx") != null)
{
activeTabIndex = Convert.ToInt32(ViewState("ActiveTabIdx"))
if (activeTabIndex != null)
{
TabContainer1.ActiveTabIndex = activeTabIndex;
}
}
you need to add ActiveTabChanged event for tab container and you can keep active tab index in view state, and on page load just check if it is not null then set it as Active tab index.
protected void TabContainer1_ActiveTabChanged(object sender, EventArgs e)
{
ViewState["ActiveTabIndex"] = TabContainer1.ActiveTabIndex;
}
PageOnLoad Event code
if (!(ViewState["ActiveTabIndex"] == null) )
{
TabContainer1.ActiveTabIndex = (int)ViewState["ActiveTabIndex"];
}
Make sure to add following attributes in TabContainer tag
AutoPostBack="true" OnActiveTabChanged="TabContainer1_ActiveTabChanged"

format for url to point to radio button selection [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
linking to a radio button selection, asp.net c#
i have a page with a textarea and radio buttons. the text area is populated with data based on the radio button selection. i want the radio button selection to appear in the url so that a user can link to the radio button selection.
i'm hoping that all i need to do i modify my querystring to include radio button value. here's the data caputered by fidler when i make a radio button selection.
__EVENTTARGET ctl00$MainContent$RadioButtonList1$6
__EVENTARGUMENT
__LASTFOCUS
__VIEWSTATE /+++PC9wPg0KPHA+/....
__EVENTVALIDATION /wEWCwKY7d6oAQLh8vmTCALk7M7lDQK+6NunDwK/6OenDwK86OenDwK86OunDwK86POnDwK96NenDwK96NunDwKxh73KA3Q+PMuKU/JUCKsF1aiY2DNLu7/pFFni/Qtz+7FXy35g
ctl00$MainContent$RadioButtonList1 41
i'm hoping my url simply needs to look something like this to point to the radio button value but and all i need is the appropriate syntax:
http://www.test.com/test.aspx?ctl00$MainContent$RadioButtonList1$41
---code behind ---
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false)
{
RadioButtonList1.SelectedIndex = 0;
RadioButtonList1.DataBind();
}
else
{
string strRedirect;
strRedirect = "frm_Articles.aspx?Article_PK=" + RadioButtonList1.SelectedValue.ToString();
Response.Redirect(strRedirect);
}
}
protected void SqlDataSource2_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
//
}
protected void SqlDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
try{
e.Command.Parameters["#URL_FK"].Value = Session["URL_PK"];
}
catch (Exception ex)
{
}
}
}
One thing to note is that you have misconstructed your url. It should be:
http://www.test.com/test.aspx?ctl00$MainContent$RadioButtonList1=41
(note the third to last character is an =.
Apart from that it would depend on how your page works in terms of picking up the selected radio button. My advice would be to just try it and see what happens. However, I would suspect that if you are doing it based on an event firing on page load (ie some kind of postback behaviour) then it won't work.
If this is the case then you will just want to do something on page load to check if that value exists in the url and set it before you load up the text. If you end up going down this route you might want to consider using a more well defined and user friendly querystring parameter. In particular the id you have there is built based on its position in the control hierarchy. If you were to redesign your HTML structure the ID might well change.
Additionally...
With the code you've provided where you set the selectedindex of your radiobutton list you need to find out what value you need before you set it and set it to 0 if you have no better value (though it looks like you are setting to 0 before binding whcih seems superfluous). Something like this may work (not compiled or tested so apologies for typos - it is designed to give you the general idea more than to be finalised code).
if (Page.IsPostBack == false)
{
RadioButtonList1.DataBind();
//Check if you have a value to set.
if (Request.Querystring(RadioButtonList1.ClientID)!=null)
{
//Get the value
string setValue = Request.Querystring(RadioButtonList1.ClientID)
//Find the right radio option to select
foreach(ListItem item in RadioButtonList1.Items)
{
if (item.Value == setValue)
{
item.Selected = true;
break;
}
}
}
}
I assume it will default to the selected index being 0 if nothing is set as selected otherwise.
Anyway, this code is meant as a starting point to work from. There may be other ways to do it and some may even be better.

dynamic data - all option in paging

I'm developing a dynamic data web app. On list.aspx page it has GridViewPager control for paging, it option in drop down list as 10,20,.. rows in a page like that, but it does not an option show all rows in a page.
How I can add "All" option in it?
I assume you are referring to a GridView and the automatic paging functionality included. If not please clarify. However, if this is the case then the default paging options do not include a show all. You can roll your own, I would start here: http://msdn.microsoft.com/en-us/library/5aw1xfh3.asp
In content folder Dynamic Data site lies the code for GridViewPager control.
What I have done is I added "All" option in dropdown list with values 0, and in the code behind file in function DropDownListPageSize_SelectedIndexChanged I check if selected value is 0 then set AllowPaging = false else true.
protected void DropDownListPageSize_SelectedIndexChanged(object sender, EventArgs e)
{
if (_gridView == null)
{
return;
}
DropDownList dropdownlistpagersize = (DropDownList)sender;
int sz=Convert.ToInt32(dropdownlistpagersize.SelectedValue);
//_gridView.PageSize = Convert.ToInt32(dropdownlistpagersize.SelectedValue);
if (sz<=0)
{
_gridView.AllowPaging = false;
//_gridView.DataBind();
//return;
}
else
{
_gridView.AllowPaging = true;
_gridView.PageSize = sz;
_gridView.AllowPaging = true;
}
int pageindex = _gridView.PageIndex;
_gridView.DataBind();
if (_gridView.PageIndex != pageindex)
{
//if page index changed it means the previous page was not valid and was adjusted. Rebind to fill control with adjusted page
_gridView.DataBind();
}
}
You will have to implement your own pager and attached it to the Gridview. Default pager will not give you this option. May be this link could help you. http://www.codeproject.com/KB/grid/GridView_pager.aspx

How to call javascript in a child page's onload event

I have an ASP.net application with an aspx page.
In Page_Load event of the aspx page, I'm handling some code which is based on the value of a hidden variable from the javascript(assigning result of javascript to hidden variable).
I am calling the javascript in Page_Load of the child page, and in the immediate statement, I'm making use of the hidden variable value for processing. When I access hidden variable value, I'm getting default value only.
Please suggest me any of handling the scenario. I need to execute the javascript and get the result into the hidden variable. Both in need to occur in Page_Load event only.
Hidden Variable declaration:
<asp:HiddenField runat='server' ID='hdnDate' Value='0' />
Javscript:
function getCDate() {
var nowDate = new Date();
var curr_month = nowDate.getUTCMonth();
curr_month ++;
var dt = curr_month + "/" + nowDate.getUTCDate() + "/" +nowDate.getFullYear()+ " " + nowDate.getUTCHours()+":" +nowDate.getUTCMinutes()+":" +nowDate.getUTCSeconds();
document.getElementById("ctl00_ContentPlaceHolder1_hdnDate").value = dt;
return true;
}
Page_Load method in code behind file:
protected void Page_Load(object sender, EventArgs e)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "getCDate();", true);
DateTime dt=Convert.ToDateTime(hdnDate.Value);
dt.AddDays(10); //getting error here because dt contains01/01/0001
}
You cannot call javascript in Page_Load. It is client side thing so should come from browser only. You can check if page is postback using IsPostBack property of Page object like this:
if(IsPostBack)
{
//this is coming from browser so you javascript might have been
//called and proper value set in hidden field.
}
Javascript is run on the client side, so can't run in the Page_Load event on the Server.
From the looks of your code, I'm pretty sure you don't need javascript, you can just put the value into a SessionVariable as:
Session.Add("DateRendered", DateTime.Now.AddDays(10).ToString("MM/dd/YYYY"));
And then retrieve it later. ASP.net takes care of storing it in the Request/Response.
RegisterStartupScript will register your block of script for the next page load.
if you just want some value to be transferred to .cs page write a static method on the .cs and call it from javascript using PageMethods.MethodName();

Resources