Datagridview最後一行
在C#中,DataGridView的Rows
屬性是一個DataGridViewRowCollection
對象,它表示DataGridView中的所有行。要獲取DataGridView的最後一行,你可以使用Rows
屬性的Count
屬性來獲取行數,然後通過索引獲取最後一行。
以下是一個簡單的示例,展示了如何獲取DataGridView的最後一行:
using System;
using System.Windows.Forms;
namespace DataGridViewExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
// 假設DataGridView的ID是 dataGridView1
DataGridViewRow lastRow = this.dataGridView1.Rows[this.dataGridView1.Rows.Count - 1];
// 處理最後一行
// 例如,顯示最後一行中的某個值
string lastRowValue = lastRow.Cells[0].Value.ToString();
MessageBox.Show("Last row value: " + lastRowValue);
}
}
}
在上面的代碼中,我們首先獲取DataGridView的Rows
屬性的Count
,然後使用這個值減去1來獲取最後一行。最後,我們列印出最後一行中的某個單元格的值。
請注意,如果你的DataGridView可能沒有數據或者可能有多選行,那麼你需要檢查行數和索引是否有效,以確保不會訪問超出範圍的行。