Reputation: 389
I want to retrieve some specific data from tblBranches
based to the choice of the user in the combobox (cboBranch.Text), one is the class_name
but when I tried to run the program the messagebox shows MySql.Data.MySqlClient.MySqlDataReader
, so how can I properly retrieve the data in my database?
query = "SELECT class_name FROM tblBranches WHERE branch_name=@branch";
MySqlCommand cmd = new MySqlCommand(query, con);
cmd.Parameters.Add("@branch", MySqlDbType.VarChar, 30).Value = _order.cboBranch.Text;
MySqlDataReader dr;
con.Open();
dr = cmd.ExecuteReader();
string class_name = dr.ToString();
MessageBox.Show(class_name);
con.Close();
Upvotes: 0
Views: 4831
Reputation: 37
Just an addition: isn't is easier to use ExecuteScalar in case there's only 1 row to expect as a result?
Example:
MySqlCommand cmd = new MySqlCommand(query, con);
cmd.Parameters.Add("@branch", MySqlDbType.VarChar, 30).Value = _order.cboBranch.Text;
var class_name = cmd.ExecuteScalar();
if (class_name != null)
{
//DoSomething with your result here.
}else{
//Item not found, handle it here
}
Upvotes: 0
Reputation: 9577
Rather than call the ToString()
method, you need to to call the GetString()
method passing the zero-based index of the ordinal position of the column in your query, zero in this case because there is only one column in your query.
Before that, you must call the Read()
method to advance the reader onto the first or next record and you also need to check the return value because it will return a bool
to indicate if another record was found.
So replace this line...
string class_name = dr.ToString();
With
string class_name = dr.Read() ? dr.GetString(0) : "Nothing Found";
Or if there could be more than one record returned...
string class_names = string.Empty;
while (dr.Read())
class_names = dr.GetString(0) + "\n";
Upvotes: 1