disable dropdownlist on page load - c#

I have 2 dropdownlists populated from database:
what I want is to disable the second one on page load and when the value of the first one =="1".
here is my second dropdownlist:
<asp:DropDownList ID="DropDownList2" runat="server" AutoPostBack="True"
DataSourceID="SqlDataSource2" DataTextField="BName" DataValueField="BId"
OnDataBound="DownList2_DataBound"
OnSelectedIndexChanged="DropDownList2_SelectedIndexChanged">
</asp:DropDownList>
This what I tried to disable the dropdownlist2 (javascript):
<script type="text/javascript">
window.onload = function () {
document.getElementById('DropDownList2').disabled = true;
}
</script>
Tried another thing in C# code:
protected void Page_Load(object sender, EventArgs e)
{
if (DropDownList1.SelectedValue.ToString() == "1")
{
DropDownList2.Enabled = false;
}
}
I even tried this alone in page_load:
DropDownList2.Enabled = false;
The problem is it's disabled on SelectedIndexChanged for dropdownlist1 but not on page load! Is there's something missing in my code?

This statement allow you to set the dropdown2 to disable at page load.
$('#' + '<%=DropDownList2.ClientID%>').attr('disabled',true);
you can do this using Jquery simply as follow:
$(document).ready(function () {
var isPostBack = '<%=IsPostBack%>';
if (isPostBack == 'False' || $('#' + '<%=DropDownList1.ClientID%>').val() == '1') {
//This statement allow you to set the dropdown2 to disable
$('#' + '<%=DropDownList2.ClientID%>').attr('disabled', true);
}
else {
$('#' + '<%=DropDownList2.ClientID%>').attr('disabled', false);
}
$('#' + '<%=DropDownList1.ClientID%>').on("change", function () {
//Your code here
if ($('#' + '<%=DropDownList1.ClientID%>').val() == '1') {
$('#' + '<%=DropDownList2.ClientID%>').attr('disabled', true);
}
else {
$('#' + '<%=DropDownList2.ClientID%>').attr('disabled', false);
}
});
});

It is likely that the DropDownList1.SelectedValue is not equal to "1" on Page Load as I guess you'd be DataBinding it somehow, which would take effect afterwards.
Try adding a SelectedIndexChanged function for DropDownList1 and dis/enabling DropDownList2 here. You can put Enabled="False" in the markup for DropDownList2 to ensure it starts off Disabled.

