【问题标题】:Splitting the data in ASP.NET在 ASP.NET 中拆分数据
【发布时间】:2013-04-12 20:02:54
【问题描述】:

我正在尝试将本地数据库中的列显示到下拉列表中。问题是我需要拆分数据,以便它们不会全部显示在一行中。我用过“;”分离数据,然后使用 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);
}

【问题讨论】:

  • 你真的应该从数据库中获取数据,关闭你的连接,然后操作它。
  • 您可以只返回拆分字符串数组而不是将它们转换为字符串吗?
  • @Tim nope,它不会让我

标签: c# asp.net database drop-down-menu split


【解决方案1】:

您只返回表格中的一列。
没有理由对字段计数使用 for 循环(始终为 1)
相反,您可以使用 List(Of String) 来保存找到的行返回的值。
然后返回此列表以用作 DropDownList 的数据源

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();

编辑
当然返回数组或 List(Of String) 需要更改方法的返回值

 public List<string> DisplayTopicNames()
 {
     ......
 }

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

如果你仍然喜欢返回一个用分号分隔的字符串,那么用这种方式改变return语句

 return string.Join(";", topicNames.ToArra());

【讨论】:

  • hmm,你的代码很清晰,很有意义。但我想写“return Convert.ToString(topicNames);”在行尾?
  • 这取决于调用代码的预期以及该代码是否可以更改。 List(Of String) 是比数组更好的方法,但在某些情况下,数组是预期的,您无法更改。
  • 它不会让我只做“return topicNames”或“return topicNames.ToArray()”
  • 它给了我一个错误错误“无法将类型'System.Collections.Generic.List'隐式转换为'string'”
  • @user123,您必须将方法的返回类型更改为string[]。这里的问题是您正在读取已经分离的数据,然后将其与; 串在一起,然后在方法结束时再次拆分该字符串。这只是没有意义。如果您的DropDownList 在此处可供您使用,则像我所说的那样将其添加到内联,如果不是,则返回List&lt;string&gt;string[] 并在调用代码中绑定到它。
【解决方案2】:

除非我失去理智,否则这样的事情应该可以工作:

while (myDataReader.Read())
{
    for (int i = 0; i < myDataReader.FieldCount; i++)
        ddl.Items.Add(myDataReader.GetValue(i))
}

其中ddl 是您的DropDownList 的名称。如果您的ddl 在此处不可用,则将它们添加到List&lt;string&gt; 集合中并返回。然后这段代码现在可能变得无关紧要:

//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);

但是,除此之外,我想为您稍微重构一下代码,因为您需要利用 using 之类的东西。

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 
    using (OleDbConnection myConn = new OleDbConnection(database))
    {
        myConn.Open();

        // Create a command object 
        OleDbCommand myCommand = new OleDbCommand("SELECT TopicName FROM Topics", myConn);

        // Execute the command 
        using (OleDbDataReader myDataReader = myCommand.ExecuteReader())
        {
            // Extract the results 
            while (myDataReader.Read())
            {
                for (int i = 0; i < myDataReader.FieldCount; i++)
                {
                    ddl.Items.Add(myDataReader.GetValue(i));
                }
            }
        }
    }

    // not sure anything needs returned here anymore
    // but you'll have to evaluate that
    return "";
}

您想要利用using 语句的原因是确保DataReaderConnection 中存在的非托管资源得到正确处理。当离开using 语句时,它会自动调用对象上的Dispose。此语句仅用于实现IDisposable 的对象。

【讨论】:

    【解决方案3】:

    我认为这应该可行:

    public List<string> DisplayTopicNames()
    {
        List<string> topics = new List<string>();
    
        // Initialise the connection 
        OleDbConnection conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|/Forum.accdb;Persist Security Info=True");
        OleDbCommand cmd = new OleDbCommand("SELECT TopicName FROM Topics");
        using(conn)
        using(cmd)
        {
            cmd.Connection.Open();
            // Execute the command 
            using(OleDbDataReader myDataReader = cmd.ExecuteReader())
            {
                // Extract the results 
                while(myDataReader.Read())
                {
                topics.Add(myDataReader.GetValue(0).ToString());
            }
        }
    }
    
    return topics;
    

    }

    【讨论】:

    • 你能解释一下“using(conn)”和“using(cmd)”的用法吗
    • @user123 确定。 using(conn) 在超出范围时自动释放连接。这意味着您不必显式调用 conn.Close() 。本质上,在 finally 中使用 conn.Dispose() 将其包装在 try/finally 中。
    • 好的,谢谢您的帮助。但是另一篇文章稍微清楚了一点。再次感谢:) 真的很感激
    猜你喜欢
    • 2013-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多