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
Hey! Try this, If you just want to display the names of all employees into a listBox, this should work. I just edited some lines from your code...
Form1()
{
InitializeComponent();
openFileDialog1.ShowDialog();
openedFile = openFileDialog1.FileName;
lbxEmployeeNames.DataSource = Query("Select [name] FROM [Employees$]");
lbxEmployeeNames.DisplayMember = "name"; // The column you want to be displayed in your listBox.
}
// Return a DataTable instead of String.
public DataTable Query(string sql)
{
System.Data.OleDb.OleDbConnection MyConnection;
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();
System.Data.OleDb.OleDbDataAdapter myDataAdapter = new System.Data.OleDb.OleDbDataAdapter(sql, MyConnection);
DataTable dt = new DataTable();
myDataAdapter.Fill(dt);
return dt;
}