datagridview.columns.add vs datagridview.columns.insert?

本文关键字:datagridview columns insert add vs | 更新日期: 2023-09-27 18:26:35

在使用c#中的windows应用程序编码时,我注意到一些令人困惑的地方,datagridview.columns.adddatagridview.columns.insert

它可以互换使用吗?还是一次?每个的目的是什么?

 DataGridViewColumn dtCol = new DataGridViewColumn();
 dtCol.Name = "ID_New";
 dtCol.DataPropertyName = "ID";
 dtCol.CellTemplate = new DataGridViewTextBoxCell();
 //dataGridView1.Columns.Add(dtCol);
 // dataGridView1.Rows[e.RowIndex].Selected = true;
 dataGridView1.Columns.Insert(3, dtCol);

datagridview.columns.add vs datagridview.columns.insert?

DataGridViewColumnCollection.Insert方法

在集合中的给定索引处插入一列。

DataGridViewColumnCollection.Add Method 

将给定列添加到集合

datagridview.Columns.Insert

在集合中的给定索引处插入一列。

private void CreateUnboundButtonColumn()
{
    // Initialize the button column.
    DataGridViewButtonColumn buttonColumn =
        new DataGridViewButtonColumn();
    buttonColumn.Name = "Details";
    buttonColumn.HeaderText = "Details";
    buttonColumn.Text = "View Details";
    // Use the Text property for the button text for all cells rather 
    // than using each cell's value as the text for its own button.
    buttonColumn.UseColumnTextForButtonValue = true;
    // Add the button column to the control.
    dataGridView1.Columns.Insert(0, buttonColumn);
}

数据网格视图.列.添加

将给定列添加到集合中。

private DataGridView dataGridView1 = new DataGridView();
private void AddColorColumn()
{
    DataGridViewComboBoxColumn comboBoxColumn =
        new DataGridViewComboBoxColumn();
    comboBoxColumn.Items.AddRange(
        Color.Red, Color.Yellow, Color.Green, Color.Blue);
    comboBoxColumn.ValueType = typeof(Color);
    dataGridView1.Columns.Add(comboBoxColumn);
    dataGridView1.EditingControlShowing +=
        new DataGridViewEditingControlShowingEventHandler(
        dataGridView1_EditingControlShowing);
}
private void dataGridView1_EditingControlShowing(object sender,
    DataGridViewEditingControlShowingEventArgs e)
{
    ComboBox combo = e.Control as ComboBox;
    if (combo != null)
    {
        // Remove an existing event-handler, if present, to avoid  
        // adding multiple handlers when the editing control is reused.
        combo.SelectedIndexChanged -=
            new EventHandler(ComboBox_SelectedIndexChanged);
        // Add the event handler. 
        combo.SelectedIndexChanged +=
            new EventHandler(ComboBox_SelectedIndexChanged);
    }
}
private void ComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
    ((ComboBox)sender).BackColor = (Color)((ComboBox)sender).SelectedItem;
}

当您使用DataGridViewColumnCollection.Insert方法时

它将在集合中的该索引处插入一列。以及当您使用DataGridViewColumnCollection.Add方法时它将把给定的列添加到最后一个集合中。

例如:如果你有4列

dataGridView1.Columns.Insert(3, dtCol);

将用新的dtCol替换第3列,并且仍然有4列

如果你使用

dataGridView1.Columns.Add (dtCol);

将添加新的列新的dtCol,您将有5列