DataGridView.Rows 屬性
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
取得集合,其中包含 DataGridView 控制項中的所有資料列。
public:
property System::Windows::Forms::DataGridViewRowCollection ^ Rows { System::Windows::Forms::DataGridViewRowCollection ^ get(); };
[System.ComponentModel.Browsable(false)]
public System.Windows.Forms.DataGridViewRowCollection Rows { get; }
[<System.ComponentModel.Browsable(false)>]
member this.Rows : System.Windows.Forms.DataGridViewRowCollection
Public ReadOnly Property Rows As DataGridViewRowCollection
屬性值
DataGridViewRowCollection,包含 DataGridView 中的所有資料列。
- 屬性
範例
下列程式代碼範例示範如何建立未系結 DataGridView的、設定 ColumnHeadersVisible、 ColumnHeadersDefaultCellStyle和 ColumnCount 屬性,以及使用 Rows 和 Columns 屬性。 它也會示範如何使用 和 AutoResizeRows 方法的版本AutoResizeColumnHeadersHeight,適當地調整數據行標頭和數據列的大小。 若要執行此範例,請將下列程式代碼貼到包含DataGridView具名dataGridView1
的表單和名為Button1
的按鈕,然後從表單的建構函式或Load事件處理程式呼叫 InitializeDataGridView
方法。 確定所有事件都與其事件處理程序連接。
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 而不是將它系結至數據源。 下列範例示範如何手動新增和插入數據列。 此範例假設您已將四 DataGridViewTextBoxColumn 個實例新增至控件的 Columns 集合。
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 控件的詳細範例,請參閱一節。
數據列除了儲存格值之外,還包含樣式資訊。 基於這個理由,您可能會想要根據您已設定樣式的現有數據列來新增或插入數據列。 您可以使用、AddCopies、 InsertCopy和 InsertCopies 方法來執行此AddCopy動作。
您也可以使用 Rows 集合來修改 控件中的值,或移除數據列。 不論控制項是否系結至外部數據來源,您都可以修改值或移除資料列。 如果有數據源,則會直接對數據源進行變更。 不過,您可能仍然需要將數據源更新推送至遠端資料庫。 如需詳細資訊,請參閱如何:將數據系結至 Windows Forms DataGridView 控件。
下列範例示範如何以程序設計方式修改儲存格值。
' 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 集合來擷取數據列的相關信息。 GetRowState使用 方法來判斷特定數據列的狀態。 GetRowCount使用和 GetRowsHeight 方法來判斷特定狀態的數據列數目或數據列的組合高度。 若要擷取具有特定狀態的數據列索引,請使用GetFirstRow、 GetLastRowGetNextRow和 GetPreviousRow 方法。
下列範例示範如何擷取第一個選取數據列的索引,然後使用它以程序設計方式刪除數據列。
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 可以包含共用和未共享的數據列。 共用數據列會共用記憶體,以減少大型記錄集的成本。 如果您的記錄集非常大,您應該小心,在存取 Rows 屬性時盡可能保留共享的數據列。
如需詳細資訊,請參閱 縮放 Windows Form DataGridView 控制項的最佳做法。