【问题标题】:DropDownList not working with SqlDataReaderDropDownList 不适用于 SqlDataReader
【发布时间】:2014-12-03 20:53:43
【问题描述】:

您好,我正在尝试让 DropDownList 与 SqlDataReader 一起使用,但它不填充 DropDownlist。 TextBox.Text 阅读器正在工作。

这是我正在使用的代码:

    using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString))
    {
        SqlCommand command =
        new SqlCommand("SELECT * FROM [datarep].[dbo].[OrderHeader] WHERE [OrderNumber] = '"+OrderNumber+"'", con);
        con.Open();

        SqlDataReader read = command.ExecuteReader();

        while (read.Read())
        {
            TextBox2.Text = (read["CreatedDate"].ToString());
            TextBox3.Text = (read["CreatedBy"].ToString());
            CompanyStored = (read["CustomerID"].ToString());
            TextBox7.Text = (read["Store_Number"].ToString());

            DropDownList1.DataTextField = (read["Year"].ToString());
            DropDownList1.DataBind();



        }
        read.Close();
    }

【问题讨论】:

  • 有多少项目被添加到 DropDownList..? also move your DropDownList1.DataBind();` 在 While 循环之外并查找如何分配 DataSource to the DropdownList
  • 仅添加 1 项 @DJKRAZE
  • 好吧,如果碰巧有更多,我仍然会移动它,也看看这个MDSN Binding Data to DropDownList
  • 谢谢@DJKRAZE
  • 由于您只希望返回一条记录,因此您应该删除while - 这使得您看起来可能有多个记录,这看起来会令人困惑。如果您确定您会获得一条记录,请执行read.Read();。如果你不确定,你可以if (read.Read())。无论哪种方式都清楚地表明您只需填写一次控件。

标签: c# asp.net


【解决方案1】:

假设您的下拉列表中已经填充了年份列表,您需要设置其值而不是设置其 DataTextField - 该属性用于定义文本数据源的列或属性名称,而不是设置选定的值本身。

DropDownList1.SelectedValue = read["Year"].ToString();

如果您还没有填充下拉菜单,那么您必须使用数据源(可能是年份列表)提前填充它。例如,假设您想要 2000 年到 2050 年之间的所有年份,这样的事情可能会奏效:

var dataSource = Enumerable.Range(2000, 51)
   .Select(x => new { TheYear = x })
   .ToArray();

DropDownList1.DataSource = dataSource;
DropDownList1.DataValueField = "TheYear";
DropDownList1.DataTextField = "TheYear";
DropDownList1.DataBind();

请注意,DataTextField 和 DataValue 字段代表数据源中对象的属性。

对于像数字这样简单的东西,您也可以一次填充一个下拉列表,而不是使用数据源 - 最终结果相同。

【讨论】:

    【解决方案2】:

    SqlDataReader 逐行读取您的数据。如果你想使用 DataReader,你必须在每次迭代时向 DDL 添加一个新的列表项

    试试这样:

    while (read.Read())
    { 
        /*code omitted*/
        var item = new ListItem(); 
        item.Text = read["Year"].ToString();
        item.Value = read["Year"].ToString();
        DropDownList1.Items.Add(item);
    }
    

    进一步阅读和替代解决方案:

    【讨论】:

    • 我收到此错误 DataBinding: 'System.Data.Common.DataRecordInternal' does not contain a property with name '2013' @Serv
    • DropDownList1.DataBind();
    • 尝试设置DropDownList1.DataValueField= "Year" DropDownList1.DataTextField = "Year";我现在不确定语法。
    • 谢谢,现在可以使用了!必须添加 DropDownList1.Items.Clear();从多次添加中清除它
    猜你喜欢
    • 1970-01-01
    • 2012-09-14
    • 2014-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多