以编程方式将单元格和行添加到DataGridView

时间:2014-08-22 16:27:46

标签: c# winforms datagridview datagridviewcombobox datagridviewcomboboxcell

我正在与DataGridViewComboBoxCell挣扎。在某些情况下(比方说,事件),我必须在我的表单ComboBox中预选DataGridView的值。当用户更改一个框时,我能够以编程方式更改另一个框:

var item = ItemName.Items.GetListItem(name);
if (item != null)
{
    _loading = true; // that's needed to come around another CellValueChanged events
    itemView.Rows[e.RowIndex].Cells["ItemName"].Value = item;
    _loading = false;
}

我正在填充ItemName.Items这样:

foreach (var item in _model.DefaultData.ItemList)
{
    if (item.Value.Code.HasValue()) ItemCode.Items.Add(new ListItem(item.Key, item.Value.Code));
    ItemName.Items.Add(new ListItem(item.Key, item.Value.Name));
}

GetListItem方法:

public static ListItem GetListItem(this DataGridViewComboBoxCell.ObjectCollection col, string name)
{
    ListItem retItem = null;
    foreach (ListItem item in col)
    {
        if (item.Name == name) { retItem = item; break; }
    }
    return retItem;
}

工作正常,但是 ......

现在我想在表单加载上向DataGridView添加行:

foreach (var item in _model.SelectedItems)
{
    var row = new DataGridViewRow();
    row.Cells.Add(new DataGridViewTextBoxCell { Value = item.Id });
    row.Cells.Add(new DataGridViewComboBoxCell { Value = ItemCode.Items.GetListItem(item.Code) });
    row.Cells.Add(new DataGridViewComboBoxCell { Value = ItemName.Items.GetListItem(item.Name) });
    row.Cells.Add(new DataGridViewTextBoxCell { Value = item.Units });
    ...
    itemView.Rows.Add(row);
}

并抛出心爱的DataGridViewComboBox value is not valid例外。请帮忙,我对此不以为然。我不想使用DataSource或类似的东西。 ItemCodeItemName列项目已填充并通过GetListItem()正确返回。我不明白为什么它正常工作,但在表单加载它不起作用(显示它也不起作用)。

编辑:抱歉,忘了添加。

我的ListItem类:

public class ListItem
{
    public int Id { get; set; }
    public string Name { get; set; }
    public ListItem(int sid, string sname)
    {
        Id = sid;
        Name = sname;
    }
    public override string ToString()
    {
        return Name;
    }
}

我已经把它放在表单加载上了:

ItemName.ValueMember = "Id";
ItemName.DisplayMember = "Name";
ItemCode.ValueMember = "Id";
ItemCode.DisplayMember = "Name";

3 个答案:

答案 0 :(得分:3)

好的,我自己设法解决了。

显然,DataGridViewComboBoxColumn.Items包含可能的项目是不够的。如果您以编程方式添加新行,则还必须将项目添加到DataGridViewComboBoxCell.Items

因此,如果其他人试图使用我没有DataTable等数据绑定的方法,那么这就是我的解决方案:

foreach (var item in _model.SelectedItems)
{
    var row = new DataGridViewRow();
    var codeCell = new DataGridViewComboBoxCell();
    codeCell.Items.AddRange(ItemCode.Items);
    codeCell.Value = ItemCode.Items.GetListItem(item.Code);
    var nameCell = new DataGridViewComboBoxCell();
    nameCell.Items.AddRange(ItemName.Items);
    nameCell.Value = ItemName.Items.GetListItem(item.Name);
    row.Cells.Add(new DataGridViewTextBoxCell { Value = item.Id });
    row.Cells.Add(codeCell);
    row.Cells.Add(nameCell);
    row.Cells.Add(new DataGridViewTextBoxCell { Value = item.Units });
    row.Cells.Add(new DataGridViewTextBoxCell { Value = item.Quantity });
    row.Cells.Add(new DataGridViewTextBoxCell { Value = item.PriceLt });
    row.Cells.Add(new DataGridViewTextBoxCell { Value = item.PriceEu });
    itemView.Rows.Add(row);
}

答案 1 :(得分:0)

        DataGridViewColumn[] dgCol = 
        {
          new DataGridViewTextBoxColumn() 
          {
              HeaderText = "Conviction", 
              SortMode = DataGridViewColumnSortMode.NotSortable,
              Width = Convert.ToInt32(0.25f * grdConvictions.Width - 19)
          },
          new DataGridViewTextBoxColumn() 
          {
              HeaderText = "Points"    , 
              SortMode = DataGridViewColumnSortMode.NotSortable,
              Width = Convert.ToInt32(0.125f * grdConvictions.Width - 19)
          },
          new DataGridViewTextBoxColumn() 
          {
              HeaderText = "Date", 
              SortMode = DataGridViewColumnSortMode.NotSortable,
              Width = Convert.ToInt32(0.125f * grdConvictions.Width - 19),
          },
          new DataGridViewComboBoxColumn () 
          {

              HeaderText = "Galletas", 
              Width = Convert.ToInt32(0.25 * grdConvictions.Width - 19),          
              DataPropertyName  = "Galletas",
              DataSource = new List<String>{"",
                                          "Maiz",
                                          "Pera",
                                          "Manzana",
                                          "Sandia",
                                          "Fresa",
                                          "Melon",
                                          "Melocoton",
                                          "Maracuya",
                                          "Cereza",
                                          "Frambuesa",
                                          "Mora",
                                          "Kiwi",
                                          "Anona",
                                          "Guayaba"
                                        },
              SortMode = DataGridViewColumnSortMode.NotSortable,
              MaxDropDownItems = 10,

              DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing,
              ReadOnly = false
          }
        };

YourDataGridView.Columns.AddRange(dgCol);

答案 2 :(得分:0)

注意:DisplayStyle = DataGridViewComboBoxDisplayStyle.ComboBox以便查看组合。我使用&#34;没有&#34;和...:

    private void grdConvictions_CellEnter(object sender, DataGridViewCellEventArgs e)
    {
        int colIndex = e.ColumnIndex;
        int rowIndex = e.RowIndex;

        if (rowIndex < 0 || colIndex < 0)
        {
            return;
        }

        DataGridView grd = (DataGridView)sender;

        if (grd[e.ColumnIndex, e.RowIndex].GetType().Name != "DataGridViewComboBoxCell")
        {
            ((DataGridViewComboBoxCell)grd.CurrentCell).DisplayStyle = DataGridViewComboBoxDisplayStyle.DropDownButton;
        }

}

    private void grdConvictions_CellLeave(object sender, DataGridViewCellEventArgs e)
    {
        int colIndex = e.ColumnIndex;
        int rowIndex = e.RowIndex;

        if (rowIndex < 0 || colIndex < 0)
        {
            return;
        }

        DataGridView grd = (DataGridView)sender;

        if (grd[e.ColumnIndex, e.RowIndex].GetType().Name != "DataGridViewComboBoxCell")
        {
            ((DataGridViewComboBoxCell)grd.CurrentCell).DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing;
        }

    }
相关问题