DataGridView.Rows DataGridView.Rows DataGridView.Rows DataGridView.Rows Property

정의

DataGridView 컨트롤의 모든 행을 포함하는 컬렉션을 가져옵니다.Gets a collection that contains all the rows in the DataGridView control.

public:
 property System::Windows::Forms::DataGridViewRowCollection ^ Rows { System::Windows::Forms::DataGridViewRowCollection ^ get(); };
[System.ComponentModel.Browsable(false)]
public System.Windows.Forms.DataGridViewRowCollection Rows { get; }
member this.Rows : System.Windows.Forms.DataGridViewRowCollection
Public ReadOnly Property Rows As DataGridViewRowCollection

속성 값

예제

다음 코드 예제에 바인딩되지 않은 만드는 방법을 보여 줍니다 DataGridView; set를 ColumnHeadersVisible, ColumnHeadersDefaultCellStyle, 및 ColumnCount 속성 및 사용 합니다 RowsColumns 속성입니다.The following code example demonstrates how to create an unbound DataGridView; set the ColumnHeadersVisible, ColumnHeadersDefaultCellStyle, and ColumnCount properties; and use the Rows and Columns properties. 버전을 사용 하는 방법을 보여 줍니다 합니다 AutoResizeColumnHeadersHeightAutoResizeRows 열 머리글과 행을 적절히 조정 하는 방법입니다.It also demonstrates how to use a version of the AutoResizeColumnHeadersHeight and AutoResizeRows methods to properly size the column headers and the rows. 이 예제를 실행 하려면 다음 코드를 포함 하는 형식으로 붙여넣습니다를 DataGridView 라는 dataGridView1 이라는 단추가 Button1를 호출 합니다 InitializeDataGridView 폼의 생성자에서 메서드 또는 Load 이벤트 처리기.To run this example, paste the following code into a form that contains a DataGridView named dataGridView1 and a button named Button1, and then call the InitializeDataGridView method from the form's constructor or Load event handler. 모든 이벤트가 해당 이벤트 처리기를 사용 하 여 연결을 확인 합니다.Ensure all events are connected with their event handlers.

   void InitializeDataGridView()
   {
      this->Size = System::Drawing::Size( 600, 600 );
      dataGridView1->Size = System::Drawing::Size( 450, 400 );

      // Create an unbound DataGridView by declaring a column count.
      dataGridView1->ColumnCount = 4;
      dataGridView1->ColumnHeadersVisible = true;

      // Set the column header style.
      DataGridViewCellStyle ^ columnHeaderStyle = gcnew DataGridViewCellStyle;
      columnHeaderStyle->BackColor = Color::Aqua;
      columnHeaderStyle->Font = gcnew System::Drawing::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.
      array<String^>^row1 = gcnew array<String^>{
         "Meatloaf","Main Dish","ground beef","**"
      };
      array<String^>^row2 = gcnew array<String^>{
         "Key Lime Pie","Dessert","lime juice, evaporated milk","****"
      };
      array<String^>^row3 = gcnew array<String^>{
         "Orange-Salsa Pork Chops","Main Dish","pork chops, salsa, orange juice","****"
      };
      array<String^>^row4 = gcnew array<String^>{
         "Black Bean and Rice Salad","Salad","black beans, brown rice","****"
      };
      array<String^>^row5 = gcnew array<String^>{
         "Chocolate Cheesecake","Dessert","cream cheese","***"
      };
      array<String^>^row6 = gcnew array<String^>{
         "Black Bean Dip","Appetizer","black beans, sour cream","***"
      };
      array<Object^>^rows = {row1,row2,row3,row4,row5,row6};
      System::Collections::IEnumerator^ myEnum = rows->GetEnumerator();
      while ( myEnum->MoveNext() )
      {
         array<String^>^rowArray = safe_cast<array<String^>^>(myEnum->Current);
         dataGridView1->Rows->Add( rowArray );
      }
   }

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

   void InitializeContextMenu()
   {
      // Create the menu item.
      MenuItem^ getRecipe = gcnew MenuItem( "Search for recipe",gcnew System::EventHandler( this, &Form1::OnMenuClick ) );

      // Add the menu item to the shortcut menu.
      System::Windows::Forms::ContextMenuStrip^ recipeMenu = gcnew System::Windows::Forms::ContextMenuStrip();

      // Set the shortcut menu for the first column.
      dataGridView1->Columns[ 0 ]->ContextMenuStrip = recipeMenu;
   }

   void OnMenuClick( Object^ /*sender*/, System::EventArgs^ /*e*/ )
   {
      if ( dataGridView1->CurrentCell != nullptr )
      {
         //Retrieve the recipe name.
         String^ recipeName = dynamic_cast<String^>(dataGridView1->CurrentCell->Value);

         //Search for the recipe.
         System::Diagnostics::Process::Start( String::Format( "http://search.msn.com/results.aspx?q={0}", recipeName ), nullptr );
      }
   }

private:

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);
    }
}
Private Sub InitializeDataGridView()

    ' Create an unbound DataGridView by declaring a column count.
    dataGridView1.ColumnCount = 4
    dataGridView1.ColumnHeadersVisible = True

    ' Set the column header style.
    Dim columnHeaderStyle As 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.
    Dim row1() As String = {"Meatloaf", "Main Dish", "ground beef", "**"}
    Dim row2() As String = _
        {"Key Lime Pie", "Dessert", "lime juice, evaporated milk", "****"}
    Dim row3() As String = {"Orange-Salsa Pork Chops", "Main Dish", _
        "pork chops, salsa, orange juice", "****"}
    Dim row4() As String = {"Black Bean and Rice Salad", "Salad", _
        "black beans, brown rice", "****"}
    Dim row5() As String = _
        {"Chocolate Cheesecake", "Dessert", "cream cheese", "***"}
    Dim row6() As String = _
        {"Black Bean Dip", "Appetizer", "black beans, sour cream", "***"}
    Dim rows() As Object = {row1, row2, row3, row4, row5, row6}

    Dim rowArray As String()
    For Each rowArray In rows
        dataGridView1.Rows.Add(rowArray)
    Next rowArray

End Sub

Private Sub button1_Click(ByVal sender As Object, _
    ByVal e As System.EventArgs) Handles button1.Click

    ' 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)

End Sub

Private Sub InitializeContextMenu()

    ' Create the menu item.
    Dim getRecipe As New ToolStripMenuItem( _
        "Search for recipe", Nothing, AddressOf ShortcutMenuClick)

    ' Add the menu item to the shortcut menu.
    Dim recipeMenu As New ContextMenuStrip()
    recipeMenu.Items.Add(getRecipe)

    ' Set the shortcut menu for the first column.
    dataGridView1.Columns(0).ContextMenuStrip = recipeMenu

End Sub

Private clickedCell As DataGridViewCell

Private Sub dataGridView1_MouseDown(ByVal sender As Object, _
    ByVal e As MouseEventArgs) Handles dataGridView1.MouseDown

    ' If the user right-clicks a cell, store it for use by the 
    ' shortcut menu.
    If e.Button = MouseButtons.Right Then
        Dim hit As DataGridView.HitTestInfo = _
            dataGridView1.HitTest(e.X, e.Y)
        If hit.Type = DataGridViewHitTestType.Cell Then
            clickedCell = _
                dataGridView1.Rows(hit.RowIndex).Cells(hit.ColumnIndex)
        End If
    End If

End Sub

Private Sub ShortcutMenuClick(ByVal sender As Object, _
    ByVal e As System.EventArgs)

    If (clickedCell IsNot Nothing) Then
        'Retrieve the recipe name.
        Dim recipeName As String = CStr(clickedCell.Value)

        'Search for the recipe.
        System.Diagnostics.Process.Start( _
            "http://search.msn.com/results.aspx?q=" + recipeName)
    End If

End Sub

설명

사용할 수는 Rows 수동으로 채울 컬렉션입니다는 DataGridView 컨트롤 데이터 소스에 바인딩하는 대신 합니다.You can use the Rows collection to manually populate a DataGridView control instead of binding it to a data source. 다음 예제에서는 수동으로 추가 하 고 행을 삽입 하는 방법을 보여 줍니다.The following example shows you how to manually add and insert rows. 이 예에서는 4 개를 추가 했다고 가정 DataGridViewTextBoxColumn 컨트롤의 인스턴스 Columns 컬렉션입니다.This example assumes that you have added four DataGridViewTextBoxColumn instances to the control's Columns collection.

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

자세한 예제를 프로그래밍 방식으로 바인딩되지 않은 채우는 DataGridView 제어 예제 섹션을 참조 하세요.For a detailed example that programmatically populates an unbound DataGridView control, see the Example section.

행에는 셀 값 외에도 스타일 정보가 포함 됩니다.Rows include style information in addition to cell values. 이러한 이유로 추가 하거나 이미 스타일이 지정 하는 기존 행을 기준으로 행을 삽입 하는 것이 좋습니다.For this reason, you might want to add or insert rows based on existing rows that you have already styled. 사용 하 여 수행할 수 있습니다 합니다 AddCopy, AddCopiesInsertCopy, 및 InsertCopies 메서드.You can do this using the AddCopy, AddCopies, InsertCopy, and InsertCopies methods.

사용할 수도 있습니다는 Rows 컨트롤에서 값을 수정 하거나 행을 제거할 컬렉션입니다.You can also use the Rows collection to modify the values in the control or to remove rows. 값을 수정 하거나 컨트롤 외부 데이터 원본에 바인딩되어 있는지 여부에 관계 없이 행을 제거할 수 있습니다.You can modify values or remove rows regardless of whether the control is bound to an external data source. 데이터 원본에 있으면 변경 데이터 원본에 직접 적용 합니다.If there is a data source, the changes are made directly to the data source. 그러나 원격 데이터베이스에 데이터 소스 업데이트를 푸시 하려면 계속 해야 합니다.You may still need to push the data source updates to a remote database, however. 자세한 내용은 방법: Windows Forms DataGridView 컨트롤에 데이터를 바인딩합니다.For more information, see How to: Bind Data to the Windows Forms DataGridView Control.

다음 예제에서는 프로그래밍 방식으로 셀 값을 수정 하는 방법을 보여 줍니다.The following example shows you how to modify cell values programmatically.

' Modify the value in the first cell of the second row.  
Me.dataGridView1.Rows[1].Cells[0].Value = "new value"  
  
' The previous line is equivalent to the following line.  
Me.dataGridView1[0, 1].Value = "new value"  
// 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 행에 대 한 정보를 검색할 컬렉션.In addition to the standard collection capabilities, you can use the Rows collection to retrieve information about rows. 사용 된 GetRowState 특정 행의 상태를 확인 하는 방법입니다.Use the GetRowState method to determine the state of a particular row. 사용 된 GetRowCountGetRowsHeight 행 개수 또는 특정 상태에서 행의 전체 높이 결정 하는 방법입니다.Use the GetRowCount and GetRowsHeight methods to determine the number of rows or the combined height of rows in a particular state. 특정 상태에 있는 행의 인덱스를 검색 하려면 사용 합니다 GetFirstRow, GetLastRowGetNextRow, 및 GetPreviousRow 메서드.To retrieve the index of a row with a particular state, use the GetFirstRow, GetLastRow, GetNextRow, and GetPreviousRow methods.

다음 예제에서는 첫 번째 선택한 행의 인덱스를 검색 하 고를 사용 하 여 프로그래밍 방식으로 행을 삭제 하는 방법을 보여 줍니다.The following example shows you how to retrieve the index of the first selected row, and then use it to programmatically delete the row.

Dim rowToDelete As Int32 = Me.dataGridView1.Rows.GetFirstRow( _  
    DataGridViewElementStates.Selected)  
If rowToDelete > -1 Then  
    Me.dataGridView1.Rows.RemoveAt(rowToDelete)  
End If  
Int32 rowToDelete = this.dataGridView1.Rows.GetFirstRow(  
    DataGridViewElementStates.Selected);  
if (rowToDelete > -1)  
{  
    this.dataGridView1.Rows.RemoveAt(rowToDelete);  
}  

성능 향상을 위해 합니다 DataGridViewRowCollection 반환한는 Rows 속성 공유 일정과 비공유 행을 포함할 수 있습니다.To improve performance, the DataGridViewRowCollection returned by the Rows property can include shared and unshared rows. 큰 레코드 집합의 비용을 줄이기 위해 메모리를 공유 하는 공유 행입니다.Shared rows share memory to reduce the cost of a large record set. 레코드 집합 매우 큰 경우 각별한 주의가 액세스할 때 행이 공유를 최대한 유지 하는 Rows 속성입니다.If your record set is very large, you should be careful to keep the rows shared as much as possible when accessing the Rows property.

자세한 내용은 Windows Forms DataGridView 컨트롤의 크기 조정에 대 한 모범 사례합니다.For more information, see Best Practices for Scaling the Windows Forms DataGridView Control.

적용 대상

추가 정보