SouthAfricanGuy SouthAfricanGuy - 3 months ago 27
C# Question

c# how to use Combobox.Value for a From Clause in a Sql query

Please can you assist me in a very weird request

I am building a form to represent a table in a datagridview.
I want to change the data that is bound to the datagridview when i select a different value in a combobox. I bound the event to a button.

i get an error when i run the code:

An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll Additional information: Syntax error in query. Incomplete query clause.



the code i have is as follows.

private void Ok_button3_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(@"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = E:\database.accdb; Persist Security Info =False;");
OleDbCommand cmd = new OleDbCommand("Select * From @name ", con);
cmd.Parameters.AddWithValue("@name", comboBox1.SelectedValue);

cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
dt.TableName = "Project";
dataGridView1.DataSource = dt;

}

Answer

This code will help you:

private void Ok_button3_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(@"Provider =        Microsoft.ACE.OLEDB.12.0; Data Source = E:\database.accdb; Persist Security Info =False;");
OleDbCommand cmd = new OleDbCommand(String.Concat("Select * From ",comboBox1.Text), con); 


cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();            
da.Fill(dt);
dt.TableName = "Project";
dataGridView1.DataSource = dt;
}