Populating a SelectList from a DataTable

前端 未结 8 1096
说谎
说谎 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:33

    Here is what I came up with it seems to work well, But I was wondering if this is the best way.

    First I created an object that looks like my results form my query,

    public class MyTestObj
    {
        public string Value_CD { get; set; }
        public string Text_NA { get; set; }
    }
    

    Then I create a ILIST and populate it with the datatable rows

    IList MyList = new List();
    foreach (DataRow mydataRow in myDataTable.Rows)
    {
      MyList.Add(new MyTestObj()
      {
        Value_CD = mydataRow["Value"].ToString().Trim(),
        Text_NA  = mydataRow["Text"].ToString().Trim()                      
      });
    }
    
    return new SelectList(MyList, "Value_CD", "Text_NA");
    

    Any comments on this approach?

提交回复
热议问题