简体   繁体   中英

how to insert multiple value into combobox using dataset from database in c#

this is my code for multiple value in combobox. I have frmEntryHistory which entry a student id and his/her name in combobox , bookID and the title in combobox, and then date. im using method on class library to get data from database and store them in dataset. And then i call that method on frmEntryHistory. I can appear ID-Tittle on combobox but not as record just name of columns on master_book table. Please help me and sorry for confusing english. :)

// Method Library Class
 public DataSet getBooks_ComboBox()
    {
        IDbDataAdapter adapter = null;
        DataSet ds = null;

        try
        {
            sb = new StringBuilder();
            adapter = new MySqlDataAdapter();
            comm = new MySqlCommand();
            ds = new DataSet();
            openConnection();
            comm.Connection = conn;
            sb.Append(@"select ID, ID + ' - ' + Title as Book from master_book");
            comm.CommandText = sb.ToString();
            adapter.SelectCommand = (MySqlCommand)comm;
            adapter.Fill(ds);
            closeConnection();
            return ds;
        }

        catch (Exception ex)
        {
            return null;
        }
    }

//In my form Entry History 
  private void frmEntryHistory_Load(object sender, EventArgs e)
    {
        lblTgl.Text = DateTime.Now.ToString("dd/MM/yyyy");
        Library lib = new Library();
        DataSet ds = new DataSet();
        //stored item into combobox
        try 
        {           
            ds = lib.getBooks_ComboBox();
            cmbBook.DataSource = ds.Tables[0];
            cmbBook.DisplayMember = "Book";
            cmbBook.ValueMember = "ID";
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

what i want for output from combobox is ID - Title example : 1 - Novel asd, etc

After you fill the datatable, before you bind it to the combobox, you can create a new column to use. This example uses the pubs database:

DataSet1.titlesDataTable TitlesTable = new DataSet1.titlesDataTable();

titlesTableAdapter1.Fill(TitlesTable);

DataColumn DC = new DataColumn();
DC.ColumnName = "Test";
DC.DataType = typeof(string);
DC.Expression = string.Format("{0} + '-' + {1}", "title_id", "title");
TitlesTable.Columns.Add(DC);

comboBox1.DataSource = TitlesTable;
comboBox1.DisplayMember = "Test";
comboBox1.ValueMember = "title_id";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM