I have a Windows Form and a database on SQL Server, called RecordStore. I have a table of CDs (called [CD-table]) I am trying to pull data from and display in this form.
I would like to have the form have a combobox that displays the CD album title ("CDname"), but I would like to be able to get the CD ID # ("CDID") from the Combobox.SelectedValue property - which I would cast as an int.
Currently, I am not sure how I can get both pieces of data in unless I made it into an object, but then it is just displaying ProjectName.CD in the combobox. I want to access the CDID as I have a DataGridView that I would like to fill with just CD data, which I would set as a DataTable, then set that DataTable as the DataGridView's DataSource
The method getting the CD Data and returning a list of CD objects.
private string myconnectionString = @"/*connection string*/";
public List<CD> GetCDList()
{
List<CD> CDList = new List<CD>();
SqlConnection myConnection;
SqlCommand myCmd;
SqlDataReader myReader;
myConnection = new SqlConnection(myconnectionString);
myCmd = new SqlCommand("SELECT CDID, CDname FROM [CD-table]", myConnection);
try
{
myConnection.Open();
myReader = myCmd.ExecuteReader();
while (myReader.Read())
{
CD newCD = new CD((int)myReader["CDID"]);
newCD.name = myReader["CDname"].ToString().Trim();
CDList.Add(newCD);
}
myReader.Close();
myConnection.Close();
}
finally
{
myConnection.Close();
}
return CDList;
}
The CD object (very basic):
public class CD
{
public string name;
private int ID;
public CD(int _ID)
{
ID = _ID;
}
}
and the code filling the Combobox on the Form load method:
List<CD> myList = myDataAccess.GetCDList();
AlbumCombobox.DataSource = myList;
Aucun commentaire:
Enregistrer un commentaire