0
votes

I am creating an application in which I am getting some data in my dataGridView1 in my form. I want to access my last row of data in some variables like I want to store columns in variables and use them. I know how to do this in GridView Cell click event but I want to use this in a loop like after every 10 seconds new data comes from database to dataGridView1 and I want last row to be accessed in variables.

Below is the code of how I am loading data in 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;
    }
}
1

1 Answers

1
votes

Can you not just access the last row of Table 0 in your dataset and then assign all columns to variables

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

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

Using your code you could do:

    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;