Hi
I just set up my IP Board.

Now i want to retrieve some of the data via mysql, so far I have no problem getting a table into a datagridview, but what do i do to get a value from a table

right now i got SELECT * FROM members WHERE name = \"jazerix\"
how do i get the value it should return? :)

cheers
Jazerix

DO:

SqlConnection sqlConn = new SqlConnection("connString");
SqlDataAdapter da = new SqlDataAdapter(@"SELECT * FROM members WHERE name = @param1", sqlConn);
DataTable table = new DataTable();
da.Fill(table);
da.Dispose();
sqlConn.Dispose();
datagridview1.DataSource = DataTable.DefaultView;

thats it.
You will have your data in DataGridView AND Binded. So all changes in datagridview will reflect in dataTable as well.
Only one adevice, set DataTable variable on a class level, like:

namespace yourNameSpace
{
    DataTable table;
    void YourMethod()
    {
        //my code in here
        but for instanitaited a table only do:
        table = new DataTable();
    }
}

Hope it helps, bye

Edited 5 Years Ago by Mitja Bonca: n/a

I think you're looking for the MySqlDataReader. Something like:

string myQuery = "SELECT * FROM members WHERE name = @name";
string connectionString = "<Your connection string here>";
MySqlConnection con = new MySqlConnection(connectionString);
MySqlCommand cmd = new MySqlCommand(myQuery, con);
cmd.Parameters.AddWithValue("name", "jazerix");

cmd.Connection.Open();

object result;
MySqlDataReader dr = cmd.ExecuteReader();
while (dr.read()) {
    result = dr["name"];
}
cmd.Connection.Close();

Alternatively, if you know that the query will just return one value, you could do it another way:

string myQuery = "SELECT id FROM members WHERE name = @name";
string connectionString = "<You connection string here>";
MySqlConnection con = new MySqlConnection(connectionString);
MySqlCommand cmd = new MySqlCommand(myQuery, con);
cmd.Parameters.AddWithValue("name", "jazerix");

cmd.Connection.Open();
object result = cmd.ExecuteScalar();
cmd.Connection.Close();

Edited 5 Years Ago by mikev2: n/a

This article has been dead for over six months. Start a new discussion instead.