Click here to Skip to main content
15,879,474 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello all i am getting following error on click of my button
please check code and let me know,
i have already spent lot of time solving this.
Purpose of this code is to get list of country's based on pincode
my dropdown is coming correct
but after that when i click on button to get my dropdownvalue in c#
it throws this error.

Object reference not set to an instance of an object.


I am getting this error on click of my button.

aspx code

XML
<%@ Page Language="C#" AutoEventWireup="false"  CodeFile="Default.aspx.cs" Inherits="_Default" EnableEventValidation="true"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Bind Dropdownlist with JQuery in asp.net</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
    //function copy() {
    //    document.getElementById("lblCountry").innerHTML = document.getElementById("ddlCountry").value;
    //}
    $(function () {
        $('[id$=txtPin]').change(function () {
            var v = $('[id$=txtPin]').val();
            $.ajax({
                type: "POST",
                contentType: "application/json;charset=utf-8",
                url: "Default.aspx/BindDatatoDropdown",
                data: JSON.stringify({ id: '1', pinCode: v }),
                dataType: "json",
                success: function (data) {
                            $.each(data.d, function (key, value) {
                                $("#ddlCountry").append($("<option></option>").val(value.ID).html(value.Description));
                            });
                },
                error: function (result) {
                    alert("error");
                }
            });
        });


        $('[id$=ddlCountry]').change(function () {

            alert("Handler for .change() called.");
        });
    });
    $(document).ready(function () {

    });
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>

    <asp:TextBox ID="txtPin" runat="server"></asp:TextBox>
    <br />
    <br />
<asp:DropDownList ID="ddlCountry" runat="server" />
     <%--onchange="copy();--%>
    <p>
        <%--<asp:Label ID="lblCountry" runat="server" Text="Label"></asp:Label>--%>
    </p>


            <asp:Button ID="btnGetData" runat="server" OnClick="btnGetData_Click" Text="Get Data" />

</form>
</body>
</html>



C# Code

C#
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Web.Services;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    public class PODetails
    {
        public string ID { get; set; }
        public string Description { get; set; }
    }

    [WebMethod]
    public static PODetails[] BindDatatoDropdown(string id, string pinCode)
    {
        DataTable dt = new DataTable();
        List<podetails> details = new List<podetails>();

        using (SqlConnection con = new SqlConnection("Data Source=SAM-PC;Initial Catalog=BPOPortalProd;Persist Security Info=True;User ID=sa;Password=sudesi123"))
        {
            SqlCommand cmd = new SqlCommand("GetAddressDetails",con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add(new SqlParameter("@id", SqlDbType.VarChar, 100)).Value = id;
            cmd.Parameters.Add(new SqlParameter("@pincode", SqlDbType.VarChar, 100)).Value = pinCode;

            con.Open();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(dt);
            foreach (DataRow dtrow in dt.Rows)
            {
                PODetails country = new PODetails();
                country.ID = dtrow["ID"].ToString();
                country.Description = dtrow["Description"].ToString();
                details.Add(country);
            }

        }
        return details.ToArray();
    }

    protected void btnGetData_Click(object sender, EventArgs e)
    {
        //This line is causing error
        string str = ddlCountry.SelectedItem.Text;
    }
}

Thanks in Advance
Posted
Updated 7-Sep-13 0:31am
v8
Comments
Dholakiya Ankit 7-Sep-13 7:22am    
check ddlCountry.SelectedItem add to watch what u are getting?
sunil mali 7-Sep-13 8:54am    
null
nikhilsreeni 11-Sep-13 2:13am    
compare this line:
data: JSON.stringify({ id: '1', pinCode: 'v' }),
sunil mali 11-Sep-13 5:20am    
compare ?? how?
Dholakiya Ankit 12-Sep-13 3:24am    
which line?

refer this :
This may help you.
aspdotnet-suresh[^]

regards :)
 
Share this answer
 
Comments
sunil mali 12-Sep-13 3:51am    
still we cannot read this value in c#
i found a solution
Hello all,

I created hidenn field in jquery ande allocated dropdown text to hidden field

XML
$('[id$=ddlCountry]').change(function () {
           var selectedOption = $("#ddlCountry option:selected").text();
           $("<input/>", { type: 'hidden', name: 'CountryName' }).val(selectedOption).appendTo("form");

           alert("Handler for .change() called.");
       });



In code behind
i used
Response.Write(Request["CountryName"]);

To read hidden field text
so i got text in my codebehined.
Thanks everyone for participating.

Regards,
SUNIL
 
Share this answer
 

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