C# SQL multiple query results into diffrent textbox - c#

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.

Related

How to use C# connect to mysql and get json data?

As mentioned above:
I'm using C# to connect to a MySQL database and I want to read JSON data type.
I use the method MySqlCommand.ExecuteReader:
using (MySqlConnection sconn = new MySqlConnection(sqlConnectString))
{
sconn.Open();
String sql_Command = #"SELECT `id` FROM orders.jsontest;";
using (MySqlCommand scmd = new MySqlCommand(sql_Command, sconn))
{
**MySqlDataReader sdr = scmd.ExecuteReader();** // fatal error
DataTable datatable = new DataTable();
// ...
}
}
Can it be that I cannot use ExecuteReader here?
I know this question is old, but just in case you do not yet have a solution to your problem or anyone else encounters a similar problem, the following code should work for you:
private IEnumerable<int> GetIds()
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open();
string commandText = #"SELECT id FROM jsontest"; // Assuming that `orders` is your database, then you do not need to specify it here.
using (MySqlCommand command = new MySqlCommand(commandText, connection))
{
MySqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
yield return reader.GetInt32(0);
}
}
}
}
Now what you should pay attention to is this line
while (reader.Read())
which fetches results from the jsontest table as long as the MySqlDataReader can still read valid results and this line
yield return reader.GetInt32(0);
which instructs the reader to get and return each record of the fetched table one at a time as an Int32 (int). You need to change this if your tables column type is not INT.
Since you selected just one column (i.e. "SELECT id"), the parameter is 0, because your fetched resul table consists of one column only.
Additionally, in your code you seem to want to get the results as a DataTable; if so, you should use MySqlDataAdapter instead of the MySqlDataReader as follows:
DataTable resultTable = new DataTable("ResultTable");
MySqlDataAdapter adapter = new MySqlDataAdapter(command);
adapter.Fill(table);
Correct your sql command
String sql_Command = #"SELECT id FROM orders.jsontest";

Put content of access database into two listboxs

Hi I have a database with two tables: 1.) Country (Table name: 2.) Website
Every country has 1 or more websites.
I am trying to make a C# WindowsForm Application where I want the User first to select a country from the first listbox1 and then all the Websites will in the second listbox2 based on the database.. I somehow can't display all the countries in the first textbox using a select statement: the code is the following
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "SELECT CountryName FROM Countries ";
//whenever you want to get some data from the database
using (OleDbDataReader reader = command.ExecuteReader())
{
listBox.Items.Add(reader);
}
//OleDbDataReader reader = command.ExecuteReader();
connection.Close();
}
catch(Exception l)
{
MessageBox.Show("Error:" + l);
}
This code doesn't show the items in the listbox.
Can someone please advise ?
You probably want to get your data from the reader and convert it to an object before you put it in the listbox. You can get the value for each column by reader["columnname"]. Dont forget that you also need to convert each value to its proper type, you will probably find all types of conversion you need in System.Convert.
With your scenario in mind you should be able to do
using (OleDbDataReader reader = command.ExecuteReader())
{
while(reader.Read())
{
listBox.Items.Add(reader["CountryName"].ToString());
}
}
You are trying to add the OleDbDataReader as a listbox item instead of using it to read the data, here is an example of how to use it :
try
{
connection.Open();
using (OleDbCommand command = new OleDbCommand())
{
command.Connection = connection;
command.CommandText = "SELECT CountryName FROM Countries ";
//whenever you want to get some data from the database
using (OleDbDataReader reader = command.ExecuteReader())
{
while (reader.NextResult())
{
listBox.Items.Add(reader.GetString(0));
}
}
}
}
catch (Exception l)
{
MessageBox.Show("Error:" + l);
}
finally
{
connection.Close();
}

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()){
// ...
}
}
}
}
}
}
}

unreachable code detected on for loop

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

Get SQL data And show it in a text box?

In the last few days I am trying to get data from my SQL table and get it into my textbox.
The table name : "check".
The code I am using :
SqlDataReader myReader = null;
connection = new SqlConnection(System.Configuration.ConfigurationManager
.ConnectionStrings["ConnectionString"].ConnectionString);
connection.Open();
var command = new SqlCommand("SELECT * FROM [check]", connection);
myReader = command.ExecuteReader();
while (myReader.Read())
{
TextBox1.Text = myReader.ToString();
}
connection.Close();
I am getting nothing as a result. Anyone know why? Maybe I am not calling the SQL correctly?
using (var connection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
using (var command = connection.CreateCommand())
{
command.CommandText = "SELECT ColumnName FROM [check]";
connection.Open();
using (var reader = command.ExecuteReader())
{
while (reader.Read())
TextBox1.Text = reader["ColumnName"].ToString();
}
}
Some comments:
don't use *, specify only those fields that you need
use using - less code, guaranteed disposal
I assume this is a test program, otherwise it does not make sense to reset Text to a in the loop
TextBox1.Text = myReader["fieldname"].ToString();
also I think you can change while with if because for every row from your table you'll overwrite textbox text!
Try this:
TextBox1.AppendText(myReader["columnname"].ToString());

Categories