Execute SQL command and output result to DataGridView in C# -


i trying execute sql command on access database on oledbconnection using c# , use information fill datagridview on windows form. have opened connection, stated query, , executed it, cannot find how output results datagridview on windows form (named dataoutput).

    private void query()     {         string cmdtext = "select * retentiontable " +             "where [datetime] between '" + getdatetimefrom("") + "' , '" + getdatetimeto("") + "'";          string connectionpath = "provider=microsoft.jet.oledb.4.0;data source=retentiondb.mdb";          try         {             oledbconnection cn = new oledbconnection(connectionpath);             dataset objdataset = new dataset();             oledbdataadapter objdataadapter = new oledbdataadapter();              if (cn.state.equals(connectionstate.closed))             {                 cn.open();             }              oledbcommand oledbsearch = new oledbcommand(cmdtext, cn);             oledbsearch.executenonquery();              objdataadapter.fill(objdataset);             dataoutput.datasource = objdataset;             cn.close();         }         catch (exception ex)         {             messagebox.show(ex.message.tostring());             messagebox.show(ex.stacktrace.tostring());         }      } 

from can see, query being executed correctly, issue comes when trying use objdataadapter.fill. guess not understanding how fill dataset output query. appreciated. thanks!

a few comments:

  1. your query subject sql injection. use parameterised query instead.
  2. you don't need open/close connection; dataadapter you.
  3. you should wrap oledbconnection , oledbcommand objects in using block ensure resources cleaned up.
  4. you don't need call executenonquery, or other execute... method on command;
  5. you need assign command selectcommand property of oledbdataadapter, or pass constructor.

try this:

private void query() {    const string connectionpath = "provider=microsoft.jet.oledb.4.0;data source=retentiondb.mdb";     try    {       using (var cn = new oledbconnection(connectionpath))       using (var cmd = new oledbcommand("select * retentiontable [datetime] between ? , ?"))       {          // parameter names don't matter; oledb uses positional parameters.          cmd.parameters.addwithvalue("@p0", getdatetimefrom(""));          cmd.parameters.addwithvalue("@p1", getdatetimeto(""));           var objdataset = new dataset();          var objdataadapter = new oledbdataadapter(cmd);          objdataadapter.fill(objdataset);           dataoutput.datasource = objdataset;       }    }    catch (exception ex)    {       messagebox.show(ex.message.tostring());       messagebox.show(ex.stacktrace.tostring());    } } 

Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -