简体   繁体   中英

Copy dropdownlist from another list with DataTextField and DataValueField

I create one datalayer method

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

from that I create one Bussiness logic method

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

Finally Presentation Layer Method for filling dropdownlist

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

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

It's working fine except the DataTextField and DataValueField not assign properly. Currently DataTextField and DataValueField same. What is mistake I did in above code.

You are binding before the elements are added to the datasource bind after the elements being added. You may pass dropdownlist to your method intead of creating local drop down in GetAll method.

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

Move the Databind() line.

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
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM