DataGridView.Rows 属性

定义

获取一个集合,该集合包含 DataGridView 控件中的所有行。

C#
[System.ComponentModel.Browsable(false)]
public System.Windows.Forms.DataGridViewRowCollection Rows { get; }

属性值

一个 DataGridViewRowCollection,包含 DataGridView 控件中的所有行。

属性

示例

下面的代码示例演示如何创建未绑定 DataGridView的 ;设置 ColumnHeadersVisibleColumnHeadersDefaultCellStyleColumnCount 属性;并使用 RowsColumns 属性。 它还演示如何使用 和 AutoResizeRows 方法的版本AutoResizeColumnHeadersHeight来正确调整列标题和行的大小。 若要运行此示例,请将以下代码粘贴到包含DataGridView名为 dataGridView1 的按钮的Button1窗体中,然后从窗体的构造函数或Load事件处理程序调用 InitializeDataGridView 方法。 确保所有事件都与其事件处理程序连接。

C#
private void InitializeDataGridView()
{
    // Create an unbound DataGridView by declaring a column count.
    dataGridView1.ColumnCount = 4;
    dataGridView1.ColumnHeadersVisible = true;

    // Set the column header style.
    DataGridViewCellStyle columnHeaderStyle = new DataGridViewCellStyle();

    columnHeaderStyle.BackColor = Color.Beige;
    columnHeaderStyle.Font = new Font("Verdana", 10, FontStyle.Bold);
    dataGridView1.ColumnHeadersDefaultCellStyle = columnHeaderStyle;

    // Set the column header names.
    dataGridView1.Columns[0].Name = "Recipe";
    dataGridView1.Columns[1].Name = "Category";
    dataGridView1.Columns[2].Name = "Main Ingredients";
    dataGridView1.Columns[3].Name = "Rating";

    // Populate the rows.
    string[] row1 = new string[] { "Meatloaf", "Main Dish", "ground beef",
        "**" };
    string[] row2 = new string[] { "Key Lime Pie", "Dessert", 
        "lime juice, evaporated milk", "****" };
    string[] row3 = new string[] { "Orange-Salsa Pork Chops", "Main Dish", 
        "pork chops, salsa, orange juice", "****" };
    string[] row4 = new string[] { "Black Bean and Rice Salad", "Salad", 
        "black beans, brown rice", "****" };
    string[] row5 = new string[] { "Chocolate Cheesecake", "Dessert", 
        "cream cheese", "***" };
    string[] row6 = new string[] { "Black Bean Dip", "Appetizer", 
        "black beans, sour cream", "***" };
    object[] rows = new object[] { row1, row2, row3, row4, row5, row6 };

    foreach (string[] rowArray in rows)
    {
        dataGridView1.Rows.Add(rowArray);
    }
}

private void button1_Click(object sender, System.EventArgs e)
{
    // Resize the height of the column headers. 
    dataGridView1.AutoResizeColumnHeadersHeight();

    // Resize all the row heights to fit the contents of all non-header cells.
    dataGridView1.AutoResizeRows(
        DataGridViewAutoSizeRowsMode.AllCellsExceptHeaders);
}

private void InitializeContextMenu()
{
    // Create the menu item.
    ToolStripMenuItem getRecipe = new ToolStripMenuItem("Search for recipe", null,
        new System.EventHandler(ShortcutMenuClick));

    // Add the menu item to the shortcut menu.
    ContextMenuStrip recipeMenu = new ContextMenuStrip();
    recipeMenu.Items.Add(getRecipe); 

    // Set the shortcut menu for the first column.
    dataGridView1.Columns[0].ContextMenuStrip = recipeMenu;
    dataGridView1.MouseDown += new MouseEventHandler(dataGridView1_MouseDown);
}

private DataGridViewCell clickedCell;

private void dataGridView1_MouseDown(object sender, MouseEventArgs e)
{
// If the user right-clicks a cell, store it for use by the shortcut menu.
    if (e.Button == MouseButtons.Right)
    {
        DataGridView.HitTestInfo hit = dataGridView1.HitTest(e.X, e.Y);
        if (hit.Type == DataGridViewHitTestType.Cell)
        {
            clickedCell =
                dataGridView1.Rows[hit.RowIndex].Cells[hit.ColumnIndex];
        }
    }
}

private void ShortcutMenuClick(object sender, System.EventArgs e)
{
    if (clickedCell != null)
    {
        //Retrieve the recipe name.
        string recipeName = (string)clickedCell.Value;

        //Search for the recipe.
        System.Diagnostics.Process.Start(
            "http://search.msn.com/results.aspx?q=" + recipeName);
            //null);
    }
}

注解

可以使用 Rows 集合手动填充控件, DataGridView 而不是将其绑定到数据源。 以下示例演示如何手动添加和插入行。 此示例假定已将四 DataGridViewTextBoxColumn 个实例添加到控件的 Columns 集合。

C#
this.dataGridView1.Rows.Add("five", "six", "seven", "eight");this.dataGridView1.Rows.Insert(0, "one", "two", "three", "four");

有关以编程方式填充未绑定 DataGridView 控件的详细示例,请参阅示例部分。

除单元格值外,行还包括样式信息。 出于此原因,你可能希望根据已设置样式的现有行添加或插入行。 可以使用 、、 AddCopiesInsertCopyInsertCopies 方法来执行此操作AddCopy

还可以使用 Rows 集合修改 控件中的值或删除行。 无论控件是否绑定到外部数据源,都可以修改值或删除行。 如果有数据源,则直接对数据源进行更改。 但是,可能仍需要将数据源更新推送到远程数据库。 有关详细信息,请参阅如何:将数据绑定到 Windows 窗体 DataGridView 控件

以下示例演示如何以编程方式修改单元格值。

C#
// Modify the value in the first cell of the second row.
this.dataGridView1.Rows[1].Cells[0].Value = "new value";

// The previous line is equivalent to the following line.
this.dataGridView1[0, 1].Value = "new value";

除了标准集合功能外,还可以使用 Rows 集合来检索有关行的信息。 GetRowState使用 方法确定特定行的状态。 GetRowCount使用 和 GetRowsHeight 方法可确定处于特定状态的行数或行的组合高度。 若要检索具有特定状态的行的索引,请使用 GetFirstRowGetLastRowGetNextRowGetPreviousRow 方法。

以下示例演示如何检索第一个选定行的索引,然后使用它以编程方式删除该行。

C#
Int32 rowToDelete = this.dataGridView1.Rows.GetFirstRow(
    DataGridViewElementStates.Selected);
if (rowToDelete > -1)
{
    this.dataGridView1.Rows.RemoveAt(rowToDelete);
}

为了提高性能, DataGridViewRowCollection 属性返回的 Rows 可以包括共享行和非共享行。 共享行共享内存以降低大型记录集的成本。 如果记录集非常大,在访问 Rows 属性时,应注意尽可能多地共享行。

有关详细信息,请参阅 缩放 Windows 窗体 DataGridView 控件的最佳做法

适用于

产品 版本
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
Windows Desktop 3.0, 3.1, 5, 6, 7, 8, 9, 10

另请参阅