c# creating a database query METHOD
Posted
by
Sinaesthetic
on Stack Overflow
See other posts from Stack Overflow
or by Sinaesthetic
Published on 2010-10-23T03:29:31Z
Indexed on
2012/04/15
5:30 UTC
Read the original article
Hit count: 181
I'm not sure if im delluded but what I would like to do is create a method that will return the results of a query, so that i can reuse the connection code. As i understand it, a query returns an object but how do i pass that object back? I want to send the query into the method as a string argument, and have it return the results so that I can use them. Here's what i have which was a stab in the dark, it obviously doesn't work. This example is me trying to populate a listbox with the results of a query; the sheet name is Employees and the field/column is name. The error i get is "Complex DataBinding accepts as a data source either an IList or an IListSource.". any ideas?
public Form1()
{
InitializeComponent();
openFileDialog1.ShowDialog();
openedFile = openFileDialog1.FileName;
lbxEmployeeNames.DataSource = Query("Select [name] FROM [Employees$]");
}
public object Query(string sql)
{
System.Data.OleDb.OleDbConnection MyConnection;
System.Data.OleDb.OleDbCommand myCommand = new System.Data.OleDb.OleDbCommand();
string connectionPath;
//build connection string
connectionPath = "provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + openedFile + "';Extended Properties=Excel 8.0;";
MyConnection = new System.Data.OleDb.OleDbConnection(connectionPath);
MyConnection.Open();
myCommand.Connection = MyConnection;
myCommand.CommandText = sql;
return myCommand.ExecuteNonQuery();
}
© Stack Overflow or respective owner