Question

My Code

string s = "";
try
{
    myCon.Open();
    myReader = myCommand.ExecuteReader();
    while (myReader.Read())
    {
        s += myReader["UserName"] +  "\n"; // here is the problem, I wish to show ["count"] ["GameDate"] 
    }
    myReader.Close();
    return s;
}
catch (Exception ex)
{
    return ex.StackTrace;
}
finally
{
    myCon.Close();
}

As I have commented, It works well until I try and add the other two columns GameDate and count Like so:

{
    s += myReader["UserName,count"] +  "\n";
}

It dose not read, how would I show both columns.

Was it helpful?

Solution

There are various things I would change about this code - returning a stack trace as if it's valid data obtained with no problems is a really bad idea, for example, and you should use a StringBuilder instead of repeated string concatenation. However, focusing on just the problem at hand...

To retrieve more than one value, you can't just add the columns into what you specify to the indexer. The indexer is meant to retrieve one value from one column. Instead, you need to call the myReader indexer twice - something like this:

s += myReader["UserName"] + " " + myReader["count"] + "\n";

Or to keep the formatting separate from the value retrieval:

s += string.Format("{0} {1}\n", myReader["UserName"], myReader["count"]);

OTHER TIPS

You need to specify each column in a separate statement. Right now, it can't find a column called "UserName,count", so I suppose it throws an exception.

You can change your code like this:

s += myReader["UserName"].ToString() + myReader["count"].ToString() +  "\n";
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top