我正在尝试将本地数据库中的列显示到下拉列表中。问题是,我需要拆分数据,这样它们就不会全部显示在一行中。我使用“;”分隔数据,然后使用split(“;”)方法分隔它们。我试过下面写的代码,但它不起作用。任何帮助都将不胜感激。

public string DisplayTopicNames()
{
    string topicNames = "";

    // declare the connection string
    string database = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|/Forum.accdb;Persist Security Info=True";

    // Initialise the connection
    OleDbConnection myConn = new OleDbConnection(database);
    //Query
    string queryStr = "SELECT TopicName FROM Topics";
    // Create a command object
    OleDbCommand myCommand = new OleDbCommand(queryStr, myConn);
    // Open the connection
    myCommand.Connection.Open();
    // Execute the command
    OleDbDataReader myDataReader = myCommand.ExecuteReader();

    // Extract the results
    while (myDataReader.Read())
    {
        for (int i = 0; i < myDataReader.FieldCount; i++)
            topicNames += myDataReader.GetValue(i) + " ";
        topicNames += ";";
    }

    //Because the topicNames are seperated by a semicolon, I would have to split it using the split()
    string[] splittedTopicNames = topicNames.Split(';');
    // close the connection
    myCommand.Connection.Close();

    return Convert.ToString(splittedTopicNames);
}

最佳答案

您只返回表中的一列。
没有理由在字段计数上使用for循环(它总是1)
相反,您可以使用List(Of String)保存找到的行返回的值。
然后返回此列表作为下拉列表的数据源

List<string> topicNames = new List<string>();
// Extract the results
while (myDataReader.Read())
{
    topicNames.Add(myDataReader.GetValue(0).ToString();
}
....
return topicNames;

但是,不清楚字段TopicName是否包含用分号分隔的字符串。
在这种情况下,您可以写:
List<string> topicNames = new List<string>();
// Extract the results
while (myDataReader.Read())
{
    string[] topics = myDataReader.GetValue(0).ToString().Split(';')
    topicNames.AddRange(topics);
}
...
return topicNames;

如果您希望返回字符串数组,那么只需将列表转换为数组
return topicNames.ToArray();

编辑
当然,返回数组或列表(字符串)需要更改方法的返回值
 public List<string> DisplayTopicNames()
 {
     ......
 }


 public string[] DisplayTopicNames()
 {
     ......
 }

如果仍然希望返回用分号分隔的字符串,请按以下方式更改return语句
 return string.Join(";", topicNames.ToArra());

07-24 09:37
查看更多