Monday, March 19, 2012

Get value from datasource in codebehind

Lets say I have a Sqldatasource that uses the following SelectCommand="SELECT category,name FROM table". How do I get the value on category from my datasource in code behind if I know that my selectcommand always will return one row? Can I write something like datasource.items["category"].Value?


Thanks for your help!

You can retrieve the value from your datasource from either dataview or datareader. Here is a sample for your reference:

You can access your SqlDataSouce from code behind through a dataview or datareader by calling select() of the SqlDatasource. If theDataSourceMode property of the SqlDatasource is set to DataSet and you get the dataview(this is default), or a DataReader if it is set to DataReader.

'Programmatically access the SqlDataSource - get back a DataView
Dim dview As DataView = CType(yourSqlDataSource.Select(DataSourceSelectArguments.Empty), DataView)

Dim str1 as string = String.Empty

For Each drow As DataRow In dview.Table.Rows

str1 &= drow("yourcol1").ToString() & "<br />"


NEXT

Or through a datareader ( don't forget to set DataSourceMode property to DataReader)

Dim myreader as SqlDataReader=CType(rndProductsDataSource.Select(DataSourceSelectArguments.Empty), SqlDataReader)

Dim str1 as string=String.Empty
if myreader.Read()
str1= reader(0) ' or your first column name

else

end if

myreader.Close()

No comments:

Post a Comment