【问题标题】:Filling a List<string> with MySQL Query用 MySQL 查询填充 List<string>
【发布时间】:2015-03-19 15:23:54
【问题描述】:

我正在尝试用列表填充 ComboBox。我之前会使用“SELECT code FROM country;”从我的数据库中填充数据的列表;作为查询。

      string MyConString =
         "SERVER=localhost;" +
         "DATABASE=world;" +
         "username=root;" +
         "PASSWORD=1111;";

        string sql = "SELECT code FROM country;";


        MySqlConnection connection = new MySqlConnection(MyConString);
        MySqlCommand cmdSel = new MySqlCommand(sql, connection);
        DataTable dt = new DataTable();
        MySqlDataAdapter da = new MySqlDataAdapter(cmdSel);
        da.Fill(dt);

        List<string> data = new List<string>();

如何填写数据?我已经尝试了很多东西,它只是无法正常工作。

【问题讨论】:

  • 显示您也尝试过什么,并准确解释它是如何不起作用的。
  • atm 无法正常工作你能详细说明吗?
  • 你有整个 DataTable 的数据,用它做你的事情。
  • 只需遍历查询结果并将您想要的内容添加到列表中。
  • 循环或使用linq,见stackoverflow.com/questions/4104464/…

标签: c# mysql string list combobox


【解决方案1】:

Calling AsEnumerable on a DataTable returns an object which implements the generic IEnumerable&lt;T&gt;,既然你只有一列,我认为这应该可以;

List<string> data = dt.AsEnumerable()
                      .Select(r => r.Field<string>("code"))
                      .ToList();

【讨论】:

    猜你喜欢
    • 2020-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多