X

[WinForm] How to dynamically add a drop down list in datagridview control

Scenario: You need to dynamically add a drop down list in a DataGridView control in a WinForm.

Requirements: The items of the drop down list are dynamically bound with data from database.

Solution:

1. Connect to database and retrieve data into a datatable, i.e. dtRanks;

2. Create a DataGridViewCombBoxColumn, set necessary properties of the CombBox column, then add it to the GridView control:

DataGridViewComboBoxColumn ranks = new DataGridViewComboBoxColumn();

ranks.DataPropertyName = “TestID”;
ranks.Name = “TestID”;
ranks.HeaderText = “Rank”;
ranks.DropDownWidth = 100;
ranks.Width = 70;
ranks.FlatStyle = FlatStyle.Flat;

ranks.DataSource = dtRanks; // populate the CombBox column
ranks.ValueMember = “RankID”;
ranks.DisplayMember = “RankTitle”;
ranks.SortMode = DataGridViewColumnSortMode.Automatic;
ranks.ReadOnly = false;

this.dgvTestHistory.Columns.Insert(0, ranks); // insert the column as the first column
this.dgvTestHistory.Sort(ranks, ListSortDirection.Ascending);

If you don’t want user to select items from the CombBox column (just for displaying data), then change ReadOnly property to true:

ranks.ReadOnly = true;

0 0 votes
Article Rating
Jeffrey:
Related Post