The issue is likely that document.getElementById('DropDownList2') doesn't find your dropdown list. The ID for the list is a server-side value that doesn't necessarily translate to the client-side ID. If you set ClientIDMode for the control to Static, then the client ID will be DropDownList2. Another option is to access the ClientID property of the control when outputting your JavaScript (if it's inline):
document.getElementById('<%=DropDownList2.ClientID%>').disabled = true;
All that being said, even if that's the case, it'd be better to just start with Enabled="False" as #aaroncatlin suggests so you don't have to wait for the JavaScript to execute before it is disabled.

in ASP.NET the generated ID differs from the asp ID on the component, to access the element from Javascript you need to use <%=DropDownList2.ClientID%> the corresponding javascript will be something like this :
document.getElementById(<%=DropDownList2.ClientID%>).disabled = true;

The DropDownList would have a default selected index of -1 and a null value for selected value. I usually check against the selected index, instead of by value. For example,
if(DropDownList1.SelectedIndex < 1){
// assuming that index 0 holds your value of "1"
DropDownList2.Enabled = false;
}
And #Jacob did rightly point out about you needing to get the proper ClientID for your JavaScript function.

Related

ASP.Net: How to maintain TextBox State after postback

I would like to know how to maintain the control state that has been modified in Javascript.
I have two TextBoxes, one DropDownList and a button (all Runat=Server) in C# ASP.net 2010 Express.
First textbox is just accept whatever data user input. Second textbox enable state will change based on DDL selected value. If ddl selected value is "-", second textbox will become Enabled = False.
If not "-", it will become Enabled = True. This enable is done through Javascript.
In my Page Load event, I have below code.
if (!IsPostBack)
{
txtKey2.Text = "";
txtKey2.BackColor = System.Drawing.ColorTranslator.FromHtml("#CCCCCC");
txtKey2.Enabled = false;
}
And in my aspx page, I have some javascript which will clear the textbox data and disable the textbox.
Here is for Second Textbox.
<asp:TextBox ID="txtKey2" runat="server" Width="425px" EnableViewState="False"></asp:TextBox>
And here is for DDL.
<asp:DropDownList ID="selKey1" runat="server" onchange="EnableSelkey(this.value,1)">
<asp:ListItem Value="0">-</asp:ListItem>
<asp:ListItem Value="1">AND</asp:ListItem>
<asp:ListItem Value="2">OR</asp:ListItem>
</asp:DropDownList>
Here is the code for my Javascript. (I have a plan to implement other textbox and ddl so in my code I have Else if condition).
function EnableSelkey(val, strID) {
var txtBox;
if (strID == "1")
txtBox = document.getElementById('<%= txtKey2.ClientID %>');
else if (strID == "2")
txtBox = document.getElementById('<%= txtKey3.ClientID %>');
else
txtBox = document.getElementById('<%= txtKey4.ClientID %>');
if (val != 0) {
txtBox.disabled = false;
txtBox.style.backgroundColor = "White";
txtBox.value = "";
txtBox.select();
}
else {
txtBox.disabled = true;
txtBox.style.backgroundColor = "#CCCCCC";
txtBox.value = "";
}
}
I have nothing in button click event.
By using above all code, when I run the project, the page loads Ok.
The second textbox enabled state is set to False (through Page_Load event). So far Ok.
Then from my browser, I choose ddl value to other instead of "-", the textbox become enable because of javascript. This is Ok.
I input the value and click on the button. Page PostBack happens here. Textbox is still enabled (because of EnableViewState = False for my textbox).
I choose ddl value to "-", second textbox became disabled.
Click on the button, page postback happen, but this time the textbox is still enabled. << This is the issue I'm trying to solve. I change EnableViewState, ViewStateMode in different values but still the same.
Is there any solution for this one?
Here is my test image URL.
State 1 ,
State 2 ,
State 3
Sorry for the long post.
I have tried and found no solution beside using additional HiddenField control.
I update the hidden field value when I update the status of my textbox in Javascript.
And on my Page Load event, I checked all the hidden field values and based on the hiddenfield values, I will disable/enable my textboxes which is for me not a good solutions.
Imagine I have 10 or 15 textboxes on my form, I need to have 10 or 15 hidden field just to maintain client side action result.
Currently, this is the only solution for me.
I'm not sure can this consider as 'Answer' so I haven't close this question yet.
<asp:DropDownList ID="selKey1" runat="server" onchange="EnableSelkey(this.value,1)">
<asp:ListItem Value="0">-</asp:ListItem>
<asp:ListItem Value="1">AND</asp:ListItem>
<asp:ListItem Value="2">OR</asp:ListItem>
</asp:DropDownList>
function EnableSelkey(val, strID) {
var txtBox;
if (strID == "1")
txtBox = document.getElementById('<%= txtKey2.ClientID %>');
else if (strID == "2")
txtBox = document.getElementById('<%= txtKey3.ClientID %>');
else
txtBox = document.getElementById('<%= txtKey4.ClientID %>');
if (val != 0) {
txtBox.disabled = false;
txtBox.style.backgroundColor = "White";
txtBox.value = "";
txtBox.select();
}
else {
txtBox.disabled = true;
txtBox.style.backgroundColor = "#CCCCCC";
txtBox.value = "";
}
}
You Have to call you javascript function on every postback.
if (!IsPostBack)
{
txtKey2.Text = "";
txtKey2.BackColor = System.Drawing.ColorTranslator.FromHtml("#CCCCCC");
txtKey2.Enabled = false;
}
ScriptManager.RegisterClientScriptBlock(this, typeof(System.Web.UI.Page), "MyJSFunction", "EnableSelkey("+selKey1.SelectedValue+",1);", true);
It May be help you, Let me know for further help.
I found a solution that worked was to put the code that I put in the !IsPostBack section for enabling and disabling the textboxes also directly in the page load event.

How to call Confirmation box in IF condition from Code-Behind?

I'm using a LinkButton and a DropDown.
When I click on the LinkButton the DropDown appears.
After selecting a DropDown value, I want a confirmation box called from JavaScript to appear, ensuring that the value is changed.
I'm calling this script in the second if condition, but it's not working.
After the confirmation I want to change the other value and exit from the condition.
protected void lnkbtnSave_Click(object sender, EventArgs e)
{
if ((ddlHiringManager.SelectedItem != null &&
(ddlHiringManager.SelectedItem.Text != lblHiringManager.Text)) &&
(Convert.ToInt32(ddlHiringManager.SelectedValue)) != -1)
{
if (ClientScript.RegisterStartupScript(typeof(Page), "Confirm", "<script type='text/javascript'>Confirm('Are you sure you want to change Hiring Manager for this requirement.');</script>"))
{
ClsClientManager objClientManager = new ClsClientManager();
if (objClientManager.UpdateHRManagerByReqID(Convert.ToInt32(hdnReqId.Value), Convert.ToInt32(ddlHiringManager.SelectedValue)) > 0)
{
lblShowHiringManager.Text = ddlHiringManager.SelectedItem.Text;
}
}
}
else
{
ClientScript.RegisterStartupScript(typeof(Page), "SymbolError", "<script type='text/javascript'>alert('Please Select Hiring Manager !');</script>");
}
}
You cannot use the result of RegisterStartupScript method.
Change ASPX page code for the LinkButton as given below
<asp:LinkButton ID="lnkbtnSave" runat="server" OnClick="lnkbtnSave_Click"
OnClientClick="javascript: return confirm('Are you sure you want to change Hiring Manager for this requirement.');">Save</asp:LinkButton>
I have added the client side click event.
On clicking the LinkButton you will get the confirmation box. The page will postback only if you click OK in the confirmation box.
Please refer this Code Snippet. On dropdown selected index change event
protected void ddlTest_SelectedIndexChanged(object sender, EventArgs e)
{
string str = "Are you sure, you want to upload leave ?";
this.ClientScript.RegisterStartupScript(typeof(Page), "Popup", "ConfirmApproval('" + str + "');", true);
}
And for Client Side declare that method.
<script type="text/javascript">
function ConfirmApproval(objMsg) {
if (confirm(objMsg)) {
$('#divUploadLeave').fadeTo('slow', .6);
return true;
} else {
$('#divUploadLeave').fadeTo('slow', 1);
return false;
}
}
Hope It helps you.
Still if you want all things on Client Side please let me know.
Please add return before Confirm this will solve your issue.
**if (ClientScript.RegisterStartupScript(typeof(Page), "Confirm", "<script type='text/javascript'>return Confirm('Are you sure you want to change Hiring Manager for this requirement.');</script>"))**

Add CSS Class through a Repeater

I have a repeater which dynamically generate tab links using Sitecore (sc:Link) like this:
<asp:Repeater ID="rptTab" runat="server" OnItemDataBound="rptTab_ItemBound">
<ItemTemplate>
<li id= "liTabTest" runat = "server" class="tab-label">
<asp:HyperLink onclick = "javascript: TabClick(this)" runat="server" id="aLink">
<sc:Link ID="hlTabLink" Field="scTabLink" runat="server" ></sc:Link>
</asp:HyperLink>
</li>
</ItemTemplate>
</asp:Repeater>
I manipulate the CSS via JS:
var loadURL;
$(document).ready(function () {
init();
});
function init() {
$("ul#Tab-labels li:first").addClass("TabbedPanelsTabSelected");
};
function TabClick(obj) {
$("ul#Tab-labels li").removeClass("TabbedPanelsTabSelected");
$(obj).addClass("TabbedPanelsTabSelected");
};
Unfortunately, this is not working because each tab is a separate .ASPX page, so the page is getting rendered again and that is why Init() in JS is getting called and CSS is getting executed to the first item everytime.
This is my code behind:
protected void rptTab_ItemBound(Object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Item i = e.Item.DataItem as Item;
Link hlTabLink = e.Item.FindControl("hlTabLink") as Link;
hlTabLink.DataSource = i.Paths.FullPath;
hlTabLink.Field = "Title";
HyperLink aLink = e.Item.FindControl("aLink") as HyperLink;
aLink.NavigateUrl = Sitecore.Links.LinkManager.GetItemUrl(i);
}
}
I tried adding CSS through code-behind but it didnt work because I cannot get the index of the tab (which tab is getting selected). Any solution will be appreciated! Thanks!
Don't run javascript for a task that is better (and easier) accomplished in code-behind. Just set the active class for the repeater item where Sitecore.Context.Item matches the name of the tab. Pseudo code inside ItemDataBound:
if(i == Sitecore.Context.Item)
{
HtmlGenericControl li = e.Item.FindControl("liTabTest");
li.Attributes.Add("class","TabPanelTabbedSelected");
}
Not sure if HtmlGenericControl is correct here, or if it has a CssClass property, but I hope you get the idea. If there is no direct representation for li on the server side, you can also bind a string literal or use a Literal control.
The answer to my question is: The repeater is like an array. So I can get the 1st and Last element of a repeater like this:
string currClass = hc.Attributes["class"].ToString();
string count = e.Item.Controls.Count.ToString();
if (e.Item.ItemIndex == 0)
{
currClass += " TabbedPanelsTabSelected";
}
else if (e.Item.ItemIndex.ToString() == count)
{
currClass += " last";
}
In this way I can add a css to my first element and the last element through Repeater.

