从数据表填充SelectList [英] Populating a SelectList from a DataTable

查看:77
本文介绍了从数据表填充SelectList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我运行了一个查询并返回了一个数据表,

I ran a query and returned a datatable,

myDataAdapter.Fill(myDataTable);

现在将行值"Value"和"Text"加载到SelectList中的最佳方法是什么?

Now what is the best way to load the row values "Value" and "Text" into a SelectList?

谢谢

推荐答案

这是我想出的效果很好的方法,但是我想知道这是否是最好的方法.

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

然后我创建一个ILIST并用数据表行填充它

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

IList<MyTestObj> MyList = new List<MyTestObj>();
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");

对此方法有何评论?

这篇关于从数据表填充SelectList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