I am trying to get a drop down list to display data from MYSQL database, database table name is Pet and I am trying to get the information from Specie.
Now the code looks good to me but it is not running so its always best to get another pair of eyes to look over it.
Thanks,
All help is appreciated.
connection string
MySqlConnection cs = new MySqlConnection(#"Data Source = 000.000.00.000;username=benoatsc_admin;password=****; Initial Catalog = dbname; Integrated Security = true");
drop down code
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
MySqlCommand cd = new MySqlCommand("SELECT * FROM Pet", cs);
cs.Open();
MySqlDataReader ddl = cd.ExecuteReader();
DdPetList.DataSource = ddl;
DdPetList.DataValueField = "Specie";
DdPetList.DataTextField = "Specie";
DdPetList.DataBind();
cs.Close();
cs.Dispose();
}
There are a few problems here:
You should likely move this code to the Page_Load method. I would assume that you want this DropDownList populated when the page loads for the user. Otherwise, the DropDownList is never populated with the data from your MySQL Database, hence you will not be able to trigger the SelectedIndexChanged event when there is no index to possibly change.
MySQL Connector/Net makes use of unmanaged resources. These should be disposed of when they are finished being used. The .NET Framework offers an elegant way to ensure that objects utilizing unmanaged resources are disposed of in the form of using statements. It is best practice to use them.
When MySqlConnection, MySqlDataReader, etc. should not only be disposed of when they are done being used, but they should also be closed. Thankfully, when dispose() is called on these objects their close() methods are called as well.
So piecing this all together yields this piece of code:
protected void Page_Load(object sender, EventArgs e)
{
using (var conn = new MySqlConnection(/* Your connection string here */))
{
conn.Open();
using (var cmd = new MySqlCommand("SELECT * FROM Pet", conn))
{
using (var reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
DropDownList1.DataSource = reader;
DropDownList1.DataValueField = "Specie";
DropDownList1.DataTextField = "Specie";
DropDownList1.DataBind();
}
}
}
}
}
I hope this all helps. If you need any clarifications, I will gladly provide it.
This would be a comment but i don't have the reputation,
what error message are you receiving ?
your connection string has got both trusted connection set to true and you are providing credentials,
remove one of them.
Related
I have below code to update my database table when button is clicked but it doesn't work.
protected void Button_Click(object sender, EventArgs e)
{
HasinReservation.Entities.Db.Transaction dt = new Transaction();
SqlConnection connection = new SqlConnection(
#"Data Source=192.x.x.x\Sql2008;Initial Catalog=GardeshgariKish;User ID=cms;Password=xxxxx;MultipleActiveResultSets=True;Application Name=EntityFramework");
connection.Open();
SqlCommand sqlCmd = new SqlCommand(
"Update Transaction SET IsCancelled = 1 WHERE BarCodeNumber = #Value1", connection);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
string barcode = dgvData.Rows[0].Cells[12].Text;
sqlCmd.Parameters.AddWithValue("Value1", barcode);
connection.Close();
}
I am troubled by your implementation of Entity Framework but then not using the framework for what it was designed...
You have configured your data adapter and the command, and even opened the connection... but you have not actually executed the command.
sqlCmd.ExecuteNonQuery();
I understand that your actual business logic may have been replaced with this simple CRUD operation, but the main reason that we use the Entity Framework is to avoid writing any T-SQL in our business logic. Why didn't you use the framework to commit the change:
protected void Button3_Click(object sender, EventArgs e)
{
// cancel the selected transaction
string selectedBarcode = dgvData.Rows[0].Cells[12].Text;
using(var dataContext = new HasinReservation.Entities.Db())
{
var transaction = dataContext.Transaction.Single(t => t.Barcode == selectedBarcode);
transaction.IsCancelled = true;
dataContext.SaveChanges();
}
}
This in itself may not be a great solution but it uses the framework to do exactly what you attempted to do manually.
Why are you trying to use a SqlDataAdapter to execute an UPDATE statement? When constructing a SqlDataAdapter with a SqlCommand object, that command object represents the SELECT command for the adapter. An UPDATE statement doesn't select anything, and a SELECT command doesn't update anything.
Get rid of the SqlDataAdapter entirely and just execute the command:
sqlCmd.ExecuteNonQuery();
You'll probably also want to add some error handling so exceptions don't reach the UI (and to ensure the connection is properly closed on error conditions). You also don't seem to be doing anything with that Transaction object, so you can probably get rid of that too.
I've ordered SQL Server from Somee. I want to use this SQL Server for my windows form. Somehow, i'm not sure, but whenever i execute the login query what i've found, it will have an unhandled exeption.
private void log_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "workstation id=wbhandler.mssql.somee.com;packet size=4096;user id=acc;pwd=pw;data source=wbhandler.mssql.somee.com;persist security info=False;initial catalog=wbhandler";
con.Open();
string felh = username.Text;
string jelsz = password.Text;
string query = "SELECT * FROM accounts WHERE account=#felhasznalo AND password=#jelszó";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.Add(new SqlParameter("#felhasznalo", felh));
cmd.Parameters.Add(new SqlParameter("#jelszó", jelsz));
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows == true )
{
MessageBox.Show("Succes");
}
else
{
MessageBox.Show("Failed");
}
}
I thought that the adress is wrong, but then i found on the website the connection string, and now i don't really know.
I'm thinking what's the problem is.
I have 3 schemes in the sql:
dbo, acc, guest.
I first created a table in dbo, then in acc. Now in both of it. But it doesn't execute the SqlDataReader dr = cmd.ExecuteReader();, sadly. Like i said, it has unhandled exeption. Any solution? Any ideas?
(the acc scheme is an example what i created in somee, so it doesn't exist, it's fake)
I also tried this way:
using (var dr = cmd.ExecuteReader())
{
if (dr.HasRows)
{
MessageBox.Show("Sikeres Login!");
}
else
{
MessageBox.Show("Sikertelen Login");
}
}
The problem is always the ExecuteReader()
Try the SqlParameterCollection.AddWithValue Method instead:
cmd.Parameters.AddWithValue("#felhasznalo", felh);
cmd.Parameters.AddWithValue("#jelszó", jelsz);
I will also recommend that you use using statements on your SQL objects to ensure that the unmanaged resources they consume are freed when they are no longer needed. You can read more on the using statement from here.
Another thing that I can suggest is adding Charset=utf8; to your connection string.
I'm a bit confused of how to get a data from an access database. Is it proper to gather it first in a List then get those data from your List OR it is okay to just directly get it in you database ?
My codes work perfectly fine, but I wanna know if there is a better way to do this?? :
private void button3_Click(object sender, EventArgs e)
{
OleDbConnection connection = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\redgabanan\Desktop\Gabanan_Red_dbaseCon\Red_Database.accdb");
connection.Open();
OleDbDataReader reader = null;
OleDbCommand command = new OleDbCommand("SELECT * from Users WHERE LastName='"+textBox8.Text+"'", connection);
reader = command.ExecuteReader();
listBox1.Items.Clear();
while (reader.Read())
{
listBox1.Items.Add(reader[1].ToString()+","+reader[2].ToString());
}
connection.Close();
*I'm getting my records directly from a database then display it in a listbox.
One thing that is sticking out like a sore thumb is the SQLInjection and to use Parameterised queries, eg:
OleDbCommand command = new OleDbCommand("SELECT * from Users WHERE LastName='#1'", connection);
command.Parameters.AddWithValue("#1", textBox8.Text)
What your doing is perfectly acceptable, although you would generally be better off to use a SQL Database.
Edit:
Here is how you seperate your business logic from the GUI:
Class BusLogic
{
public List<string> ListboxItems = new List<string>();
public void PopulateListBoxItems(string userName)
{
string connString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\redgabanan\Desktop\Gabanan_Red_dbaseCon\Red_Database.accdb";
using (OleDbConnection connection = new OleDbConnection(connString))
{
connection.Open();
OleDbDataReader reader = null;
OleDbCommand command = new OleDbCommand("SELECT * from Users WHERE LastName='#1'", connection);
command.Parameters.AddWithValue("#1", userName)
reader = command.ExecuteReader();
while (reader.Read())
{
ListboxItems.Add(reader[1].ToString()+","+reader[2].ToString());
}
}
}
}
GUI
private void button3_Click(object sender, EventArgs e)
{
var busLogic = new BusLogic();
busLogic.PopulateListBoxItems(textBox8.Text);
\\listBox1.Items.Clear();
ListboxItems.DataSource = busLogic.ListboxItems;
}
The beauty of this "MVC" approach is that we only really need to test the BusLogic if we rely on controls being bound using Binding.
ps Ideally ListboxItems would be an IEnumerable instead of List so that we don't expose any functionality to Add/Remove etc from the caller. This is good API design.
I would say the answer is "yes" to both.
What you're doing now is perfectly acceptable for simple cases. Just be aware that it doesn't "scale" very well. That is, loading 10 or 20 items is fine. But what happens if it becomes 10 thousand or a million?
In that case you want to look at using a Model-View-Controller (MVC) architecture. That's a topic in itself, but basically you decouple the listbox (the "view") from the data (the "model").
See this site for a C#-centric MVC discussion
In between what you're doing now and a full-blown MVC architecture, you may simply want to do as you suggest - load the list first then add them to the list box. That gains you nothing if you just load it once, but if the list is loaded "all over the place", you can save the database IO overhead each time by just accessing it once.
The fact that you thought to ask the question indicates you're on the right track.
Although your code works without any problem, I suggest you to perform some exception handling as in this example, since both OleDbConnection.Open() and OleDbCommand.ExecuteReader() might throw an InvalidOperationException.
It is also common to wrap the connection with a using statement, so in the end connection.close() is called automatically, but this is just a personal preference.
You can maybe separate your data access functions in different classes or create generic functions to retrieve records.
I am developing a front-end sales application.
Is this an efficient way of inserting data multiple times into a sql table, from a single button:
private void button1_Click(object sender, EventArgs e)
{
c.Open();
string w = "insert into checkmultiuser(username) values (#username)";
SqlCommand cmd = new SqlCommand(w, c);
cmd.Parameters.Add("#username", SqlDbType.VarChar);
cmd.Parameters["#username"].Value = textBox1.Text;
//cmd.ExecuteNonQuery();
cmd.ExecuteReader();
c.Close();
}
What are its drawbacks? One would be that again and again the connection is opened and closed when the button is clicked which would effect the speed greatly.
You ar edoing the right way: see this question: to close connection to database after i use or not? too.
Perhaps don't do the database insert for each entry, but store each entry in a DataSet, then insert them all at once, a la a save button.
For each entry do this:
String s = textBox1.Text;
If ( *\Enter validation logic*\ )
{
//Insert data into DataSet
}
else
{
//Throw error for user.
}
Then once you're ready to commit to DB, insert each item from the DataSet, similar to the examples in the other answers here.
I would open the connection once when the form opens and re-use that connection until the form is closed.
As for inserting records, the code you have is right.
From a resource management point of view it would be better if you can work out how many times you need to insert the data and then perform the operation in the one button click, perhaps iterating through a loop until the correct amount of insert operations has been completed. This means you are not constantly opening and closing the connection with each button press but instead opening it, performing the insert queries and closing the connection.
Also I recommend that you implement your code with the "using" statement, this way it will automatically handle the disposal and release of resources.
private void button1_Click(object sender, EventArgs e, string[] value)
{
try
{
using(SQLConnection c = new SQLConnection(connectionString))
using(SQLCommand cmd = new SQLCommand(c))
{
c.Open();
string w = "insert into checkmultiuser(username) values (#username)";
cmd.CommandText = w;
cmd.Parameters.Add("#username", SqlDbType.VarChar);
for(int i = 0; i < value.Length; i++)
{
cmd.Parameters["#username"].Value = value[i];
cmd.ExecuteReader();
}
}
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
}
If you can create the SQLConnection in the method then it will also allow you create it in a using statement, again taking care of managing and releasing resources.
In terms of the statement you are using I can't see any problems with it, you're using parameterized queries which is a good step to take when interacting with SQL databases.
References:
try-catch - MSDN
I don't think you should have to worry about the time lag due to opening and closing a connection, particularly if it is happening on a manually triggered button click event. Human perceivable response time is about 200 milliseconds. At best, I'd guess someone could click that button once every 100 milliseconds or so. Plenty of time to open and close a connection.
If, however, you are dealing with a routine that will be connecting to your database, you could pass in the connection, include a using statement as Mr. Keeling mentioned already, and just verify that it is ready.
Here is yet another approach, which returns a DataTable (since your original post displayed executing a Data Reader):
public static DataTable UpdateRoutine(SQLConnection c, string value) {
const string w = "insert into checkmultiuser(username) values (#username)";
DataTable table = new DataTable();
using(SQLCommand cmd = new SQLCommand(w, c)) {
cmd.Parameters.Add("#username", SqlDbType.VarChar);
cmd.Parameters["#username"].Value = value;
try {
if ((cmd.Connection.State & ConnectionState.Open) != ConnectionState.Open) {
cmd.Connection.Open();
}
using (SqlDataReader r = cmd.ExecuteReader()) {
table.Load(r);
}
}
return table;
} catch(SqlException err) { // I try to avoid catching a general exception.
MessageBox.Show(err.Message, "SQL Error");
}
return null;
}
i am working on C# .net platform
i wanted to connect my combox to my text box
this is code done by me but it is give me error
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
panel1.Visible = true;
string sql;
SqlConnection cn = new SqlConnection();
cn.ConnectionString = "Data Source=CJ\SQLEXPRESS;Initial Catalog=elligiblity;Persist Security Info=True;User ID=sa;Password=123";
cn.Open();
sql = "SELECT inst_name FROM institude WHERE(inst_id="+comboBox2.SelectedItem+")";
SqlCommand cmd = new SqlCommand(sql,cn);
SqlDataReader myReader = cmd.ExecuteReader();
while(myReader.Read())
{
textBox2.Text = myReader["inst_name"].ToString();
}
myReader.Close();
cn.Close();
The multi-part identifier "System.Data.DataRowView" could not be bound.
on this line of the code
SqlDataReader myReader = cmd.ExecuteReader();
As well as that problem there are a few issues with your code that you might want to bear in mind.
Firstly, if there is an error between opening and closing the connection (as indeed there was) then you're probably going to leave connections open. Eventually this will choke your site. Use
using (SqlConnection cn = new SqlConnection())
{
}
when you're out of the scope of the using statement the connection will be closed and disposed of.
Also, you probably want to parameterize your query (for reasons both of security and efficiency), so that it is
sql = "SELECT inst_name FROM institude WHERE(inst_id=#inst_id)";
Then add that parameter to your command object and set its value to your combo box selected item value.
You want
comboBox2.SelectedValue
or
comboxBox2.SelectedItem.ToString()
then but I'd look at using parameters instead as that's not a very good way of creating a SQL string.
Also, do you realise that if you return more than one result your textbox2 will only show the last result as its text will get over-ridden with each result as its read?
First of all check the binding of dropdown. If you are binding datasource with ID and Text something like this combobox2.DisplayMember ="Name"; combobox2.ValueMember ="ID". After that you have to check for the parameter to be used in your query if its text then try combobox2.text else if you are selecting on the basis of id use int.parse(combobox2.selectedvalue) or simply combobox2.selectedvalue if your id is alphanumeric.