Question

I want invoke the last column's last row value and display it in a textbox (TextBox2.Text) in C#.

Table details: In one event I inserted the row value so uncount rows insert into the table. I want to achieve in another (result) event to get last column's last row value... How is it possible, possibly explained with some code? Or is there some general syntax to get last row value?

Was it helpful?

Solution

Fetch total rows and columns and pass these values as index to datatable dtable

int totalRows = dtable.Rows.Count;
int totalCols = dtable.Columns.Count;

string value = dtable.Rows[totalRows-1][totalCols-1].ToString();

TextBox2.Text=value;

Suppose your datatable dtable in C# contains these rows and now you want last columns last row value that is col3 last row value which if you see in datatable below is vgt.

col1 | col2 | col3
 1      abc    pqr
 2      art    lmn
 3      yut    xyz
 4      btt    vgt

dtable.Rows.Count gives me number of rows which is 4

dtable.Columns.Count gives me number of columns which is 3

So to access the last row last column value we pass these values as index to datatable which is like a 2D array and since you know arrays start from index 0 , the actual address of last row last column would be [totalRows-1][totalColumns-1]

OTHER TIPS

SELECT LAST(column_name) FROM table_name; This command will help you to access last row of any column. just name of last column . and run

If the last column name is known and the rows have one unique id is int field which is not autoid or integer you can just do the above :

  string query = " select top 1 youlastcolumnname   from 
      FROM youtable ORDER BY youruniqueid desc";

C# code as asked:

 using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(yourconnectionstring))
            {
                conn.Open();
                System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(query , conn);
                cmd.CommandType = System.Data.CommandType.Text;
                youttextbox.Text = cmd.ExecuteScalar().ToString();
                conn.Close();
            }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top