如何从asp.net中的ArrayList值绑定ComboBox?

时间:2014-11-27 11:10:58

标签: c# asp.net

enter image description here

但未填写正确

我还提到了这样的表和代码到图像

代码赞:

        DataTable dtUserType = new Common().GetUserType(true);
        DataTable dtUserType 1= new Common().GetUserTypeByUser(true);

        ArrayList lstUserTypeId =new ArrayList();
        lstUserTypeId.AddRange(dtUserType1.Rows[0]["UserTypeId"].ToString().Split(','));

        DataTable dtDownlist = new DataTable();
        dtDownlist.Columns.Add("UserTypeId");
        dtDownlist.Columns.Add("UserType");
        DataRow dr;


        foreach (string s in lstUserTypeId)
        {
            for (int i = 0; i < dtUserType.Rows.Count; i++)
            {

                dr = dtDownlist.NewRow();
                 //List Of superior List
                if(s.ToString() != dtUserType.Rows[i]["UserTypeId"].ToString())
                {


                    dr["USerType"] = dtUserType.Rows[i]["UserType"].ToString();
                    dr["UserTypeId"] = dtUserType.Rows[i]["UserTypeId"].ToString();
                    dtDownlist.Rows.Add(dr);
                }


            }
        }


        cmbUser.DataSource = dtDownlist; 
        cmbUser.DataTextField = "UserType";
        cmbUser.DataValueField = "UserTypeId";
        cmbUser.DataBind();

1 个答案:

答案 0 :(得分:0)

一般来说:

  1. 不要将主表拆分为子表,每个子表有1列 - 这就是为什么表中有列的原因
  2. 查询数据时 - 使用LINQ
  3. 尽可能不使用DataTable - 观察我在答案中发布了多少个投射操作(在你的情况下使用类型表Common)

    DataTable common = new Common(); // Id, UserType, UserTypeId
    
    var sections = common.Where(c => c.UserType.ToString() == "B").First()
                         .ToString().Split(',');
    
    DataTable dtDownlist = new DataTable();
    dtDownlist.Columns.Add("UserTypeId");
    dtDownlist.Columns.Add("UserType");
    DataRow dr;
    
    
    foreach (string id in sections)
    {
        for (int i = 0; i < dtUserType.Rows.Count; i++)
        {
            if(Convert.ToInt16(id) == Convert.ToInt16(common.Rows[i]["Id"]))
            {
                dr = dtDownlist.NewRow();
    
                dr["USerType"] = dtUserType.Rows[i]["UserType"].ToString();
                dr["UserTypeId"] = dtUserType.Rows[i]["UserTypeId"].ToString();
                dtDownlist.Rows.Add(dr);
            }
        }
    }
    
    
    cmbUser.DataSource = dtDownlist; 
    cmbUser.DataTextField = "UserType";
    cmbUser.DataValueField = "UserTypeId";
    cmbUser.DataBind();