How to scroll to selected row in GridView

I have a GridView with PageSize = 20 (20 rows) but it can show only 10 rows without a vertical scrollbar appearing.
My problem is that when a postback occurs, it jumps to top row of the grid even though I selected a different row. I would like to scroll to the selected row. How can I do this?
Add MaintainScrollPositionOnPostback in your page directive.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" MaintainScrollPositionOnPostback ="true"%>
Another way, use a scrollTop method of the DIV that wraps your GridView:
private void ScrollGrid()
{
int intScrollTo = this.gridView.SelectedIndex * (int)this.gridView.RowStyle.Height.Value;
string strScript = string.Empty;
strScript += "var gridView = document.getElementById('" + this.gridView.ClientID + "');\n";
strScript += "if (gridView != null && gridView.parentElement != null && gridView.parentElement.parentElement != null)\n";
strScript += " gridView.parentElement.parentElement.scrollTop = " + intScrollTo + ";\n";
ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "ScrollGrid", strScript, true);
}
EDIT:
This won't work for several reasons:
1) if the gridView is inside a NamingContainer control, like a Panel, because the Id on the client side won't be the ClientId. You need to use the UniqueId of teh control instead.
2) you can't trust the row height to calculate the scroll position. If the text in any column wraps to more than one line, or any row contains something higher than the style, the size of the row will be different
3) different browsers can have different behaviors. You're better of using jQuery scrollTop() and scroll() functions. To use them, you must use scrollTop on client side and set the value of a HiddenControl that can be read on server side to reset the position. You can't get the height of the rows in the browser until they are rendered on client side.
This code in the RowDataBound event handler for the gridview worked for me:
protected void dgv_usersRowDatabound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowIndex == intEditIndex)
{
DropDownList drpCategory = e.Row.FindControl("drpCategory") as DropDownList;
drpCategory.Focus();
}
}
The Gridview contains a dropdownlist in each row as an EditItemTemplate.
This worked for me, and required no ASP.NET AJAX, UpdatePanel or cookie, and a lot less JavaScript than other solutions I've seen.
<input type="hidden" runat="server" id="hdnScroll" value="0" />
<div style="height:600px; overflow-x:hidden; overflow-y:scroll">
<asp:GridView runat="server" ID="myGridView" OnRowDataBound="myGridView_RowDataBound" OnSelectedIndexChanged="myGridView_SelectedIndexChanged">
...
</asp:GridView>
</div>
Then
protected void myGridView_SelectedIndexChanged(object sender, EventArgs e) {
//if(gr != null) gr.SelectedRow.Cells[0].Focus(); // Only works on an editable cell
hdnScroll.Value = (myGridView.SelectedIndex * (int)myGridView.RowStyle.Height.Value).ToString();
}
Finally back in the .aspx, to run upon postback
<script type="text/javascript">
$(function() {
document.getElementById('<%=myGridView.ClientID%>').scrollTop = $('#hdnScroll').val();
});

How can i get ASP.Net Grid Element using Javascript

I am using a Grid View in asp.net, i want to get Element on clicking a grid, how can i do so?
A grid has a column id, name, warp, weft, etc, i want to pick the selected cell data using Javascript, let me know.
Please help...
Regards
Atif
To track which row button is clicked, you have to set the row Index as a parameter to a JS function like...
protected void grdForecast_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType ==DataControlRowType.DataRow )
{
((Button)e.Row.FindControl("buttonId")).Attributes.Add("onclick", "javascript:update(" + (e.Row.RowIndex ) + ");");
}
}
And then in JavaScript:
<script language="javascript" type="text/javascript">
function update(ri) {
var grd = document.getElementById('<%= GridView1.ClientID %>');
SecondCellValue = grd.rows[ri].cells[1].childNodes[0].value
ThirdCellValue = grd.rows[ri].cells[2].childNodes[0].value
}
</script>
Do you have a control inside the cell that you can reference? If not, then you can create a hidden control. Then you can write out the control's client id to the client side in the PreRender event handler via ScriptManager. And you can then get a hold of that element by id and find other content inside that parent cell.
Alternatively, you can use jquery to handle cell click events...
$('#myTable td').click(function () {
alert($(this).html());
});

Categories