【问题标题】:Copy dropdownlist from another list with DataTextField and DataValueField使用 DataTextField 和 DataValueField 从另一个列表复制下拉列表
【发布时间】:2012-12-20 09:23:06
【问题描述】:

我创建了一个数据层方法

  public static List<SegmentBL> GetAllSegment(string SortDirection, string SortExpression)
    {

        var ds = DBHelper.GetDatabase().ExecuteDataSet("UDS_Select_SegmentMaster");

        var val = ds.Tables[0].AsEnumerable().Select(r => new SegmentBL
        {
            _SegmentId = Convert.ToInt32(r[0].ToString()),
            _SegmentName = r[1].ToString()
        });
        List<SegmentBL> list = val.ToList();
        return list;
    }

由此我创建了一个业务逻辑方法

public DropDownList GetAll(string SortDirection, string SortExpression)
    {
        var list = new DropDownList();
        list.DataSource = SegmentDL.GetAllSegment(SortDirection, SortExpression);
        list.DataTextField = "_SegmentName";
        list.DataValueField = "_SegmentID";
        list.DataBind();
        ListItem item = new ListItem();
        item.Text = "--Select--";
        item.Value = "0";
        list.Items.Insert(0, item);
        return list;
    }

最后是用于填充下拉列表的表示层方法

 private void FillSegment()
    {
        ddlSegment.DataSource = seg.GetAll(General.SortAscending,"SegmentID").Items;

        ddlSegment.DataBind();
        ddlSegment.DataTextField = "_SegmentName";
        ddlSegment.DataValueField = "_SegmentID";
    }

除了 DataTextField 和 DataValueField 没有正确分配外,它工作正常。目前 DataTextField 和 DataValueField 相同。我在上面的代码中犯了什么错误。

【问题讨论】:

  • 不确定业务逻辑是否应该创建 UI 元素 - 您是否可以将数据源项返回到表示层。尝试将同一事物绑定两次似乎不合逻辑。
  • 因为同一行代码我在我的应用程序中使用了超过 20 次。

标签: c# asp.net drop-down-menu


【解决方案1】:

在元素被添加到数据源绑定之前,您是在元素被添加之后绑定的。您可以将pass dropdownlist 添加到您的方法中,而不是在GetAll 方法中创建本地下拉列表。

public DropDownList GetAll(string SortDirection, string SortExpression, DropDownList list)
{
  //  var list = new DropDownList(); //Remove this line
    list.DataSource = SegmentDL.GetAllSegment(SortDirection, SortExpression);
    list.DataTextField = "_SegmentName";
    list.DataValueField = "_SegmentID";      
    ListItem item = new ListItem();
    item.Text = "--Select--";
    item.Value = "0";
    list.Items.Insert(0, item);
    list.DataBind();
    return list;
}

【讨论】:

  • 嘿,我需要在那里传递 ref DropDownList List 作为参数。
【解决方案2】:

移动 Databind() 行。

private void FillSegment()
    {
        ddlSegment.DataSource = seg.GetAll(General.SortAscending,"SegmentID").Items;


        ddlSegment.DataTextField = "_SegmentName";
        ddlSegment.DataValueField = "_SegmentID";

        ddlSegment.DataBind(); //After and not before defining the fields value
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-15
    • 1970-01-01
    • 2011-10-17
    相关资源
    最近更新 更多