jacksonSD
jacksonSD

Reputation: 677

Fill Combobox with Data from Database

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;

Upvotes: 1

Views: 800

Answers (2)

Jes&#250;s L&#243;pez
Jes&#250;s L&#243;pez

Reputation: 9221

You just need to set ValueMember and DisplayMember properties:

List<CD> myList = myDataAccess.GetCDList();
AlbumCombobox.DataSource = myList;
AlbumCombobox.DisplayMember = "Name";
AlbumCombobox.ValueMember = "ID";

The CD class should be defined as follows:

public class CD
{
    public string Name {get; set; }
    public int ID {get; private set;}

    public CD(int _ID)
    {
        ID = _ID;
    }
}

Upvotes: 3

Ultraspark
Ultraspark

Reputation: 1

Answer given by @jesus Lopez is correct. But we need to check whether the valuemember string as it is case sensitive. Otherwise it will throw "Could not bind to the new value member." error.

Link: http://www.fmsinc.com/free/NewTips/NET/NETtip37.asp

List<CD> myList = myDataAccess.GetCDList();
AlbumCombobox.DataSource = myList;
AlbumCombobox.DisplayMember = "name";
AlbumCombobox.ValueMember = "ID"; // case sensitive.

Cheers!.

Upvotes: 0

Related Questions