I’m trying to create a Windows Form application in C#, mostly just to practice what I learned in university. My database is an Access database made up of three tables (SetIndex, SetSong [a junction table], and Song). We never learned how to use a database in an application, just in a web site. Most of what I’ve learned, I’ve learned through trial and error.
I have a combobox list with dates from the SetIndex table, the value being the ID (the primary key of SetIndex). I need to be able to query the database with a select statement that says setindex.id = setsong.setid and setsong.songid = song.id and setIndex.id = a variable, the chosen value from the dropdown list. I wrote a select statement in Access using (setindex.id = ?) that works just fine in Access, but I haven’t figured out how to do it in C#. I’ve found answers about how to use parameters and how to query multiple tables, but nothing that combines the two.
So is there a way to do it within the code?
This is the last thing I tried:
using (OleDbConnection dataConnection = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Mandy\Documents\Visual Studio 2010\Projects\SetManager1.3\SetManager1.3\SetManager.accdb"))
{
using (OleDbCommand dataCommand = dataConnection.CreateCommand())
{
dataCommand.CommandText = "SELECT Title FROM Song WHERE Song.ID = SetSong.SongID AND SetIndex.ID=SetSong.SetID AND SetIndex.ID=@ID";
dataConnection.Open();
dataCommand.Parameters.AddWithValue("@ID", ID);
DataTable table = new DataTable();
OleDbDataAdapter adapter = new OleDbDataAdapter();
adapter.SelectCommand = dataCommand;
adapter.Fill(table);
bindingSource1.DataSource = table;
dataGridView1.AutoResizeColums(DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);
dataGridView1.ReadOnly = true;
dataGridView1.DataSource = bindingSource1;
}
}
ID is an int variable that comes from a global class that takes the ID value from the combo box listing the dates (the value of the selected SetIndex.ID). I tested to make sure this part was working by using a label and a button and it seems to be retrieving the value, storing it in GlobalClass.ViewBySetDate, and converting it to my int ID just fine.
But this is coming up with the error “No value given for one or more required parameters.”
Is there a better/working way to do this? Or, if not, how do I fix the error?
Thank you in advance,
Mandy
Edit: I changed the Select statement to the following:
SELECT song.Title FROM SetIndex INNER JOIN (song INNER JOIN SetSong ON song.ID = SetSong.SongID) ON SetIndex.ID = SetSong.SetID WHERE ((set index.id) =[?]);
The error is no more, but the datagridview is still blank.
Test you query in the database.. the method is the same to access the database, but your query is wrong
SetSong is not defined inside the query.