簡體   English   中英

使用C#獲取DataGridView中最后記錄的內容

[英]Get Contents of Last Record in DataGridView using C#

我正在創建一個應用程序,在該應用程序中以表格的形式在dataGridView1中獲取一些數據。 我想訪問某些變量中的最后一行數據,就像我想將列存儲在變量中並使用它們一樣。 我知道如何在GridView Cell click事件中執行此操作,但是我想在循環中使用它,例如每隔10秒鍾就有新數據從數據庫發送到dataGridView1,並且我希望在變量中訪問最后一行。

以下是我如何在dataGridView中加載數據的代碼

using (var con = new SqlConnection(ConStr))
{
    string query = "SELECT * FROM CHECKINOUT";
    using (var cmd = new SqlCommand(query, con))
    {
        con.Open();
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);

        dataGridView1.DataSource = ds.Tables[0].DefaultView;
    }
}

您不僅可以訪問數據集中表0的最后一行,然后將所有列分配給變量嗎?

int lastRow = 0;
lastRow = ds.Tables(0).rows.count - 1;

string col1 = ds.Tables(0).Rows(lastRow)(0).tostring.trim;

使用您的代碼,您可以執行以下操作:

    using (var con = new SqlConnection(ConStr))
{
    string query = "SELECT * FROM CHECKINOUT";
    using (var cmd = new SqlCommand(query, con))
    {
        con.Open();
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);

        dataGridView1.DataSource = ds.Tables[0].DefaultView;
    }
}
    int lastRow = 0;
    lastRow = ds.Tables(0).rows.count - 1;

    string col1 = ds.Tables(0).Rows(lastRow)(0).tostring.trim;
    string col2 = ds.Tables(0).Rows(lastRow)(1).tostring.trim;
    string col3 = ds.Tables(0).Rows(lastRow)(2).tostring.trim;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM