开发者

How to databind a dropdownlist at page load

Assuming i have two dropdownlists namely: dropdownlistA and dropdownlistB. at page load, i bind values to dropdownlistA. however, depending on the value selected or displayed in dropdownlistA, i want to bind data to dropdownlistB.

Currently, i can bind data to dropdownlistA alright and i already have the required dataset and datatable bind data to dropdownlist. However, dropdownlistB does not bind at page load since the criteria for filling the dataset to bind dropdownlistB (which is the value of dropdownlistA) is not selected. how can i make this wwork.

I am currently considered if this might work. If i were to call the databind for dropdownlistA in a different declared method besides its binding in page load, and select the value from bind in the declared method, would any value be selected?

For example: In during page load, i call the a method that returns dataset values which i bind to dropdownlistA(caseIDDropDownList). then i call another method (CreateexhibitDataSet()) which contains the dataset values for binding dropdownlistB(exhibitDropDownList). however, i need to define a criteria in the CreateExhibitDataset() method which i will use to generate the dataset values to bind dropdownlistB. if i were to call for the data bind of dropdownlistA(caseIDDropdownList) again in the CreateExhibitDataset() method and pick the value in the dropdown list, would i get any values?

How can i work around this to bind both dropdownlists on page load?

protected void Page_Load(object sender, EventArgs e)
    {
        //mgrID = "M510";
        //mgrID = Request.QueryString["mgrID"];
        mgrID = (string)(Session["userID"]);

        if (mgrID != null)
        {
            if (!IsPostBack)
            {
                CreateCasesDataset();
                DataView caseDataView = new DataView(caseDataSet.Tables[0]);
                caseIDDropDownList.DataSource = caseDataView;
                caseIDDropDownList.DataTextField = "CaseID";
                caseIDDropDownList.DataBind();

                CreateExhibitDataset();

                DataView exhibDataView = new DataView(exhibitDataSet.Tables[0]);
                exhibitsDropDownList.DataSource = exhibDataView;
                exhibitsDropDownList.DataTextField = "ExhibitID开发者_Go百科";
                exhibitsDropDownList.DataBind();
            }
        }
        else
        {
            string message = "The System couldnt identify you with any ID. Please Log in to access system functions";
            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());
        }

    }

And this is the additional code of the CreateExhibitMethod

private void CreateExhibitDataset()
    {
        caseIDDropDownList.DataBind();
        string selectedCaseID = caseIDDropDownList.SelectedValue.ToString();

        SqlConnection exhibitConnection = new SqlConnection(strConn);
        exhibitSqlDataAdapter.SelectCommand = new SqlCommand("SELECT ExhibitID FROM Exhibits WHERE CaseID = '"+selectedCaseID+"'", exhibitConnection);
        exhibitSqlDataAdapter.Fill(exhibitDataSet);
    }


You can also use the Page_LoadComplete event to help accomplish this. It has the benefit of firing after the Load but before other page driven events. I would recommend keeping your bind of DropDownListB in a separate method, then if !IsPostBack call that method from the Page_LoadComplete method. Otherwise use @WraithNath's idea of calling that method from the SelectedIndexChanged event.


If you set DropDownList A to AutoPostback, then wire up the SelectedIndexChangedEvent.

eg:

protected void DropDownListA_SelectedIndexChanged(object sender, EventArgs args)
{
   //Get value from list A
   string sValue = DropDownListA.SelectedValue.toString();

  //Get the data related to the selected Value in A
  Datatable Data = DataManager.GetList(sValue);

//Bind the list B
 DropDownListB.DataSource = Data;
DropDownListB.DataBind();
}

EDIT: if you really want to bind both lists on page load you could store all the values in a javascript array and add and remove values based on the selections but you would have to do it all in javascript


I think you don't want dropdownlistB to be bound at page load because you do not know which items to bound to. You can use an asp.UpdatePanel to do this, but this requires you to configure Ajax. You can also consider jQuery for this: Bind the change event:

$(document).ready(function() {
    $('#dropdownlistA').change(getdropdownlistB);
});

 function getdropdownlistB() {
            var ID= $("#getdropdownlistA").attr("value");
 dropdownlistB= $('#dropdownlistB').attr('disabled', true).children('option').remove().end().append('<option value="0">Loading...</option>');

            PageMethod("my.aspx/getdropdownlistBbyID", ["ID", ID], getdropdownlistBResponse)
        }

function PageMethod(wsurl, paramArray, onSuccess) {
            var pagePath = window.location.pathname;
            //Create list of parameters in the form:  
            //{"paramName1":"paramValue1","paramName2":"paramValue2"}  
            var paramList = '';
            if (paramArray.length > 0) {
                for (var i = 0; i < paramArray.length; i += 2) {
                    if (paramList.length > 0) paramList += ',';
                    paramList += '"' + paramArray[i] + '":"' + paramArray[i + 1] + '"';
                }
            }
            paramList = '{' + paramList + '}';
            //Call the page method
            $.ajax({
                type: "POST",
                url: wsurl,
                contentType: "application/json; charset=utf-8",
                data: paramList,
                dataType: "json",
                async: false,
                success: onSuccess,
                error: function(xhr, status, error) {
                    alert("error")
                }
            });
        }

 function getdropdownlistBResponse(response) {
            var listB= (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;
            var dropdownlistB= $('#dropdownlistB');
            dropdownlistB.attr('disabled', false).children('option').remove();
            if (listB.length == 0) { dropdownlistB.attr('disabled', true).append('<option value="0">Select A...</option>'); }
            for (var i = 0; i < listB.length; i++) {
                var val = listB[i].bVal;
                var text = listB[i].bText;
                var def = listB[i].Default;

                dropdownlistB.append('<option value="' + val + '">' + text + '</option>');
                if (def) { dropdownlistB.val(val); } //set the default
            }

        }

Then in the ASPX page you get the data for dropdownlistB:

[WebMethod]
        public static List<listB> getdropdownlistBbyID(string ID)
            //called from script to get the dropdownlistB, using the selection ID from dropdownlistA
        {

           .. Insert code to get your data
            List<listB> blist= new List<listB>() { };
            ...Insert code to fill blist with your data with rows of 3 values {ID, text, default yes/no}


            return blist;
        }


Try setting the dropdownlistA listindex to the first value (e.g. index = 0) and then fire your auto-fill routine for listB

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