Dropdownlist "Enable true" is not working Asp.net - javascript

I have set dropdown enable set to false in one button click and i will set enable="true" is not working in page load
here is my aspx
<asp:DropDownList ID="ddlJournal" runat="server" OnSelectedIndexChanged="ddlJournal_SelectionChanged" AutoPostBack="true" CssClass="drop" />
Here is my click event:
protected void btnTemplate_click(object sender, EventArgs e)
{
check.Value = "1";
Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "Load_functions()", true);
//txtAddJournal.Attributes.Add("Style", "display:block");
//btnUpload.Attributes.Add("Style", "display:block");
//if (fileuploader.HasFile)
//{
try
{
string Filename = Path.GetFileName(fileuploader.FileName);
//fileuploader.SaveAs(Server.MapPath("~/") + Filename);
// fileuploader.SaveAs(Server.MapPath("D:\\Req Sep16\\") + Filename);
OleDbConnection myconnectionini = default(OleDbConnection);
OleDbDataAdapter mycommandini = default(OleDbDataAdapter);
//if (fileuploader.PostedFile.FileName.EndsWith(".xls") == false & fileuploader.PostedFile.FileName.EndsWith(".xlsx") == false)
//{
// // lbl_Error.Text = "Upload only excel format";
// Response.Write(#"<script language='javascript'>alert('Upload only excel format');</script>");
// return;
//}
//else
//{
gvDetails.DataSource = null;
string pathToSave = HttpContext.Current.Server.MapPath("~/UploadFiles/") + "Copy of Database_HBM";
//fileuploader.PostedFile.SaveAs(pathToSave);
//strFilePath = "D:\\Files\\" + fileuploader.FileName;
string constrini = "provider=Microsoft.Jet.OLEDB.4.0;data source=" + pathToSave + ";Extended Properties=Excel 8.0;";
DataSet ds = new DataSet();
// DataTable dt = new DataTable();
myconnectionini = new OleDbConnection(constrini);
mycommandini = new OleDbDataAdapter("select * from [Sheet1$]", myconnectionini);
ds = new DataSet();
mycommandini.Fill(ds);
gvDetails.DataSource = ds.Tables[0];
gvDetails.DataBind();
ddlJournal.SelectedIndex = -1;
ddlJournal.Enabled = false;
//ddlJournal.Attributes.Add("disabled", "disabled");
//}
}
catch (Exception ex)
{
string msg = ex.Message;
}
//}
}
And my page load event is
protected void Page_Load(object sender, EventArgs e)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "Grid", "headerLock();", true);
// ScriptManager.RegisterStartupScript(Page, this.GetType(), "Key", "<script>headerLock();</script>", true );
if (!IsPostBack)
{
Bindddl();
BindGrid(null);
ddlJournal.Enabled = true;
}
else
{
ddlJournal.Enabled = true;
}
}
button :
<asp:Button ID="btnUpload" runat="server" Text="Template 1" OnClientClick="return Validate();"
OnClick="btnTemplate_click" CssClass="btn" />
but still my dropdown list is disable.
suggest me get a solution
thanks in advance

You can set dropdown list Enabled false from its control only like this
<asp:DropDownList ID="ddlJournal" runat="server" OnSelectedIndexChanged="ddlJournal_SelectionChanged" AutoPostBack="true" CssClass="drop" Enabled="false"/>
And the rest code should work fine.
Please mark it helps

Understand that your if-else condition in Page_Load() method is the main culprit. You're always setting ddlJournal.Enabled = true, no matter what. Seems like you didn't properly understand the concept of IsPostBack. ddlJournal is supposed to be disabled when IsPostBack is true, because that's what you want. Otherwise, it's supposed be enabled.
This is a very concise explanation about what IsPostBack is:
Postback in an event that is triggered when a action is performed by a contol on a asp.net page. for eg. when you click on a button the data on the page is posted back to the server for processing.IsPostback is normally used on page _load event to detect if the page is getting generated due to postback requested by a control on the page or if the page is getting loaded for the first time.
[a comment from http://forums.asp.net/t/1115866.aspx?What+is+IsPostBack ]
So based on that, you should change your code like the following:
protected void Page_Load(object sender, EventArgs e)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "Grid", "headerLock();", true);
if (!IsPostBack)
{
//When IsPostBack is false, ddlJournal should be enabled
Bindddl();
BindGrid(null);
ddlJournal.Enabled = true;
}
else
{
//Else, IsPostBack is true, so, ddlJournal should be disabled
ddlJournal.Enabled = false;
}
}
Also, you don't need this in your btnTemplate_click() method since you're doing this on page load:
ddlJournal.Enabled = false;

Related

Html button call a function in code behind and it fires only once

