1

在此处输入图像描述

我正在尝试从列表中按值绑定(选择)一些数据,但这是不可能的。

如您所见,我按此值存储它们:

DataValueField="ID_PROJECT_TYPE_DETAILS"

我有以下html代码:

<asp:ListBox SelectionMode="Multiple" ID="DDLProjectDetails" runat="server" 
                        DataSourceID="SqlDataSource4" DataTextField="DESCRIPTION" 
                        DataValueField="ID_PROJECT_TYPE_DETAILS">
                                    </asp:ListBox>

                    <script type="text/javascript">
                        $(document).ready(function () {
                            $('#<%= DDLProjectDetails.ClientID %>').dropdownchecklist({ width: 248 });
                        });
                    </script>

                    <asp:SqlDataSource ID="SqlDataSource4" runat="server" 
                        ConnectionString="<%$ ConnectionStrings:MesarchConnectionString %>" 
                        SelectCommand="SELECT * FROM [PROJECT_TYPE_DETAILS]"></asp:SqlDataSource>

和代码背后的代码:

string insCmd = "SELECT ID_PROJECT, ID_PROJECT_TYPE_DETAILS FROM PROJECT_TYPE_DETAILS_OF_PROJECT WHERE ID_PROJECT = @IDProject";

...

 dr = com.ExecuteReader();
            while (dr.Read())
            {
                if (DDLProjectDetails.Items.Contains(DDLProjectDetails.Items.FindByValue(dr.GetInt32(1).ToString()))) 
                    DDLProjectDetails.Items.FindByValue(dr.GetInt32(1).ToString()).Selected = true;
            }

并且不会像这样填写我的下拉清单: 在此处输入图像描述

当我运行程序时,我的 DDLProjectDetails 没有显示有任何项目......

4

1 回答 1

1

DDLProjectDetails 的项目集合尚未绑定数据。您所要做的就是调用DataBind(),这样当您的代码涉及到ExecuteReader() ...Items 时,它们就已经被绑定了。

// demo code for one of my tables
string conStr = YOUR_CON_STR;
using (SqlConnection con = new SqlConnection(conStr))
{
    SqlCommand com = new SqlCommand("SELECT [idBenutzer], [benutzerName], [aktiv] FROM [Benutzer]", con);
    con.Open();
    SqlDataReader rdr = com.ExecuteReader();

    DropDownList1.DataBind(); // NECESSARY
    while (rdr.Read())
    {
        Debug.WriteLine(rdr.GetInt32(0) + " " + rdr.GetString(1) + " " + rdr.GetBoolean(2));
        if (DropDownList1.Items.Contains(DropDownList1.Items.FindByValue(rdr.GetInt32(0).ToString())))
        {/* do anything */ }
    }
}
于 2012-09-20T20:32:54.797 回答