Showing posts with label sqldatareader. Show all posts
Showing posts with label sqldatareader. Show all posts

Wednesday, March 7, 2012

new in .Net but learning SqlConnection, SqlCommand and SqlDataReader How in code_behind

Hi.

I want to now a little about CodeBehind how to use it with SqlConnection, SqlCommand and SqlDataReader.

How i use:
Web.Config
<connectionStrings>
<add name="ConnectionStringTest" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\DSNbase.mdb;Persist Security Info=True"providerName="System.Data.OleDb"/>
</connectionStrings>

Default.aspx
<asp:RepeaterID="test"runat="server"DataSourceID="SqlDataSourcetest">
...
..
<asp:SqlDataSourceID="SqlDataSourcetest"runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionStringTest %>"
ProviderName="<%$ ConnectionStrings:ConnectionStringTest.ProviderName %>"
SelectCommand="SELECT [ID], [Name], [Sex], [Born], [Color], [Dog], [Images] FROM [Dogs] WHERE ([Dog] = 'YES') ORDER BY [ID]">
</asp:SqlDataSource>

How can i take my asp:SqlDataSource and put it in my CodeBehind, so it use the ConnectionString from my Web.Config and so i can use my Repeater on my default.aspx site.. !?
Maybe if u got a great link that show "How to do" maybe om MSDN/MSDN2.

You can use a datareader. Heres an example i put together using a stored procedure:

#region StoredProcedure GetDogs
// CREATE PROCEDURE GetDogs()
// AS
// SELECT ID, Name, Sex, Born, Color, Dog, Images FROM Dogs WHERE Dog='YES' ORDER BY ID
// RETURN
#endregion

//This will get the connectionstring from the web.config
SqlConnection objConn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringText"].ConnectionString);
SqlCommand objCmd = new SqlCommand("GetDogs", objConn);
objCmd.CommandType = CommandType.StoredProcedure;

objConn.Open();
SqlDataReader objRdr = objCmd.ExecuteReader(CommandBehavior.CloseConnection);

if (objRdr.HasRows)
{
testRepeater.DataSource = objRdr;
testRepeater.DataBind();
}
else { // do alternative if no data is present. }

objRdr.Close();
objConn.Close();

|||

Hi.

How will this look like if im using VB.

|||

This should work, but im not 100% sure, Im doing this by hand and not in VS, but its striaght forward and you should be able to see how to change it:

//This will get the connectionstring from the web.config
Dim objConn As SqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringText"].ConnectionString)
Dim objCmd As SqlCommand = new SqlCommand("GetDogs", objConn)
objCmd.CommandType = CommandType.StoredProcedure

objConn.Open();
Dim objRdr As SqlDataReader = objCmd.ExecuteReader(CommandBehavior.CloseConnection)

testRepeater.DataSource = objRdr
testRepeater.DataBind()

objRdr.Close()
objConn.Close()

Hope this helps.