簡體   English   中英

以編程方式將單元格和行添加到DataGridView

[英]Programmatically add cells and rows to DataGridView

我正在努力使用DataGridViewComboBoxCell 在某些情況下(比方說,事件),我必須在Form的DataGridView預先選擇ComboBox的值。 當用戶更改一個框時,我可以以編程方式更改另一個框:

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或類似的東西。 通過GetListItem()正確填充和返回ItemCodeItemName列項。 我不明白為什么它正常工作,但在表單加載它不起作用(顯示它也不起作用)。

編輯:對不起,忘了添加。

我的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";

好的,我設法自己解決了。

顯然, 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);
}
        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);

注意:DisplayStyle = DataGridViewComboBoxDisplayStyle.ComboBox以便查看組合。 我用“沒什么”,......:

    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;
        }

    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM