Tuesday, March 27, 2012

Binding last row in table to a label

Hi all. I have a label on my page and I want to bind it to a field in a table. The catch is that I want to bind it to the last row in the table. I think I can use the custom binding, but I don't know how to bind to the last row. Any Suggestions ?

p.s. The page is tied to an SqlDataSource that retrieves the data from the above table.

Thanks in advance.

Could you not change the datasource to only return the last row? Or did you want all the other rows as well?

What about

Label1.text = dt.Rows(dt.Rows.Count-1)("FieldName").ToString()

where dt is the datatable containing the data you are binding to.

|||

Thanks for the reply GavDraper,

but what is the type of dt, how can I use a sql server table in my code ? and what is the meaning of "FieldName" ?

|||

the type of dt is datatable. You would need to replace fieldname with the name of the field you want to pull data from. below is a very rough quick example although I'm unable to test this as im not at my development machine, you would also want to include some error handling

dim dt as new datatable()dim sqlCon as new sqlConnection(strCon)dim sqlAdp as new SqlDataAdapter()sqlAdp.SelectCommand.Connection = sqlCon()
sqlAdp.Selectcommand.CommandText ("SELECT * FROM tablename")sqlAdp.fill(dt)lbl1.Text = dt.Rows(dt.Rows.Count-1)("FieldName")
|||

I'll give it a try,

but is it possible to do it without the code behind ?

I have the label and I use databinding to bind the fields in the table using the sqldatasource, but somehow it gives me the first row in the table.

I use a stored procedure to select the data from the table and use parameters in that stored procedure. So is it possible to bind to these parameters declaratively so they would give me the fields in the last row ?

The stored procedure:

CREATE PROCEDURE dbo.createPage@.PageTitlenvarchar(300)OUTPUT, @.PageMetaDescnvarchar(300)OUTPUT,@.PageMetaWordsnvarchar(300)OUTPUT,@.PageDescnvarchar(300)OUTPUT,@.PageTemplateint OUTPUTASDECLARE @.pIdAS intSELECT @.pId =cast(SCOPE_IDENTITY()AS int)--selecting the id of the last row inserted--selecting the data from that rowSELECT PageTitle,PageMetaDesc,PageMetaWords,PageDesc,PageHTML, PageTemplate, PageSummaryHTMLFROM PagesWHERE PageId = @.pIdGO
 
|||

that stored procedure is returning the data in no particular order how can you be sure its always the last record you want? You could change the stored procedure to only return 1 record by using the TOP keyword but to make this accurate the data would have to be ordered to guarentee you will always get the correct row.

No comments:

Post a Comment