Reputation: 2823
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();
}
Upvotes: 0
Views: 5307
Reputation: 10026
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.
Upvotes: 2
Reputation: 303
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.
Upvotes: 2