I have html button which calls a function in code behind and it fires only once.
I want it to fire event every time I click the button.
It is possibly duplicated but I have tried to add "!IsPostBack" but it doesn't work.
My ascx class:
<button runat="server" type="button" class="btn btn-report" onserverclick="OnReportBtnClick" id="reportBtn">
<i class="glyphicon glyphicon-floppy-disk"></i>
</button>
I have to use html button, not <asp:Button> because <asp:Button> doesn't let me to insert <i> tag inside.
Here is my code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
try
{
reportBtn.ServerClick += OnReportBtnClick;
}
catch (Exception ex)
{
}
}
}
//this method is called only once even I click the button many times afterwards.
protected void OnReportBtnClick(object sender, EventArgs e)
{
try
{
// Set file name
string pdfName = SPContext.Current.Web.Title + fileType;
CultureInfo provider = CultureInfo.InvariantCulture;
DateTime startDate = DateTime.MinValue;
if (!string.IsNullOrEmpty(report_startDate_datePicker.Value))
startDate = DateTime.ParseExact(report_startDate_datePicker.Value, format, provider);
DateTime endDate = DateTime.MaxValue;
if (!string.IsNullOrEmpty(report_endDate_datePicker.Value))
endDate = DateTime.ParseExact(report_endDate_datePicker.Value, format, provider);
// Provisioning data for report
var report = GetReport(startDate, endDate);
// Merger data to template html
byte[] data = GetPdfData(htmlTemplate, report);
//Respond report to client
RenderResponse(pdfName, data);
}
catch (Exception ex)
{
LoggingService.LogError(LoggingService.NTT_ERROR,
string.Format("ERROR: {0} - SOURCE: {1} | {2}", ex.Message, ex.Source, System.Reflection.MethodBase.GetCurrentMethod().Name));
}
}
//I think the problem could be this method.
//I return a pdf file to client
private void RenderResponse(string pdfName, byte[] data)
{
try
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "application/pdf";
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + pdfName);
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
HttpContext.Current.Response.BinaryWrite(data);
HttpContext.Current.Response.End();
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
catch (Exception ex)
{
LoggingService.LogError(LoggingService.NTT_ERROR,
string.Format("ERROR: {0} - SOURCE: {1} | {2}", ex.Message, ex.Source, System.Reflection.MethodBase.GetCurrentMethod().Name));
}
You can use a LinkButton
<asp:LinkButton runat="server" ID="ReportBtn" Text="<i class='glyphicon glyphicon-floppy-disk'></i>" OnClick="ReportBtn_Click" CssClass="btn btn-report" />
in .cs page
protected void ReportBtn_Click(object sender, EventArgs e)
{
//your code
}
They do support html in the text field.

Show message only on first access to the web page in c#

With this code I show JavaScript alert message box in ASP.Net from server side using C#.
But I need show the message only on first access to the web page, how to do resolve this ?
Please help me.
My code below, thank you in advance.
protected void Page_Load(object sender, EventArgs e)
{
string message = "Hello!";
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("<script type = 'text/javascript'>");
sb.Append("window.onload=function(){");
sb.Append("alert('");
sb.Append(message);
sb.Append("')};");
sb.Append("</script>");
ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", sb.ToString());
}
You need to check that the page is not posting back before you display your alert:
if (!IsPostBack)
{
string message = "Hello!";
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("<script type = 'text/javascript'>");
sb.Append("window.onload=function(){");
sb.Append("alert('");
sb.Append(message);
sb.Append("')};");
sb.Append("</script>");
ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", sb.ToString());
}
Updates:
You can create a cookie to track the alert so it does not display after displaying during the initial page load:
private bool Alerted()
{
if (Request.Cookies["alerted"] != null)
return Server.HtmlEncode(Request.Cookies["alerted"].Value) == "true";
else
{
Response.Cookies["alerted"].Value = "true";
Response.Cookies["alerted"].Expires = DateTime.Now.AddDays(10);
return false;
}
}
Usage:
if(!Alerted())
{
// alert script here
}

Whats wrong in this asp.net code? Textbox value doesnt set

protected void Button1_Click(object sender, EventArgs e)
{
if (count > 100)
{
StringBuilder javascript = new StringBuilder();
javascript.Append(" <script language=\"javascript\" type=\"text/javascript\">");
javascript.Append(" var tmp = confirm(\"No:Of Records exceeds 1000.Please confirm you want to continue\");");
javascript.Append("if (tmp)");
javascript.Append("{document.getElementById(\" <%=TextBox1.ClientID%>\").value=\"1\"; alert(document.getElementById(\"<%=TextBox1.ClientID %>\").value);}");
javascript.Append(" </script>");
ClientScript.RegisterStartupScript(GetType(), "recordscript", javascript.ToString(), false);
return;
}
}
Here I want to set the value of the textbox by clicking the button event and oly that condition is true.So I cant call that function from source.actually that function gets called but the textbox value doesnt set..I really dont understand where is the problem..
protected void Button1_Click(object sender, EventArgs e)
{
if(count>100)
{
StringBuilder javascript = new StringBuilder();
javascript.Append(" <script language=\"javascript\" type=\"text/javascript\">");
javascript.Append(" var tmp = confirm(\"No:Of Records exceeds 1000.Please confirm you want to continue\");");
javascript.Append("if (tmp)");
javascript.Append("{document.getElementById('" + TextBox1.ClientID + "').value=\"1\"; alert(document.getElementById('" + TextBox1.ClientID+ "').value);}");
javascript.Append(" </script>");
ClientScript.RegisterStartupScript(GetType(), "recordscript", javascript.ToString(), false);
return;
}
}
}
You need to concatenate the TextBox1.ClientID with your javascript string. The code you have will get rendered to the page as is, look at the output of your rendered page with view source, you will see the string '<%= TextBox1.ClientID =%>' not the expected ID. Keep in mind that the inline display expression <%= =%> is equivalent to a server Response.Write().

