C# 从数据表填充SelectList

C# 从数据表填充SelectList,c#,asp.net,asp.net-mvc,C#,Asp.net,Asp.net Mvc,我运行了一个查询并返回了一个数据表 myDataAdapter.Fill(myDataTable); 现在,将行值“Value”和“Text”加载到SelectList中的最佳方法是什么 谢谢假设您的数据表有两列(文本和值),您必须 1. Set the DropDownList's DataSource to the table 2. Set the DataTextField to the text column name 3. Set the DataValueField to the

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

myDataAdapter.Fill(myDataTable);
现在,将行值“Value”和“Text”加载到SelectList中的最佳方法是什么


谢谢

假设您的数据表有两列(文本和值),您必须

1. Set the DropDownList's DataSource to the table
2. Set the DataTextField to the text column name
3. Set the DataValueField to the value column name
4. Call the Databind method

这是我想到的,它似乎工作得很好,但我想知道这是否是最好的方法

首先,我创建了一个对象,它看起来像我的查询结果

public class MyTestObj
{
    public string Value_CD { get; set; }
    public string Text_NA { get; set; }
}
然后我创建一个ILIST并用datatable行填充它

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");
IList MyList=new List();
foreach(myDataTable.Rows中的DataRow mydataRow)
{
添加(新的MyTestObj()
{
Value_CD=mydataRow[“Value”].ToString().Trim(),
Text_NA=mydataRow[“Text”].ToString().Trim()
});
}
返回新的选择列表(MyList、“Value\u CD”、“Text\u NA”);

对这种方法有什么评论吗?

看起来不错。通过为接受数据行的MyTestObj创建一个构造函数,我会使它更干净一些。这样你就可以写:

MyList.Add(new MyTestObj(mydataRow));
publicstaticsystem.Web.Mvc.SelectList DT2SelectList(DataTable dt,string valueField,string textField){
如果(dt==null | | valueField==null | | valueField.Trim().Length==0
||textField==null | | textField.Trim().Length==0)
返回null;
var list=新列表();
对于(int i=0;i

我写这篇文章是为了u

我找不到直接将DataTable绑定到SelectList的方法,所以我决定创建一个扩展方法来实现这一点:

public static SelectList ToSelectList(this DataTable table, string valueField, string textField)
{
    List<SelectListItem> list = new List<SelectListItem>();

    foreach (DataRow row in table.Rows)
    {
        list.Add(new SelectListItem() 
        {
            Text = row[textField].ToString(), 
            Value = row[valueField].ToString()
        });
    }

    return new SelectList(list, "Value", "Text");
}
公共静态选择列表到选择列表(此数据表、字符串值字段、字符串文本字段)
{
列表=新列表();
foreach(table.Rows中的DataRow行)
{
添加(新建SelectListItem()
{
Text=行[textField].ToString(),
Value=行[valueField].ToString()
});
}
返回新的SelectList(列表,“值”、“文本”);
}

我现在回答这个问题已经太迟了,但我认为这可能是一个优化的方法,希望它能起作用

List<SelectListItem> listName= new List<SelectListItem>();

for (int i = 0; i < datatableName.Rows.Count; i++)
   {
     listName.Add(new SelectListItem { Text = datatableName.Rows[i]["ColumnName"].ToString(), Value = datatableName.Rows[i]["ColumnName"].ToString() });
   }
List listName=new List();
对于(int i=0;i
您还可以通过应用另一个循环并将其用作datatable的列标识符处的索引来循环列名


谢谢。

数据表包含扩展方法AsDataView。您可以使用此扩展方法从数据表填充SelectList。代码示例:

DataTable dt = new DataTable();
dt.Columns.Add("Id", typeof(string));
dt.Columns.Add("Name", typeof(string));
dt.Rows.Add("1", "test");
//populate selectlist with DataTable dt
var selectList = new SelectList(dt.AsDataView(), "Id", "Name");

这里IdSelectList中是selectedValue列,NameDisplayMember列。

完全在“Dot Net Developer”回答中,我添加了他/她的解决方案的完整实现:

 /// <summary>
    /// retrieve the document types from the database
    /// </summary>
    /// <returns></returns>
    private SelectList FillDocumentTypes()
    {
        SqlCommand command = null;
        SqlConnection _sqlcon = null;
        SelectList result = null;
        try
        {
            _sqlcon = new SqlConnection(connectionString);
            string commandText = string.Concat("select Code, [Description] from tblC2scDocumentTypeCodes");

            command = new SqlCommand(commandText, _sqlcon);
            _sqlcon.Open();
            SqlDataAdapter dataAdapter = new SqlDataAdapter(commandText, _sqlcon);

            DataTable dataTable = new DataTable();

            dataTable.Locale = System.Globalization.CultureInfo.InvariantCulture;
            dataAdapter.Fill(dataTable);

            //populate selectlist with DataTable dt
            result = new SelectList(dataTable.AsDataView(), "Code", "Description");

            _sqlcon.Close();
            return result;

        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine(ex.Message);
          }
        finally
        {
            command.Dispose();
            _sqlcon.Dispose();
        }

    }
//
///从数据库中检索文档类型
/// 
/// 
private SelectList FillDocumentTypes()
{
SqlCommand=null;
SqlConnection _sqlcon=null;
SelectList结果=null;
尝试
{
_sqlcon=新的SqlConnection(connectionString);
string commandText=string.Concat(“从tblC2scDocumentTypeCodes中选择代码,[说明]);
command=newsqlcommand(commandText,_sqlcon);
_sqlcon.Open();
SqlDataAdapter dataAdapter=新的SqlDataAdapter(commandText,_sqlcon);
DataTable=新的DataTable();
dataTable.Locale=System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(dataTable);
//用数据表dt填充selectlist
结果=新的选择列表(dataTable.AsDataView(),“代码”,“说明”);
_sqlcon.Close();
返回结果;
}
捕获(例外情况除外)
{
系统.诊断.调试.写入线(例如消息);
}
最后
{
command.Dispose();
_sqlcon.Dispose();
}
}

忘了提到我是在MVC中做这件事的,而不是使用控件啊,这是一条非常重要的信息。您可能想编辑您的帖子。这是asp.net方法,而不是asp.NETMVC。
 /// <summary>
    /// retrieve the document types from the database
    /// </summary>
    /// <returns></returns>
    private SelectList FillDocumentTypes()
    {
        SqlCommand command = null;
        SqlConnection _sqlcon = null;
        SelectList result = null;
        try
        {
            _sqlcon = new SqlConnection(connectionString);
            string commandText = string.Concat("select Code, [Description] from tblC2scDocumentTypeCodes");

            command = new SqlCommand(commandText, _sqlcon);
            _sqlcon.Open();
            SqlDataAdapter dataAdapter = new SqlDataAdapter(commandText, _sqlcon);

            DataTable dataTable = new DataTable();

            dataTable.Locale = System.Globalization.CultureInfo.InvariantCulture;
            dataAdapter.Fill(dataTable);

            //populate selectlist with DataTable dt
            result = new SelectList(dataTable.AsDataView(), "Code", "Description");

            _sqlcon.Close();
            return result;

        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine(ex.Message);
          }
        finally
        {
            command.Dispose();
            _sqlcon.Dispose();
        }

    }