【问题标题】:How to databind a dropdownlist at page load如何在页面加载时对下拉列表进行数据绑定
【发布时间】:2011-01-23 16:01:11
【问题描述】:

假设我有两个下拉列表,即:dropdownlistA 和 dropdownlistB。在页面加载时,我将值绑定到 dropdownlistA。但是,根据 dropdownlistA 中选择或显示的值,我想将数据绑定到 dropdownlistB。

目前,我可以将数据绑定到 dropdownlistA 好,并且我已经拥有所需的数据集和数据表将数据绑定到下拉列表。但是,由于未选择填充数据集以绑定 dropdownlistB(即 dropdownlistA 的值)的标准,因此 dropdownlistB 在页面加载时不会绑定。我怎样才能使这个工作。

我目前正在考虑这是否可行。如果我要在页面加载中的绑定之外的其他声明方法中调用 dropdownlistA 的数据绑定,并在声明的方法中从 bind 中选择值,是否会选择任何值?

例如: 在页面加载期间,我调用返回绑定到 dropdownlistA(caseIDDropDownList) 的数据集值的方法。然后我调用另一个方法 (CreateexhibitDataSet()),其中包含绑定 dropdownlistB(exhibitDropDownList) 的数据集值。但是,我需要在 CreateExhibitDataset() 方法中定义一个标准,我将使用它来生成数据集值以绑定 dropdownlistB。如果我在 CreateExhibitDataset() 方法中再次调用 dropdownlistA(caseIDDropdownList) 的数据绑定并在下拉列表中选择值,我会得到任何值吗?

如何解决这个问题,以便在页面加载时绑定两个下拉列表?

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";
                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());
        }

    }

这是 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);
    }

【问题讨论】:

  • 如果它解决了我的问题,我保证接受厚厚的答案...:(

标签: c# asp.net


【解决方案1】:

您也可以使用Page_LoadComplete 事件来帮助完成此操作。它的好处是在 Load 之后但在其他页面驱动的事件之前触发。我建议将 DropDownListB 绑定保留在单独的方法中,然后如果 !IsPostBackPage_LoadComplete 方法调用该方法。否则使用@WraithNath 从SelectedIndexChanged 事件调用该方法的想法。

【讨论】:

  • @Joe---事情是我已经为 dropdownlistA 设置了一个 slectedindexchanged,它会自动绑定 dropdownlistB 的列表。这很好用。但我不确定根据@WraithNath 的帖子,当页面尚未完成加载时,选定的 indexchanged 会如何触发,所以我认为你的建议会很完美。但是我如何声明 page_loadcomplete?
  • 完美运行...但是当我使用喙点时,我意识到从 dropdownlisA 中选择的值是空的。"" 猜想我必须检查是否有任何值实际绑定到 droopdownlistA
  • @Selase - 是的。它与Page_Load(object sender, EventArgs e) 完全一样,只是它是Page_LoadComplete(object sender, EventArgs e)
【解决方案2】:

如果将 DropDownList A 设置为 AutoPostback,则连接 SelectedIndexChangedEvent。

例如:

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();
}

编辑:如果您真的想在页面加载时绑定两个列表,您可以将所有值存储在 javascript 数组中并根据选择添加和删除值,但您必须在 javascript 中完成所有操作

【讨论】:

  • @Wra- 感谢您的回复..非常感谢。这可以在页面加载上工作吗?我为 dropdownlistA 更改了所选索引的类似代码...但是这在回发时会发生。我希望在表单加载时执行此操作...也可以回发,但是在 dropdownlistB 中没有显示任何值,直到我在 dropdownlistA 中选择另一个值然后 selectedindexchanged 为 dropdownlisA 触发并绑定 dropdownlListB
  • 嗨,我不会在页面加载时绑定两个列表。您将在列表 2 中有多余的项目,这只会使页面需要更长的时间来呈现。我将在列表 B 中有 1 个列表项,上面写着“请在列表 A 中选择一个项目”这样的列表实际上是空的,直到在列表 A 中选择了一个项目。如果将两个列表都包装在 asp:UpdatePanel 中,则用户甚至不会注意到回发,当在 A 中选择项目时,列表 B 将加载
【解决方案3】:

我认为您不希望在页面加载时绑定 dropdownlistB,因为您不知道要绑定到哪些项目。 您可以使用 asp.UpdatePanel 来执行此操作,但这需要您配置 Ajax。 您也可以为此考虑 jQuery: 绑定更改事件:

$(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
            }

        }

然后在 ASPX 页面中获取 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;
        }

【讨论】:

    【解决方案4】:

    尝试将 dropdownlistA listindex 设置为第一个值(例如 index = 0),然后为 listB 触发自动填充例程

    【讨论】:

    • @Hor...听起来很吸引人...我在哪里设置这个索引?在页面加载中或何时调用方法来填充 dropdownlistB 的数据集?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多