带Dropdownlist的DataGridView在Desktop应用程序中引发异常

时间:2015-01-21 06:57:40

标签: c# datagridview combobox

我开发了一个小应用程序,其中我使用了Grid-view并在其中放入了一个下拉列表。使用下拉列表我可以编辑列表并在运行时添加值。

问题:
当我在其中添加任何值并单击时,它会给我一些错误。在组合框中添加了一些时间值。但有时它通过异常。

例外:
 DataGridViewCell值无效。 enter image description here

Mycode看起来像:

 DataGridViewComboBoxColumn groupcmb = new DataGridViewComboBoxColumn();
    groupcmb.Name = "grdgroup";  
    groupcmb.HeaderText = "Group";  
    groupcmb.MinimumWidth = 120;  
    var items = groupname.getlist();  
    groupcmb.DataSource = items;  
    grddevices.Columns.Insert(5, groupcmb); 

private void grddevices_EditingControlShowing(object sender,    DataGridViewEditingControlShowingEventArgs e)  
{  
if (e.Control.GetType() == typeof(DataGridViewComboBoxEditingControl))  
{  
DataGridViewComboBoxEditingControl cbo = e.Control as  DataGridViewComboBoxEditingControl;  
cbo.DropDownStyle = ComboBoxStyle.DropDown;  
//cbo.SelectedIndex = 0;  
if (cbo.Items.Count != 0)  
{  
cbo.SelectedIndex = 0;  
}  
cbo.Validating += new CancelEventHandler(cbo_Validating);  

}  
}  

// Event call  



 public void cbo_Validating(object sender, CancelEventArgs e)  
    { 
    try  
    {  
    DataGridViewComboBoxEditingControl cbo = sender as DataGridViewComboBoxEditingControl;  
    DataGridView grid = cbo.EditingControlDataGridView;  
    object value = cbo.Text;  
    if (value.ToString() != "")  
    {  
    cbo.Validating -= new CancelEventHandler(cbo_Validating);  
    if (cbo.Items.IndexOf(value) == -1)  
    {
    GroupName groupname = new GroupName();  
    DataGridViewComboBoxCell cboCol =(DataGridViewComboBoxCell)grid.CurrentCell;  

   groupname.Group = value.ToString();  
   groupname.AddGroupName();  
   cbo.SelectedText = value.ToString();  

   }  
   }  
   }  
   catch (Exception ex)  
   {  
   MessageBox.Show(ex.ToString());  
   }  

   }  


class GroupName
    {
        public static List<string> group = new List<string>();

        public GroupName()
        {

        }
        public string Group { set; get; }
        public void AddGroupName()
        {
            group.Add(Group);
        }
        public int numberofGroup()
        {
            return group.Count;
        }
        //public string getGroupname(int i)
        //{
        //    return group.ElementAt(i);
        //}
        public List<string> getlist()
        {
            return group;
        }
    }

0 个答案:

没有答案