Populating a SelectList from a DataTable

前端 未结 8 1064
说谎
说谎 2020-12-18 11:12

I ran a query and returned a datatable,

myDataAdapter.Fill(myDataTable);

Now what is the best way to load the row values \"Value\" and \"Te

相关标签:
8条回答
  • 2020-12-18 11:35
        public static System.Web.Mvc.SelectList DT2SelectList(DataTable dt, string valueField, string textField){            
            if (dt == null || valueField == null || valueField.Trim().Length == 0
                || textField == null || textField.Trim().Length ==0)
                return null;
    
    
            var list = new List<Object>();
    
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                list.Add(new
                {
                    value = dt.Rows[i][valueField].ToString(),
                    text = dt.Rows[i][textField].ToString()
                });
            }
            return new System.Web.Mvc.SelectList(list.AsEnumerable(), "value", "text");
        }
    

    I wrote this for u

    0 讨论(0)
  • 2020-12-18 11:40

    Looks fine. I would make it a bit cleaner by creating a constructor for MyTestObj that accepted a DataRow. That would allow you to write:

    MyList.Add(new MyTestObj(mydataRow));
    
    0 讨论(0)
提交回复
热议问题