Hemant Sisodia Hemant Sisodia - 2 months ago 20
ASP.NET (C#) Question

How to call 'onchange' event of asp.net listbox after its codebehind function is called

I have a Listbox defined as:

<asp:ListBox ID="lst_Agenda" onchange="drawChart()" OnSelectedIndexChanged="lst_Agenda_SelectedIndexChanged" SelectionMode="Multiple" CssClass="txt12 myListBox" AutoPostBack="true" DataTextField="Name" runat="server" Width="100%" Height="100%" />


After we select some items in this, lst_Agenda_SelectedIndexChanged method of codebehind is called which calls some other ListBoxes to be populated in cascading way. There is a function in Javascript named as drawChart which generates a Chart based on values selected in all these ListBoxes.

Hence I want that codebehind function should be called before the javascript function call on listbox changed event. But currently it is happening just opposite, Javascript function drawChart gets called first without filling values in the listboxes.

I tried calling Javascript function from codebehind method directly by using:

ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "myscript", "drawChart()", true);


But using this gives me null values for any 'document.getElementById' call.

The Codebehind Function and JS call is as:

protected void lst_Agenda_SelectedIndexChanged(object sender, EventArgs e)
{
lst_Agenda_Changed();

foreach (ListItem li in lst_SubAgenda.Items)
li.Selected = true;

foreach (ListItem li in lst_Doctors.Items)
li.Selected = true;

lst_SubAgenda_Changed();

lst_Group_Changed();

//ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "myscript", "drawChart()", true);
}


The Javascript for drawChart is as:

function drawChart() {
var tempDateToWeek = "";
var tempDateToYear = "";
var DateOfWeek = new Date();

tempDateToWeek = document.getElementById('txtRangeTo').value.substring(0, 2);
tempDateToYear = document.getElementById('txtRangeTo').value.substring(6, 10);
...........


I am getting error in drawChart if I call it from codebehind at line where I fill variable tempDateToWeek by value of document.getElementById('txtRangeTo').

So how can I achieve this?

Answer

You should call RegisterStartupScript instead of RegisterClientScriptBlock in your event handler in code-behind. It will cause the Javascript code to be executed once the page has loaded after the postback, so that the DOM elements will be accessible with document.getElementById.

protected void lst_Agenda_SelectedIndexChanged(object sender, EventArgs e)
{
    lst_Agenda_Changed();

    foreach (ListItem li in lst_SubAgenda.Items)
        li.Selected = true;

    foreach (ListItem li in lst_Doctors.Items)
        li.Selected = true;

    lst_SubAgenda_Changed();
    lst_Group_Changed();

    ScriptManager.RegisterStartupScript(this, GetType(), "DrawChart", "drawChart();", true);
}

The onchange event handler should also be removed from the DropDownList to avoid calling the client code before the postback.

Comments