enter image description hereI'm trying to show all my items on a combobox, but when y run my app I only get one item. Can you help me please, here's my code
try
{
MySqlConnection conection = new MySqlConnection("server = 127.0.0.1; database = sistemalaboratorio; Uid = root; pwd =;");
string selectQuery = "SELECT clavemateria FROM materia";
conection.Open();
MySqlCommand command = new MySqlCommand(selectQuery, conection);
MySqlDataReader reader = command.ExecuteReader();
while (reader.Read());
{
comboBox1.Items.Add(reader["clavemateria"].ToString());
}
} catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Assuming this read is happening before the page loads the combobox, make sure your materia table has more than 1 record in it.
These queries might usful to count the records in your SQL table in case you dont have direct access using SQL Management studio
SELECT COUNT(*) FROM materia WITH (NOLOCK)
-- NOLOCK here is for testing for this answer: no more, no less
or
SELECT clavemateria, count(*)
FROM materia
GROUP BY clavemateria
Also you can try this:
string qr1 = "select * from materia ";
SqlCommand cmd1 = new SqlCommand(qr1, con);
con.Open();
SqlDataReader dr1 = cmd1.ExecuteReader();
cmbcat.Items.Clear();
while (dr1.Read())
{
cmbcat.Items.Add(new Item(dr1["clavemateria"].ToString(), dr1["clavemateria"].ToString()));
}
con.Close();
Or refer to this example
Related
I am working on a database C# project. I am using the a SQL Server database with a few tables I created. I am working on trying to get it so that I can hard code a function to sort the database by name alphabetically and still keep the ids to increment by 1's. At the moment the first is correct, but the rest are still the same name.
SqlConnection cn = new SqlConnection(global::Cookbook_Project.Properties.Settings.Default.RecipesDatabaseConnectionString);
try
{
cn.Open();
var command = new SqlCommand("Select * from SoupTable", cn);
command.ExecuteNonQuery();
command.CommandText = "Select soups from SoupTable Order By soups ASC";
btnSoup1.Text = command.ExecuteScalar().ToString();
command.CommandText = "Select soups from SoupTable Order By soups ASC";
btnSoup2.Text = command.ExecuteScalar().ToString();
command.CommandText = "Select soups from SoupTable Order By soups ASC";
btnSoup3.Text = command.ExecuteScalar().ToString();
command.CommandText = "Select soups from SoupTable Order By soups ASC";
btnSoup4.Text = command.ExecuteScalar().ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error");
}
finally
{
cn.Close();
}
This is the code for connecting to the database and attempting to sort.
This is the data view of the table in the database with ids also sorted (I used the sort function here, not what I want)
Screenshot #1
Design view of the table:
Screenshot #2
You need to execute your SQL once using a DataReader, like this:
List<string> SoupList = new List<string();
using (SqlCommand command = new SqlCommand("Select soups from SoupTable Order By soups ASC", cn))
{
using (SqlDataReader myReader = command.ExecuteReader())
{
while (myReader.Read())
{
SoupList.Add(Convert.ToString(myReader["soups"].ToString()));
}
}
}
Now SoupList contains all your records.
Edit: Updated to use Convert.ToString() as suggested in the comments.
With one SELECT query, the code seems to add to the listbox correctly, but when I add another query, the listbox doesn't show anything anymore, and it seems that that rdr[3] does not exists (Contact has 3 columns and Numar_contact has one column (should't it be this one the rdr[3]?))
string connString = #"database=Agenda_db; Data Source=Marian-PC\SQLEXPRESS; Persist Security Info=false; Integrated Security=SSPI";
SqlConnection conn = new SqlConnection(connString);
try {
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM Contact;"+ "SELECT * FROM Numar_contact", conn)
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
listBox1.Items.Add(rdr[0].ToString() + ' ' + rdr[1].ToString() + ' ' + rdr[2].ToString()+' '+ rdr[3].ToString());
}
rdr.Close();
Join your queries with a UNION. The way you've got it now, it'll return two results sets.
SELECT [col1], [col2] FROM Contact
UNION ALL
SELECT [col1], [col2] FROM Numar_contact
As DJ KRAZE pointed out in a comment, it might not be a bad idea to wrap this in a sproc or a TVF. But this will work too.
Edit:
I just learned via comments that the two tables are actually unrelated. In light of that, I'd be tempted to use two SqlCommands with two, distinct foreach loops. But if you're sold on this way,
SELECT id_contact, nume_contact, prenume_contact FROM Contact
UNION ALL
SELECT id_contact, numar, NULL FROM Numar_contact
This will align the data from the two tables, but where the second table doesn't have a [prenume_contact] it will select NULL. I might have mixed up the column positions here, since I don't really understand what those names are meant to represent.
Edit 2:
string connString = #"database=Agenda_db; Data Source=Marian-PC\SQLEXPRESS; Persist Security Info=false; Integrated Security=SSPI";
using (SqlConnection conn = new SqlConnection(connString))
{
try
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Contact", conn))
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
listBox1.Items.Add(rdr[0].ToString() + " " + rdr[1].ToString() + " " + rdr[2].ToString());
}
}
using (SqlCommand cmd2 = new SqlCommand("SELECT * FROM Numar_contact", conn))
using (SqlDataReader rdr2 = cmd.ExecuteReader())
{
while (rdr2.Read())
{
listBox1.Items.Add(rdr2[0].ToString() + " " + rdr2[1].ToString());
}
}
}
catch { }
}
Edit 3, thanks to insight from Scott Chamberlain:
On the other hand, you might want to perform a JOIN of some kind, most commonly an INNER JOIN. Note that this is an entirely different operation from any we've talked about before.
SELECT Contact.id_contact, Contact.nume_contact, Contact.prenume_contact, Numar_contact.numar
FROM Contact
INNER JOIN Numar_contact on Contact.id_contact = Numar_contact.id_contact
This will tie the two tables together, returning a record for each contact-numar_contact. Again, this is definitely not the same as doing a UNION. Make sure you're aware of the difference before you pick which you want.
Use this if your second table contains data that relates many-to-one to the first table.
Thanks to your comment, what you are wanting to do is JOIN the tables.
SELECT Contact.id_contact, nume_contact, prenume_contact, numar
FROM Contact
INNER JOIN Numar_contact on Contact.id_contact = Numar_contact.id_contact
That will combine the two tables in to four columns where id_contact matches in both tables.
You may want a INNER JOIN or a LEFT JOIN depending on if you want rows to show up only when there is a item in the 2nd table or show up anyway and just make the 4th column DBNull.Value.
Yes you can.
Here is an example from the MSDN I've modified to use your code - you need to move the reader to the Next ResultSet
string connString = #"database=Agenda_db; Data Source=Marian-PC\SQLEXPRESS; Persist Security Info=false; Integrated Security=SSPI";
SqlConnection conn = new SqlConnection(connString);
SqlCommand myCommand = new SqlCommand("SELECT * FROM Contact; SELECT * FROM Numar_contact", conn);
SqlDataReader myReader ;
int RecordCount=0;
try
{
myConnection.Open();
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
//Write logic to process data for the first result.
RecordCount = RecordCount + 1;
}
MessageBox.Show("Total number of Contacts: " + RecordCount.ToString());
bool moreResults = myReader.NextResult(); // <<<<<<<<<<< MOVE TO NEXT RESULTSET
RecordCount = 0;
while (moreResults && myReader.Read())
{
//Write logic to process data for the second result.
RecordCount = RecordCount + 1;
}
MessageBox.Show("Total number from Numar_contacts: " + RecordCount.ToString());
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
conn.Close(); // Could be replaced with using statement too
}
I can`t to return value from second query.
Part of code...
MySqlConnectionStringBuilder mysqlSB = new MySqlConnectionStringBuilder();
mysqlSB.Server = "localhost";
mysqlSB.Database = "test";
mysqlSB.UserID = "admin";
mysqlSB.Password = "1111";
MySqlConnection con = new MySqlConnection();
con.ConnectionString = mysqlSB.ConnectionString;
MySqlCommand Select = new MySqlCommand("select name from table_1 where id='1' ", con);
MySqlDataReader myReader;
con.Open();
myReader = Select.ExecuteReader();
while (myReader.Read())
{
count++;
}
string name = myReader["name"].ToString();
if (count == 1)
{
MySqlCommand Select2 = new MySqlCommand("select country from table_2 where name='"+name+"'", con);
MySqlDataReader myReader2;
myReader2 = Select2.ExecuteReader();
while (myReader2.Read())
{
count++;
}
return myReader2["id"].ToString();
}
If I delete second part, after if(count==1) and return name = all ok, but when I return id will error. Plase Tell why, because I need to return second, third... values of query.
Thank you!
If I were you I'd fill a datatable with the results of your query
See here
Connecting to a Mysql DB with C# - Need some with Datasets
I don't know what you want to do with the countries you select out but if its in a datatable you can then bind it to a dropdown or something
In your second you are returning id field and are only selecting the country field from the database. It isn't returning an id field for you to read from thus an error.
Database Name is ONLINEEXAM
I have several tables in the db and I want to list some table names starts with letters "set % " in Dropdownlist in asp.net.
I use the following code and I'm getting the error : invalid object name ONLINEEXAM.dbo.sysobjects
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
paperset();
}
}
private void paperset()
{
try
{
string conn = ConfigurationManager.ConnectionStrings["sqlconn"].ConnectionString;
SqlConnection con = new SqlConnection(conn);
con.Open();
SqlCommand cmd = new SqlCommand(
"select * from ONLINEEXAM.dbo.sysobjects where name like 'Set%'", con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
ListItem item = new ListItem();
item.Value = dr[0].ToString();
papersetlist.Items.Add(item);
}
dr.Close();
con.Close();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
finally { }
}
May be you are running query against a different database, run you query in sql server to check it.
also try this
SqlCommand cmd = new SqlCommand("select * from sys.objects where name like 'Set%'", con);
or use this to get all the tables
select * from sys.tables where name like 'Set%'
Take a look to verify the user ID has access to the sysobjects table.
Assuming you are running SQL2005 or later, you can also look at the INFORMATION_SCHEMA schema and review the TABLES view:
Select TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, TABLE_TYPE
from [database.]INFORMATION_SCHEMA.TABLES
i m trying to retrieve the Specialization ID from a table called Specializationtbl, using C# MSVS 2008 and the table includes SpecializationName and SpecializationID beside some other rows and my question is related to some error " No Data to present ", the command goes as bellow:
SqlCommand READSpecID = new SqlCommand("SELECT * FROM Specializationtbl WHERE SpecializationName='" + comboBox1.Text + "'" , DBcnction);
DBcnction.Open();
SqlDataReader ReadSpecID_ = READSpecID.ExecuteReader();
ReadSpecID_.Read();
int SpecID_ = Convert.ToInt16(ReadSpecID_["SpecID"].ToString());
DBcnction.Close();
i also tried to Select the "SpecID" instead of all the rows, but cant seem to seal the query correctly and keep receiving "No data present " error, any idea where am i making the mistake?
1) Try opening DBcnction before assigning the value to READSPecID
DBcnction.Open();
SqlCommand READSpecID = new SqlCommand("SELECT * FROM Specializationtbl WHERE SpecializationName='" + comboBox1.Text + "'" , DBcnction);
2) Run the command in SSMS:
SELECT * FROM Specializationtbl WHERE SpecializationName ='yourvalue'
and see if any results are returned
3) Check comboBox1.Text has a value in it
4) Validate the contents of comboBox1.Text (Or use paremetrised queries or a stored procedure) to ensure you do not become a victim of SQL Injection: http://en.wikipedia.org/wiki/SQL_injection
Refactor to solve your TWO problems:
Your SQL injection problem when building your SQL statement.
Use ExecuteScalar if you only need one value.
Implement using blocks.
string retVal;
using (var conn = new SqlConnection(SomeConnectionString))
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = "SELECT SpecID FROM Specializationtbl WHERE SpecializationName= #Name";
cmd.Parameters.AddWithValue("#Name", comboBox1.Text);
conn.Open();
retVal = cmd.ExecuteScalar().ToString();
}
int specID = int.Parse(retVal);
If you really needed more than one value from your statement:
using (var conn = new SqlConnection(SomeConnectionString))
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = "SELECT SpecID, Value2 FROM Specializationtbl WHERE SpecializationName= #Name";
cmd.Parameters.AddWithValue("#Name", comboBox1.Text);
conn.Open();
var dr = cmd.ExecuteReader();
while (dr.Read())
{
Customer c = new Customer {
ID = dr["SpecID"].ToString(),
Value = dr["Value2"].ToString(),
};
}
}
Need to first test if there are any rows. I suspect the query is returning zero rows.
if (ReadSpecID_.HasRows)
{
ReadSpecID_.Read();
}