Click here to Skip to main content
15,891,184 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a stored procedure which is generating a attendance report (in sql server 2012).
now I have to execute this stored procedure from my VB.NET application and display the results in a DataGrid View. help me out to display the result in the datagrid view in vb.

This is the code for stored procedure:

SQL
<pre>USE [first_db]
GO

/****** Object:  StoredProcedure [dbo].[GET_ATTENDANCE]    Script Date: 22-02-2018 11:34:43 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[GET_ATTENDANCE]
@STARTDATE  DATETIME,
@ENDDATE    DATETIME
AS BEGIN

--Now generate dates between two dates by Common table expression . and store that values in one temporary table (#TMP_DATES) .
;WITH DATERANGE  AS
(
  SELECT DT =DATEADD(DD,0, @STARTDATE)
  WHERE DATEADD(DD, 1, @STARTDATE) <= @ENDDATE
  UNION ALL
  SELECT DATEADD(DD, 1, DT)
  FROM DATERANGE
  WHERE DATEADD(DD, 1, DT) <= @ENDDATE
)
SELECT * INTO #TMP_DATES
FROM DATERANGE


--As the Report columns (Dates) are dynamic ,  hence Columns (Dates) are concatenated   one by one  from Temporary table (#TMP_DATES) and store the value in a local variable . 
DECLARE @COLUMN VARCHAR(MAX)
SELECT @COLUMN=ISNULL(@COLUMN+',','')+ '['+ CAST(CONVERT(DATE , T.DT) AS VARCHAR) + ']'  FROM #TMP_DATES T

--After Pivot , some columns may be Null as data (here PRESENT_STATUS) not exists in pivot section    .Now  replace the Null values by 'N/A'  .

DECLARE @Columns2 VARCHAR(MAX)
SET @Columns2 = SUBSTRING((SELECT DISTINCT ',ISNULL(['+ CAST(CONVERT(DATE , DT) as varchar )+'],''A'') AS ['+CAST(CONVERT(DATE , DT) as varchar )+']' FROM #TMP_DATES GROUP BY dt FOR XML PATH('')),2,8000)

--Now declare one local variable to write the dynamic sql query .
DECLARE @QUERY VARCHAR(MAX)

--Here Right outer join is done to show the all dates from the temporary table

SET @QUERY = 'SELECT User_Id, ' + @Columns2  +' FROM
            (
                  SELECT  A.User_Id , B.DT AS DATE, A.STATUS FROM MarkA A RIGHT OUTER  JOIN #TMP_DATES B ON A.DATE=B.DT              
           ) X
            PIVOT
            (
                 MIN([STATUS])
                 FOR [DATE] IN (' + @COLUMN + ')
            ) P
            WHERE ISNULL(User_Id,'''')<>''''
            '

 EXEC (@QUERY)

 --Drop the  temporary table
      DROP TABLE #TMP_DATES
     
 END

GO


What I have tried:

this is the code in vb:
Private Sub StartDatePicker_ValueChanged(sender As Object, e As EventArgs) Handles StartDatePicker.ValueChanged
        ' StartDate = Format(StartDatePicker.Value, "yyyy/mm/dd")
        sd = Date.Parse(StartDatePicker.Text)


    End Sub

    Private Sub EndDatePicker_ValueChanged(sender As Object, e As EventArgs) Handles EndDatePicker.ValueChanged
        'EndDate = Format(EndDatePicker.Value, "yyyy/mm/dd")
        ed = Date.Parse(EndDatePicker.Text)

    End Sub

Private Sub Show_Button_Click(sender As Object, e As EventArgs) Handles Show_Button.Click
        Try
            Dim dt As DataTable = New DataTable()


            Dim cmd As SqlCommand = New SqlCommand("GET_ATTENDANCE", connection)
            cmd.CommandType = CommandType.StoredProcedure

            cmd.Connection = connection


            
            cmd.Parameters.AddWithValue("@STARTDATE", sd)
            cmd.Parameters.AddWithValue("@ENDDATE", ed)

            connection.Open()
            Dim adp As New SqlDataAdapter(cmd)
            Dim ds As DataSet = New DataSet()
            cmd.ExecuteNonQuery()

            adp.Fill(ds, "GET_ATTENDANCE")


            DataGridView1.DataSource = ds.Tables(0)
            connection.Close()


        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try



        

    End Sub
End Class

I have a form which selects the start date and end date from the user and displays the result in the data grid view.But this code neither generates an error nor an exception is thrown ?? so what should i do (results are not getting displayed in the datagridview)
Posted
Updated 21-Feb-18 23:51pm
v3
Comments
Maciej Los 22-Feb-18 2:13am    
Are you sure that your SP is working fine? Does it return any data if you execute it on MS SQL Manangement Studio?
Member 13674721 22-Feb-18 3:20am    
yes it is properly executing on the sql management studio and showing the desired results
Maciej Los 22-Feb-18 3:24am    
Next time, please, use "Reply" widget, if you want to inform me about your answer.
Member 13674721 22-Feb-18 3:30am    
Sorry !!i ll take care next time
Maciej Los 22-Feb-18 3:33am    
Don't worry. :)

1 solution

try this -
below code spinet is from my program, this works fine for me

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
public partial class _Default : System.Web.UI.Page
{
	protected void Page_Load(object sender, EventArgs e)
	{
		SqlCommand command = new SqlCommand();
		SqlDataAdapter adapter = new SqlDataAdapter();
		DataSet ds = new DataSet();
		int i = 0;
		string sql = null;
		string connetionString = "Data Source=.;Initial Catalog=pubs;User ID=sa;Password=*****";
		SqlConnection connection = new SqlConnection(connetionString);
		connection.Open();
		command.Connection = connection;
		command.CommandType = CommandType.StoredProcedure;
		command.CommandText = "EmployeeData";
		adapter = new SqlDataAdapter(command);
		adapter.Fill(ds);
		connection.Close();
		GridView1.DataSource = ds.Tables[0];
		GridView1.DataBind();
	}
}


read this blog as well-
Bind data to grid view using SP

and this one as well
Grid View Binding using Stored Procedure[^]
 
Share this answer
 
v2
Comments
Member 13674721 22-Feb-18 8:33am    
Still its not showing the results in the data grid view .

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900