user123
user123

Reputation: 97

Splitting the data in ASP.NET

I am trying to display a column from my local database into a dropdown list. The problem is that I would need to split the data so that they are not displayed all in one line. I have used the ";" to separate the data and then using the split(";") method to split them. I have tried the code that I've wrote below but it's not working. Any help will be appreciated.

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

Upvotes: 1

Views: 2346

Answers (3)

Steve
Steve

Reputation: 216333

You are returning just one column from the table.
There is no reason to use a for loop over a field count (it is always 1)
Instead you could use a List(Of String) to save the values returned by the rows found.
Then return this list to use as datasource for your DropDownList

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

However it is not clear if the field TopicName contains itself strings separated by semicolon.
In this case you could write:

List<string> topicNames = new List<string>();
// Extract the results 
while (myDataReader.Read())
{
    string[] topics = myDataReader.GetValue(0).ToString().Split(';')
    topicNames.AddRange(topics);
}
...
return topicNames;

if you prefer to return an array of strings then it is just a matter to convert the list to an array

return topicNames.ToArray();

EDIT
Of course returning an array or a List(Of String) requires changes to the return value of your method

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

or

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

if you still prefer to return a string separated by semicolons then change the return statement in this way

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

Upvotes: 2

Codeman
Codeman

Reputation: 12375

I think this should work:

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;

}

Upvotes: 0

Mike Perrenoud
Mike Perrenoud

Reputation: 67918

Unless I've lost my mind, something like this should work:

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

where ddl is the name of your DropDownList. If your ddl isn't available here, then add them to a List<string> collection instead and return that. And then this code may now become irrelevant:

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

but, on top of all this I want to restructure the code for you a little because you need to be leveraging things like 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 "";
}

The reason you want to leverage the using statement is to ensure that unmanaged resources that exist in the DataReader and Connection get disposed properly. When leaving the using statement it will automatically call Dispose on the object. This statement is only used for objects that implement IDisposable.

Upvotes: 0

Related Questions