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

时间:2014-10-14 08:05:07

标签: c# datagridview windows-applications

在c#中使用windows应用程序编码时,我发现有些令人困惑, datagridview.columns.add vs datagridview.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);

3 个答案:

答案 0 :(得分:3)

DataGridViewColumnCollection.Insert方法

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

DataGridViewColumnCollection.Add Method 

将给定列添加到集合

答案 1 :(得分:0)

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

datagridview.Columns.Add

将给定列添加到集合中。

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

答案 2 :(得分:0)

使用DataGridViewColumnCollection.Insert方法

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

例如:如果你有4列

dataGridView1.Columns.Insert(3, dtCol);

将用新的dtCol替换第3列,但仍然会有4列

如果您使用

dataGridView1.Columns.Add (dtCol);

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