unreachable code detected on for loop - c#

Tried finding similar from my problem but it seems there are too many unreachable code detectedmy table consist of 4 rows and I tried this code
using (MySqlConnection conn = new MySqlConnection(myConnection))
{
conn.Open();
MySqlCommand cmd = new MySqlCommand(query, conn);
int num = Convert.ToInt32(cmd.ExecuteScalar());
MySqlCommand cmd1 = new MySqlCommand(query2, conn);
MySqlDataReader reader = cmd1.ExecuteReader();
while (reader.Read())
{
for (int a = 0; a <= num; a++)
{
List li = new List();
li.linkLabel1.Text = reader["TitleAnime"].ToString();
flowLayoutPanel1.Controls.Add(li);
// break;
}
}
conn.Close();
}
but it gives me 16 values and thats too much then I tried putting break inside the for loop and I was able to achieve my goal and it gives me 4 values which is the same on my table but there seems to be an error called unreachable code detected..should I ignore it since I was able to get what I need? or is there another way for that

I'm pretty sure you are doing one query too much there, and you are getting NxN results because of that first query and of that for loop.
Try something like this:
using (MySqlConnection conn = new MySqlConnection(myConnection))
{
conn.Open();
MySqlCommand cmd1 = new MySqlCommand(query2, conn);
MySqlDataReader reader = cmd1.ExecuteReader();
while (reader.Read())
{
List li = new List();
li.linkLabel1.Text = reader["TitleAnime"].ToString();
flowLayoutPanel1.Controls.Add(li);
}
conn.Close();
}
If that does the job, consider in changing the name of the query1 and cmd1 to query and cmd since now you'll have only one of each

It's quite simple. You're running a for loop based on the number of entries you have in your database from the command object.
The read method will iterate four times if that's how many records you have in your database. Refer to this article for more information: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.read(v=vs.110).aspx.
In short, just remove the for loop and you'll get the result you want.

Try something like this:
while (reader.Read())
{
flowLayoutPanel1.Controls
.Add(new List { linkLabel1.Text = reader["TitleAnime"].ToString()});
}

Related

How to populate list or array with values from access database

I am trying to populate a group of labels in a C# windows form with some values that are in a certain attribute (PlayerName) in a database that I have in access.
Currently the only code I have is:
OleDbConnection connection = new OleDbConnection(CONNECTION STRING HERE);
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "SELECT PlayerName FROM [TotalPlayerName] WHERE Team = 1 AND SportID = " + Form1.IDNumber;
I need a list or array that holds these values so I can use them to populate the labels, but I am unaware of how to do this.
You need to call ExecuteReader to obtain a data reader and then loop through the rows of the result set like this:
List<string> result = new List<string>();
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
result.Add(reader.GetString(0));
}
}
Before you do this, don't forget to open the connection like this:
connection.Open();
There are a couple of things here..... for sake of best practice well its more standard practice... as I like to say!
Use USING as this cleans up after connection.. see here for great examples in a "using" block is a SqlConnection closed on return or exception?
using (OdbcDataReader DbReader = DbCommand.ExecuteReader())
{
int fCount = DbReader.FieldCount;
while (DbReader.Read())
{
Label1 = DbReader.GetString(0);
Label2 = DbReader.GetString(1);
Label3 = DbReader.GetString(2);
Label4 = DbReader.GetString(3);
for (int i = 0; i < fCount; i++)
{
String col = DbReader.GetString(i);
Console.Write(col + ":");
}
Console.WriteLine();
}
}
NB your SQL only return 1 field /String at the moment
while reading the data fill the list like
List<string> players = new List<string>();
OleDbDataReader rdr = command.ExecuteReader();
While(rdr.Read())
{
players.Add(rdr["PlayerName"].ToString());
}
You need to create a OleDbReader object to read the response from the query. You will also need to create a List to store the data Something like this:
List<string> playerNameList = new List<string>();
using (OleDbReader r = command.ExecuteReader())
{
while(reader.Read())
{
playerNameList.Add(reader.GetString(0));
}
}
One option might be using OleDbDataAdapter to fill a DataTable those values that returns your query;
var dt = new DataTable();
using(var da = new OleDbDataAdapter(command))
{
da.Fill(dt);
}
And since your query return one column, you can use AsEnumerable to that datatable to get them as a string like;
List<string> list = dt.AsEnumerable()
.Select(r => r.Field<string>("PlayerName"))
.ToList();
You can read: Queries in LINQ to DataSet
By the way, you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Also use using statement to dispose your connection and command automatically as I did for OleDbDataAdapter in my example.

