Reputation: 121
I am executing this code:
private string _ejecutarSentencia(string query, SqlConnection cnn)
{
string resultado = string.Empty;
Logica logica = new Logica();
try
{
using (SqlCommand command = new SqlCommand(query, cnn))
{
command.CommandType = CommandType.Text;
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
try
{
resultado += reader.GetValue(0).ToString().Trim() + "\n";
}
catch
{ }
}
}
}
}
catch { }
return resultado;
}
But it only returns me one value (in this example "01\n") and the same query on the same connection executed on sql management studio returns me:
Code
01
02
03
04
I want the function to return all the rows like this:
"01\n02\n03\n04\n"
Using .Net Framework 2.0 and Windows Forms in VS 2012.
Thanks.
Upvotes: 0
Views: 253
Reputation: 155
You mentioned in your comment that the while loop is only processing once, remove the try catch blocks which should allow the exception to pop in your IDE
private string _ejecutarSentencia(string query, SqlConnection cnn)
{
string resultado = string.Empty;
Logica logica = new Logica();
using (SqlCommand command = new SqlCommand(query, cnn))
{
command.CommandType = CommandType.Text;
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
resultado += reader["Code"].ToString().Trim() + "\n";
}
}
}
}
return resultado;
}
Upvotes: 0
Reputation: 56
if your opera Consist data like this
Sl Col1 Col2 Col3
1 KB Keyboard 20.00
2 JS JOYstick 20.00
Your code gets 1\nKB\nKeyboard\n20.00
thn stops by throwing error
Upvotes: 0
Reputation: 186813
It seems that you don't want i
variable while reading cursor:
// Do not use String when concatinating many chunks, but StringBuilder
StringBuilder resultado = new StringBuilder();
...
using (SqlDataReader reader = command.ExecuteReader()) {
while (reader.Read())
resultado.AppendLine(reader.GetValue(0).ToString().Trim());
}
...
return resultado.ToString();
Upvotes: 1
Reputation: 33867
This code is wrong:
int i = 0;
while (reader.Read())
{
try
{
resultado += reader.GetValue(i).ToString().Trim() + "\n";
}
catch
{ }
i++;
}
You increment the i value for each row in your resultset, but this means that for your second row, you are trying to access a value in 'column' 2. Given your resultset, this will fail.
Also, and this is the very wrong bit, you have an empty catch in your code, which will hide all this. Empty catches that just swallow exceptions are nearly always a bad idea and may result in the poor fool that has to maintain that hunting you down in the future.
Upvotes: 0
Reputation: 3874
You are increasing i each readed record. In your code i is intended to access to a field by position. I think that you don't need i variable. Try this to retrieve allways the first column:
resultado += reader.GetValue(0).ToString().Trim() + "\n";
Also: avoid using empty catch. If you don't know what to do with the exception, let it to flow.
Upvotes: 1