0

I'm using Asp.Net with C#. I want to add Database names to DropDownList at Runtime. Here is the code.

Code Behind:

    [WebMethod]
    public void GetDdlList()
    {
    if (!String.IsNullOrEmpty(txtServer.Text.ToString()))
    ServerName = txtServer.Text.ToString();
    if (!String.IsNullOrEmpty(txtUnm.Text.ToString()))
    UserName = txtUnm.Text.ToString();
    if (!String.IsNullOrEmpty(txtPwd.Text.ToString()))
    Pwd = txtPwd.Text.ToString();
    SqlConnection conn = new SqlConnection("Data Source=" + ServerName + ";User ID=" +  UserName + ";Password=" + Pwd);
    SqlCommand cmd = new SqlCommand();
    cmd.Connection = conn;
    cmd.CommandText = "SELECT name FROM sys.databases";
    cmd.CommandType = CommandType.Text;
    conn.Open();
    SqlDataReader rdr = cmd.ExecuteReader();
    while (rdr.Read())
    {
       ddlDbnm.Items.Add(rdr.GetString(0).ToString());
    }
    conn.Close();
    }

Script:

<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript">
    $(document).ready(function () {
        $('#<%= ddlDbnm.ClientID %>').click(function () {
            PageMethod.GetDdlList();
            //alert('hi');
        })
    });
</script>  

When I write GetDdlList() code on button click, it executes successfully. But I don't want to use button click. Instead I want this code to be executed when I click on DropDownList. In above example nothing is happening when I click on Dropdownlist.

7
  • You can populate the dropdownlist on page_load event or button click even.As far as i know DropDownList doesn't have any option to populate it in a way which you want. Commented Jan 28, 2014 at 6:02
  • @Khan, I don't want to implement it on button click. I want to execute it when dropdownlist is focused or clicked. page_load is not useful as connection to server is required generating list of databases. Commented Jan 28, 2014 at 6:07
  • What you can do is just create an image (transparent) and use image button over the dropdown list and create a click event of it. Then hide the image button once it is clicked. Commented Jan 28, 2014 at 6:15
  • @Șhȇkhaṝ, I can make image button transparent but fail to put it over dropdownlist. Can you give me some reference to do so? Commented Jan 28, 2014 at 7:43
  • 1
    @netX here is the fiddle for the same jsfiddle.net/69Jss Commented Jan 28, 2014 at 8:44

3 Answers 3

1

You can get the click event of dropdownlist in jquery and then make an ajax call to your method. The following is the code the get click event of the dropdownlist:

    $(document).ready(function () {
        var isClickToLoad = true;

        $('#<%= ddlDbnm.ClientID %>').click(function () {
            if (isClickToLoad == false) {
                //The following line is not allowing the selection changed value to persist
                //But commenting it out will call the server side code just once 
                //i.e. when first time the dropdownlist is clicked
                //You need to handle it
                isClickToLoad = true;
                return;
            }

            isClickToLoad = false;
            $('#<%= ddlDbnm.ClientID %>').empty();

            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "Default.aspx/GetDdlList",
                data: '{ }',
                dataType: "json",
                success: function (msg) {
                    var options = "";
                    $.each(msg.d, function (index, value) {
                        options = options + "<option>" + value + "</option>";
                    });
                    $('#<%= ddlDbnm.ClientID %>').html(options);
                }
            });
        })
    });

The following is the webmethod code:

    [WebMethod]
    public static List<string> GetDdlList()
    {
        //This can be your call to database. Hard-coded here for simplicity
        List<string> lst = new List<string>();

        lst.Add("aaa");
        lst.Add("bbb");

        return lst;
    }

The link here details out how you can use jquery ajax in your code.

Hope this helps

Sign up to request clarification or add additional context in comments.

6 Comments

No it's not working. I've declared [WebMethod] in code behind and called it from the code you have given using PageMethod.myMethod(). but it's doing nothing.
Did you enable PageMethod in your ScriptManager? Also first check if the above code is working by writing "alert('hi')" in place of "//Your jquery ajax call here". Then add code for PageMethod and create a breakpoint in your method and see if it is getting hit.
I've check. nothing done when clicking on dropdownlist. Not even 'hi' is displayed. It's giving error "Microsoft JScript runtime error: Object expected" when Page Postbacks.
Well it is working fine with me. Can you please edit your question to post the jquery code? BTW I hope you are including the js file for jquery library in your aspx page. Something like the following: <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
I've modified my question. "Microsoft JScript runtime error: Object expected" this error solve. but nothing happen when I click dropdownlist.
|
0

You already have a click event in built with Visual Studio for the ComboBox. Right click on Combox and select properties. In Properties, click Event button (Lightening symbol) and find the event "Click" in it and double click on this even which would automatically create the click event. And you can add the above code to this event and try running it. This should help u in achieving your target. Try this and let me know if this doesnt work for you.

2 Comments

the solution you have given is for windows application and not for web application.
Sorry i didnt notice that.
0

You can use this js to dynamic dropdownlist:

HTML:

<select>
 <option>Select Something</option>
    <option>&nbsp;</option>
    <option>&nbsp;</option>
    <option>&nbsp;</option>
</select>

JavaScript:

$(document).ready(function () {
    var isClickToLoad = true;
    $("select").click(function(e) {
        if (isClickToLoad == false){
            isClickToLoad = true;
            return;
        }
        isClickToLoad = false;
        $("select").empty().html("<option>Loading options</option>");
        setTimeout(function() {
            $.ajax({
                type: "POST",
                url: 'your url',
                traditional: true,
                dataType: "json",
                data: {},
                success: function(resp) {
                    $('select').empty();
                    if (resp.length > 0) {
                        var listItems = [];
                        for (var i = 0; i < resp.length; i++) {
                            listItems.push('<option value="' +
                                resp[i].Value + '">' + resp[i].Text
                                + '</option>');
                        }
                        $('select').append(listItems.join(''));
                    }
                }
            });
            $("select :nth-child(1)").attr("selected", "selected");
        }, 500);
    });
});

demo

2 Comments

thanx for answer but I want to add items at runtime after connecting to database as mentioned in my code. here I can do for only static values.
@netX check edited post. I add ajax-call for dynamic load data

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.