Specifies that I have problems with my conn.open and my Conn.Close

this is how I select some content twice and when I get into the middle to select so like that it gives me trouble to select something on file.
The problem I have never seen before,
I think it's something with conn.open() and Conn.Close()
my code looks like this:
int prisId = Convert.ToInt32(Request.QueryString["Id"]);
cmd.Parameters.AddWithValue("#ppId", prisId);
cmd.CommandText = "SELECT priser FROM Priser WHERE Id = #ppId;";
conn.Open();
SqlDataReader readerPriser = cmd.ExecuteReader();
if (readerPriser.Read())
{
PanelerrorHandelsbetingelser.Visible = false;
string Brugerid = Session["id"].ToString();
cmd.Parameters.AddWithValue("#brugerid", Brugerid);
cmd.CommandText = "SELECT id, brugernavn, fornavn, efternavn FROM brugere WHERE Id = #brugerid;";
SqlDataReader readerBrugerid = cmd.ExecuteReader();
if (readerPriser.Read())
{
Session["id"] = readerBrugerid["id"].ToString();
Session["brugernavn"] = readerBrugerid["brugernavn"].ToString();
Session["fornavn"] = readerBrugerid["fornavn"].ToString();
Session["efternavn"] = readerBrugerid["efternavn"].ToString();
Session["adresse"] = TextBoxAdresse.Text;
Session["post"] = TextBoxPost.Text;
Session["telefon"] = TextBoxTelefon.Text;
Session["prisen"] = readerPriser["priser"].ToString();
LabelErrorBuyNow.Text = " - Yeaaa Jesper!";
}
else
{
LabelErrorBuyNow.Text = " - Der findes intet med dit brugerid!";
}
}
conn.Close();
problems come after line 9-10
The problem is such that it appears this one mistake on my part: There is already an open DataReader associated with this Command which must be closed first.
Always remember to release resources after they are used. So at the method end, you should:
cmd.Parameters.Clear();
readerPriser.Close();
conn.Close();
The exception tells you exactly what is wrong.
You have tried to run two SqlDataReaders over the same connection without either specifying MultipleActiveResultSets=True in your connection string or else first closing the first reader.
You have three options:
Use a second connection to run the second SqlDataReader.
Add "MultipleActiveResultSets=True" to your connection string.
Close the first SqlDataReader before using the second.
You need to close the readerPriser first be
readerPriser.Close();
Then affiliate the same command with next reader.
Always close the readers after using them.
There are two problems here. First of all, you are not placing all of your IDisposable objects into using blocks. Second, you are reusing the same SqlCommand for different queries. Third, your second Read call is using the wrong SqlDataReader.
Try
using (SqlConnection conn = new SqlConnection(...)){
conn.Open();
using (SqlCommand selectPriser = new SqlCommand("SELECT priser FROM Priser WHERE Id = #ppId;", conn))
{
selectPriser.Parameters.AddWithValue("#ppId", prisId);
using (SqlDataReader readerPriser = selectPriser.ExecuteReader())
{
if (readerPriser.Read())
{
// ...
using (SqlCommand selectBrugere = new SqlCommand("SELECT id, brugernavn, fornavn, efternavn FROM brugere WHERE Id = #brugerid;"){
string Brugerid = Session["id"].ToString();
selectBrugere.Parameters.AddWithValue("#brugerid", Brugerid);
using (SqlDataReader readerBrugerid = selectBrugere.ExecuteReader()){
if (readerBrugerid.Read()){
// ...
}
}
}
}
}
}
}

Return values from SQL Server to C# convert ToArray?

I am working on an assignment at the moment, trying to get values from a SQL Server database and storing them in an array. My connection is fine, but I am having trouble putting the returned values into an array.
Here is what I've got, have changed it a bit since I asked the question:
public int Bay;
int temp;
[DataContract]
public Garage()
{
List<Garage> Bays = new List<Garage>();
SqlConnection connection = new SqlConnection("Data Source=fastapps04.qut.edu.au;Initial Catalog=*******;User ID=******;Password=******");
connection.Open();
SqlCommand command = new SqlCommand("SELECT Bay FROM Garage", connection);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
temp = reader.GetOrdinal("Bay");
Bays.Add(temp);
}
Bays.ToArray();
reader.Close();
connection.Close();
}
Getting the error at
Bays.Add(temp)
Each call to reader.Read() will advance the reader to the next row of your result set. You seem to have assumed that you can get all rows into your array from a single read.
If you change your code so that you just add temp to your array on each iteration of the while loop you should find that it works.
I'd type the code, but I'm on my phone. :)
Change the Bays to a List<int>, and return either a list or call .ToArray() on the list. Also, use Using statements with connections and commands.
List<int> Bays = new List<int>();
using(SqlConnection connection = new SqlConnection("connString"))
{
connection.Open();
using (SqlCommand command = new SqlCommand("SELECT Bay FROM Garage",
connection))
{
using (SqlDataReader reader= command.ExecuteReader())
{
while (reader.Read())
{
Bays.Add(reader.GetInt32(reader.GetOrdinal("Bay")));
}
}
}
}
.....
Little modification need to be done in your code in order to get the desired result needed by you.
public Garage()
{
SqlConnection connection = new SqlConnection("Data Source=fastapps04.qut.edu.au;Initial Catalog=*******;User ID=******;Password=******");
connection.Open();
SqlCommand command = new SqlCommand("SELECT Bay FROM Garage", connection);
SqlDataReader reader = command.ExecuteReader();
List<Garage> listBays =new List<Garage>();
while (reader.Read())
{
temp = reader.GetInt32(reader.GetOrdinal("Bay"));
listBays.Add(temp);
}
Garage[] Bays=listBays.ToArray();
reader.Close();
connection.Close();
}