Sharepoint 2010 XsltListViewWebPart on an application page

I'm trying to add an XsltListViewWebPart control to a sharepoint application dynamically.
When I run ShowDocumentList(pnlAdminCurrentDocuments) on Page_Load everything works fine.
However, if i call the same function on a ajax request, the control loads, but none of the events get fired (i.e. sorting, expanding tree view etc)
XsltListViewWebPart wp;
private void ShowDocumentList(Panel panel)
{
try
{
ShowMessage("<p>No documents to show</p>");
string meetingURL = "http://rl01/sites/nmc/FullMonty";
string meetingId = "6d39de81-a7f7-4cff-9c94-5d2893526dc5";
if (!string.IsNullOrEmpty(meetingURL) && !string.IsNullOrEmpty(meetingId))
{
using (SPSite site = new SPSite(meetingURL))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists.TryGetList("Meeting Documents");
if (list == null)
return;
SPView view = null;
try
{
view = list.Views["Submitted"];
//view = list.Views[0];
}
catch { }
if (view == null)
{
//todo - replace with toolbx message
ShowMessage("Cannot view documents");
}
else
{
wp = new XsltListViewWebPart();
wp.ChromeType = PartChromeType.None;
wp.ListId = list.ID;
wp.ViewGuid = view.ID.ToString();
wp.WebId = web.ID;
wp.XmlDefinition = view.GetViewXml();
wp.XmlDefinition = wp.XmlDefinition.Replace("MEETING_ID", meetingId);
//SetToolbarContext(web);
panel.Controls.Clear();
panel.Controls.Add(wp);
}
}
}
}
}
catch (Exception ex)
{
ShowMessage("");
}
}
The function actually gets the data and does everything but none of the client side functionality on the list view doesn't work. Throws a javascript error even when I mouse over the column names. If I add the control with a full postback without using ajax, everything works as expected.
protected void radAjaxMgr_AjaxRequest(object sender, Telerik.Web.UI.AjaxRequestEventArgs e)
{
ShowDocumentList(pnlAdminCurrentDocuments);
}
HTML markup is as follows
<telerik:RadAjaxManager ID="radAjaxMgr" runat="server" OnAjaxRequest="radAjaxMgr_AjaxRequest">
</telerik:RadAjaxManager>
<asp:UpdatePanel runat="server" ID="pnl1">
<ContentTemplate>
<asp:Panel ID="pnlAdminCurrentDocuments" runat="server" CssClass="i3q_DocumentListHldr submittedDocsPanel">
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
Javascript function to raise the ajax call
function test()
{
var ajaxMgr = $find("<%= RadAjaxManager.GetCurrent(this).ClientID %>");
if (ajaxMgr)
{
ajaxMgr.ajaxRequest("Name1;Value1");
}
}
Thanks in advance :-)

Change Gridview Textbox's visible property true false on DropdownLists's Selected index change event using javascript not working

I am making Gridview's Textbox visible true or false when user changes Dropdownlists selectedIndexchange event for that i have done following code
My .CS File code is as below:
protected void gvTaskList_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
HiddenField hdn = (HiddenField)e.Row.FindControl("hdnStatus");
DropDownList ddl = (DropDownList)e.Row.FindControl("ddlStatus");
TextBox txt = (TextBox)e.Row.FindControl("txtVal");
if (ddl != null)
{
ddl.Items.Add("Not Started");
ddl.Items.Add("In Progress");
ddl.Items.Add("Complete");
if (hdn != null)
{
ddl.SelectedValue = hdn.Value;
}
//ddl.SelectedIndexChanged += new EventHandler(ddl_SelectedIndexChanged);
ddl.Attributes.Add("onChange", "return myFun(" + "'" + txt.ClientID + "'" +");");
}
}
}
catch (Exception ex)
{
Utility.ErrorList("EmpTaskList--RowdataBound", ex.ToString());
}
}
Note: My combobox and textbox both are in EditTmplate
Javascript code is as below
<script type="text/javascript">
function myFun(txtControl) {
var v = document.getElementById("<%=" + txtControl + "%>");
alert(v);
}
When i m changing dropdownlist index function is called and alert is showing null.
So can anyone please suggest me what i m doing wrong??
I don't think you want the server-side tags in your getElementById call:
var v = document.getElementById(txtControl);

Categories

Resources