DataGridViewComboBoxColumn set the selectedindex

大兔子大兔子 提交于 2019-12-07 03:38:58

问题


hi i runtime bind the data into datagridview combobox. But how do i make it to auto display the first item? i do not able find the selectedindex from DataGridViewComboBoxColumn.

  DataGridViewComboBoxColumn cbStudentCourse = (DataGridViewComboBoxColumn)dgStudentCourse.Columns["studentCourseStatus"];
                    cbStudentCourse.DataSource = Enum.GetValues(typeof(CourseStudentStatus));
                    cbStudentCourse.DisplayIndex = 1;

-- Update ---
i saw someone doing this in solution 3
LInk
Are you sure i need such a long code to just have the first item selected??????


回答1:


A DataGridViewComboBoxColumn has no SelectedIndex, and SelectedValue properties. However you can get the same behavior of SelectedValue by setting the Value property.

For instance on first index the value member has value 2 then you should set .Value = "2" to set the first index selected.

For example

myDataGridViewComboBoxColumn.Value = "20";

In your case

myDataGridViewComboBoxColumn.Value = CourseStudentStatus.EnumToBeSelected.ToString();

Here is more details about DataGridViewComboBoxColumn




回答2:


the best way to set the value of a datagridViewComboBoxCell is:

DataTable dt = new DataTable();
dt.Columns.Add("Item");
dt.Columns.Add("Value");
dt.Rows.Add("Item1", "0");
dt.Rows.Add("Item1", "1");
dt.Rows.Add("Item1", "2");
dt.Rows.Add("Item1", "3");
DataGridViewComboBoxColumn cmb = new DataGridViewComboBoxColumn();
cmb.DefaultCellStyle.Font = new Font("Tahoma", 8, FontStyle.Bold);
cmb.DefaultCellStyle.ForeColor = Color.BlueViolet;
cmb.FlatStyle = FlatStyle.Flat;
cmb.Name = "ComboColumnSample";
cmb.HeaderText = "ComboColumnSample";
cmb.DisplayMember = "Item";
cmb.ValueMember = "Value";
DatagridView dvg=new DataGridView();
dvg.Columns.Add(cmb);
cmb.DataSource = dt;
for (int i = 0; i < dvg.Rows.Count; i++)
{
dvg.Rows[i].Cells["ComboColumnSample"].Value = (cmb.Items[0] as 
DataRowView).Row[1].ToString();
}

It worked with me very well



来源:https://stackoverflow.com/questions/5367561/datagridviewcomboboxcolumn-set-the-selectedindex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!