C# SQL multiple query results into diffrent textbox

So I'm having this :
Conn.Open();
SqlCommand Comm3 = new SqlCommand("SELECT answer" + " FROM answers" + " WHERE id_answer=5" , Conn);
SqlDataReader DR3 = Comm3.ExecuteReader();
And there is multiple results,how can I now move each of them in diffrent textbox (i already created textboxes? Till now i only managed to get same result into them.
this is normally how i do it....
SqlConnection cn = new SqlConnection("my connection string");
cn.Open();
string sql = "select * from table where column = whatever";
using (SqlCommand cmd = new SqlCommand(sql,cn))
{
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
myTextBox1.Text = (string)dr["Column1"];
myTextBox2.Text = (string)dr["Column2"];
myTextBox3.Text = (string)dr["Column3"];
}
dr.Close();
}
cn.Close();
just make sure you are aiming the right column name while looping through them, and cast correctly.
You need to loop through each of the item in the Database table. Think of a foreach loop, where you simply just go through each item and work on it similarly.
Here is a sample for that,
// Create new SqlDataReader object and read data from the command.
using (SqlDataReader reader = command.ExecuteReader())
{
// while there is another record present
while (reader.Read())
{
// write the data on to the screen
textBox.Text = reader[0];
}
}
This will add the value of reader's first column (answer) to the textBox. Now make sure you're calling correct textBox to add the value to.
http://www.codeproject.com/Articles/823854/How-to-connect-SQL-Database-to-your-Csharp-program Do give this article a read.

Limit your use of DataTable

I recently saw this, see below. I got OutofMemoryException when loading 2.5 million records with DataTable. And near the bottom, there is a table.Dispose(). Memory usage: 560Mb! Why use DataTable anyway?
public string[] GetIDs()
{
DataTable table = new DataTable();
using (SqlConnection dwConn = new SqlConnection(this.ConnectionString))
{
dwConn.Open();
SqlCommand cmd = dwConn.CreateCommand();
cmd.CommandText = "SELECT ID FROM Customer";
SqlDataReader reader = cmd.ExecuteReader();
table.Load(reader);
}
var result = new string[table.Rows.Count];
for(int i = 0; i < result.Length; i++ )
{
result[i] = table.Rows[i].ItemArray[0].ToString();
}
table.Dispose();
table = null;
return result;
}
I turned this in the following, and the memory used was now 250Mb for 2.5 million records, same as above. The memory used is now less than 45% of the original.
public IEnumerable<String> GetIDs()
{
var result = new List<string>();
using (var dwConn = new SqlConnection(ConnectionString))
{
dwConn.Open();
SqlCommand cmd = dwConn.CreateCommand();
cmd.CommandText = "SELECT ID FROM Customer";
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
result.Add(reader["ID"].ToString());
}
}
}
return result;
}
Its good to see that you have a problem to your solution, but i would also recommend to have a look at this discussion which depicts that DataReader is a better solution than DataTable, but it depends on it use as well. After reading this you will understand memory consumption is expected to be less in case of DataReader.
Another advantage using SqlDataReader is documented in MSDN documentation is:
A part from Remarks:
Changes made to a result set by another process or thread while data
is being read may be visible to the user of the SqlDataReader.
So it is a possible reason that you are getting this difference in observation.
Hope it is useful for you and others as well.

Categories