binding to datagrid from code behind page.

  • Thread starter Thread starter mike
  • Start date Start date
M

mike

I'm having a problem with binding my sqldatareader to my
datagrid in my asp .net page.

Below is my code in the page_load section of the code
behind page:

Dim oCon2 As SqlClient.SqlConnection = New
SqlClient.SqlConnection("data source=Test;initial
catalog=data1;password=;user id=sa;packet size=4096")
oCon2.Open()

Dim cmd As SqlClient.SqlCommand = New
SqlClient.SqlCommand("AwardCalendar2", oCon2)
cmd.CommandType = CommandType.StoredProcedure
Dim par As SqlClient.SqlParameter = New
SqlClient.SqlParameter("@Date", SqlDbType.DateTime)
par.Direction = ParameterDirection.Input
par.Value = strdate
cmd.Parameters.Add(par)
Dim sqlreader As SqlClient.SqlDataReader
sqlreader = cmd.ExecuteReader()

DataGrid1.DataSource = sqlreader
DataGrid1.DataBind()

sqlreader.Close()
oCon2 = Nothing

The datagrid in the aspx file is defined as follows:

<asp:DataGrid id="DataGrid1" style="Z-INDEX: 105; LEFT:
14px; POSITION: absolute; TOP: 146px" runat="server"
Height="178px" Width="532px" ForeColor="Black"
BackColor="#8080FF" BorderColor="Blue"></asp:DataGrid>

When I run the page it doesn't show the datagrid. I have
a querystring that specifies the date value entered.
 
First a word of WARNING. NEVER develop with SA and ALWAYS set your SA
password to something other than "". This is crucial to avoid a plague of
locusts from attacking your server.
Next, we don't know who you are besides "news.microsoft.com". Please
identify yourself.

You are attempting to bind to the first resultset returned by the SP. It
might not contain a rowset or the rowset might be empty (I suspect the
former). You're also going the long way around to code this. How about:

Dim oCon2 As New SqlClient.SqlConnection ("data source=Test;initial
catalog=data1;password=YY;user id=XX;packet size=4096")
oCon2.Open()

Dim cmd As New SqlClient.SqlCommand("AwardCalendar2", oCon2)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add(("@Date", SqlDbType.DateTime).Value = strDate
Dim sqlreader As SqlClient.SqlDataReader
sqlreader = cmd.ExecuteReader(CommandBehavior.CloseConnection)
DataGrid1.DataSource = sqlreader
DataGrid1.DataBind()
sqlreader.Close()
oCon2 = Nothing

hth

--
____________________________________
William (Bill) Vaughn
Author, Mentor, Consultant
MVP, hRD
www.betav.com
Please reply only to the newsgroup so that others can benefit.
This posting is provided "AS IS" with no warranties, and confers no rights.
__________________________________
 
Back
Top