Click here to Skip to main content
15,914,416 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hello people,

Got into a weird problem, hope experts out here would be able to help.
I am trying to populate a dropdownlist namely ddlStates when the values in the dropdownlist ddlCountry changes.I don't want to use the OnSelectedIndexChanged event of the dropdownlist and AutoPostBack property too.

Hence, I dropped a ScriptManager instance from the AJAX extensions part of the toolbox on to the Default.aspx page and set the EnablePageMethods property as true.
Next, I wrote an event called as onchange for the ddlCountry and called a Javascript function named as ddlCountry_Changed().

In ddlCountry_Changed(), I am trying to call a server-side method named as populateStatesinDefault() as PageMethods.populateStatesinDefault().

The control is going inside that server-side function. The problem is that for PageMethods to be working we need to add [System.Web.Services.WebMethod()] over the method and we need to declare that very method as static.

In static methods, we can't call non static members directly, we would need to make an object reference. Since all my controls are in partial class _Default, I am creating an object of this partial class and trying to access the dropdownlist controls via this object.

But to my surprise, I am getting a NullReference exception. The control ddlCountry when accessed via partial class obj shows as null.
Below are my codes:

Default.aspx:

C#
<head>
    <script language="javascript" type="text/javascript">
    debugger
        function ddlCountry_changed() {
            PageMethods.populateStatesinDefault(onsuccess);
            //alert('hii');
        }
        function onsuccess() {
            alert('success');
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <h2> Let's populate DropDowns using AJAX without AutoPostBack</h2>

        <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
        </asp:ScriptManager>
            <asp:DropDownList ID="ddlCountry" runat="server" CssClass="DropDown" onchange="ddlCountry_changed()">
            </asp:DropDownList>
            <asp:DropDownList ID="ddlStates" CssClass="DropDown" runat="server">
            </asp:DropDownList>
</body>


Default.aspx.cs:

C#
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        DAL obj = new DAL();
        DataTable dt = obj.populateCountry();
        ddlCountry.DataSource = dt;
        ddlCountry.DataTextField = dt.Columns[1].ToString();
        ddlCountry.DataValueField = dt.Columns[0].ToString();
        ddlCountry.DataBind();
      }
    [System.Web.Services.WebMethod()]
    public static void populateStatesinDefault()
    {
            _Default defObj = new _Default();
            int country = int.Parse(defObj.ddlCountry.SelectedItem.Value);//NullReference error over here
            DAL obj2 = new DAL();
            DataTable dt = obj2.populateStates(country);
            defObj.ddlStates.DataSource = dt;
            defObj.ddlStates.DataTextField = dt.Columns[1].ToString();
            defObj.ddlStates.DataValueField = dt.Columns[0].ToString();
            defObj.ddlStates.DataBind();
    }
}


Data Access Layer:

C#
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public class DAL
{
    SqlConnection xconn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStrings"].ToString());
    public DataTable populateCountry()
    {
        SqlDataAdapter da = new SqlDataAdapter("select * from Development.dbo.Country", xconn);
        DataTable dt = new DataTable();
        da.Fill(dt);
        return dt;
    }
    public DataTable populateStates(int selectedCountry)
    {
        SqlDataAdapter da = new SqlDataAdapter("select * from Development.dbo.States where CountryID='"+selectedCountry+"'", xconn);
        DataTable dt = new DataTable();
        da.Fill(dt);
        return dt;
    }
}


Am I missing something? I think that the controls in the page are under the _Default class and hence if we create an object of _Default class and try to access the controls inside a static method, it should work, but strangely it ain't.
Any help or pointers would be greatly appreciated.

-Regards
Anurag
Posted
Updated 16-Apr-13 9:13am
v2

use ajax CascadingDropDown control
 
Share this answer
 
Comments
Anurag Sinha V 17-Apr-13 0:05am    
And what if I dnt wana use the AJAX cascadingdropdown?
[no name] 17-Apr-13 0:26am    
using javascript or jquery and webservice, retrieve information from database and fill dropdown with options tag at client side only
Anurag Sinha V 17-Apr-13 0:43am    
Hmm..thanks for your time mate..will try to do as per your suggestion...
Scroll-to-Load-Data-webservice-javascript
use this reference in this see how html tags are use to load data on page without postback hope it will help you :)
 
Share this answer
 
Hi,

you are instantiating object for _Default class, when you are instantiating a class new memory is created in heap for newly created object, without entering anything in new object for that drop down how you can use it. i think it should provide null exception only

C#
 _Default defObj = new _Default();
int country = int.Parse(defObj.ddlCountry.SelectedItem.Value);
 
Share this answer
 
Comments
Anurag Sinha V 17-Apr-13 1:11am    
So what do u suggest?

-Anurag
Hi,

First Put Contry class for Pass data to Javascript
public class Country
{
    private string _name;
    public string Name
    {
        get { return _name; }
        set { _name = value; }
    }
 
    private string _id;
    public string Id
    {
        get { return _id; }
        set { _id = value; }
    }
}



i prefer- Webmethod that take argument of selected Country ID

Your Javascript

<script language="javascript" type="text/javascript">
   
        function ddlCountry_changed() {
           var e = document.getElementById("ddlCountry");
           var countryID = e.options[e.selectedIndex].value;
            PageMethods.populateStatesinDefault(countryID ,onsuccess);
            //alert('hii');
        }

        function OnSuccess(response) {
           var ddlCountries = document.getElementById("<%=ddlCountries.ClientID %>");
           ddlCountries.options.length = 0;
           AddOption("Please select", "0");
           for (var i in response) {
            AddOption(response[i].Name, response[i].value);
        }

        function AddOption(text, value) {

          var option = document.createElement('<option value="' + value + '">');
          ddlCountries.options.add(option);
          option.innerText = text;

        }
    </script>


And Your Web Method

[System.Web.Services.WebMethod()]
    public static List<country>  populateStatesinDefault(string CountryID)
    {
           
            DAL obj2 = new DAL();
            int country = int.Parse(CountryID);
            DataTable dt = obj2.populateStates(country);
            List<country> countries = new List<country>();
            foreach(DataRow dr in dt.Rows)
            {
             
              Country country = new Country();
 
              country.Name =dr["ContryName"]; //Alter Your DB Column Name
              country.Id = dr["ContryID"];
              countries.Add(country);
            }
            return countries;
    }
</country></country></country>



Thanks

Siva Rm K
 
Share this answer
 
Comments
Anurag Sinha V 17-Apr-13 1:17am    
Hmm..thanks mate..it looks different..I will try it and will update the thread..
-regards
anurag

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900