How to update existing rows via trigger with C# in SQL - c#

I have a table in SQL called EmpLog which contains the 'start' and 'end' data for employees. I'm quite confused as to how I'm going to change the variables within the trigger during update since it has to cater to all different employees. Do I need to alter the trigger via sql parameter in c# for every insertion? or is there an alternative to keep it minimal and efficient? Thank you in advance. Since as far as I'm able to understand triggers are hard coded onto the database, which is changeable through 'ALTER'. What can I do to change existing row's with different IDs via trigger?
create trigger TrgEmpLog on EmpLog
AFTER UPDATE
AS
declare #shiftstart time;
declare #shiftend time;
declare #totalminutes decimal(18,2);
IF EXISTS (SELECT shiftend FROM EmpLog WHERE EmpID = "C# Variable" and CONVERT(date,LogDate) = CONVERT(date, GETDATE()) and shiftend is not null)
BEGIN
IF EXISTS (SELECT EmpLog.TotalMinutes from EmpLog WHERE EmpID = "C# Variable" and CONVERT(date,LogDate) = CONVERT(date, GETDATE()) and TotalMinutes is not null)
BEGIN
ROLLBACK TRANSACTION
END
ELSE
select #shiftstart=EmpLog.ShiftStart from EmpLog where EmpID = "C# Variable" and CONVERT(date,LogDate) = CONVERT(date, GETDATE()) and TotalMinutes IS NULL;
select #shiftend=EmpLog.ShiftEnd from EmpLog where EmpID = "C# Variable" and CONVERT(date,LogDate) = CONVERT(date, GETDATE()) and TotalMinutes IS NULL;
select #totalminutes=DATEDIFF(MINUTE,#shiftstart, #shiftend);
UPDATE EmpLog
SET TotalMinutes=#totalminutes/60.00
WHERE EmpID= "C# Variable"and CONVERT(date,LogDate) = CONVERT(date, GETDATE());
END
ELSE
BEGIN
ROLLBACK TRANSACTION
END
And the code that I'm using to prompt the trigger is:
UPDATE EmpLog
SET ShiftEnd = 'current time'
WHERE EmpID='C# variable' and CONVERT(date,LogDate) = CONVERT(date, GETDATE());
This code below ends in a trigger, but it works when I remove the 'and logDate = getdate().
UPDATE EmpLog SET ShiftEnd = '09:00:00' WHERE EmpID = 1 and CONVERT(date, LogDate) = CONVERT(date, GETDATE())

This code below worked for me with some quick testing. Maybe it will work for what you need. The actual trigger part is probably all you really need, the rest I was using to test.
The way this is written, it will only update the current, and relevant record (the one being updated at the time). Joining to the inserted table makes sure that happens. Use the inserted and deleted Tables (MSDN)
CREATE TABLE EmpLog (EmpID int, ShiftStart time, Shiftend time, LogDate date, TotalMinutes decimal(18,2));
GO
-- Trigger starts here
CREATE TRIGGER TrgEmpLog ON EmpLog
AFTER UPDATE
AS
IF EXISTS (SELECT *
FROM EmpLog A JOIN inserted B
ON A.EmpID = B.EmpID
WHERE CONVERT(date, A.LogDate) = CONVERT(date, GETDATE())
AND A.shiftend IS NOT NULL)
BEGIN
IF EXISTS (SELECT *
FROM EmpLog A JOIN inserted B
ON A.EmpID = B.EmpID
WHERE CONVERT(date, A.LogDate) = CONVERT(date, GETDATE())
AND A.TotalMinutes IS NOT NULL)
BEGIN
ROLLBACK TRANSACTION
END
UPDATE EmpLog
SET TotalMinutes=DATEDIFF(MINUTE, A.ShiftStart, A.Shiftend)/60.00
FROM EmpLog A JOIN inserted B
ON A.EmpID = B.EmpID;
END
ELSE
BEGIN
ROLLBACK TRANSACTION
END
GO
-- Trigger End here
INSERT INTO EmpLog (EmpID, ShiftStart, Shiftend, LogDate) VALUES (1, '00:00:00', NULL, GETDATE()),
(2, '08:00:00', NULL, GETDATE()),
(3, '16:00:00', NULL, GETDATE());
SELECT * FROM EmpLog;
UPDATE EmpLog SET Shiftend = '08:00:00' WHERE EmpID = 1;
SELECT * FROM EmpLog;
DROP TABLE EmpLog;
You may have to play around with some of the IF EXISTS, if they don't follow you logic exactly.
As #massimiliano mentioned in the comments, triggers can get quite complicated if you want them to. For me, I avoid that. The trigger is always one of the last places I think to look when troubleshooting issues. Personal preference!
Good Luck!

Related

SQL Server Trigger on Specified Columns

Hey,
I am trying to update some columns in my table in SQL Server 2014 and I wrote some code on the trigger and to consequently insert the new values into a new table, using the following code procedure:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Atrin Noori
-- =============================================
ALTER TRIGGER [dbo].[UsersOnUPDATE]
ON [dbo].[Users]
After UPDATE
AS
BEGIN
SET NOCOUNT ON;
--
DECLARE #user_key int
SELECT #user_key = i.User_key FROM inserted i;
--
IF UPDATE (User_fullname)
BEGIN
DECLARE #newfullname nvarchar(MAX);
DECLARE #oldfullname nvarchar(MAX);
--
SELECT #oldfullname = i.User_fullname FROM deleted i;
SELECT #newfullname = i.User_fullname FROM inserted i;
--
INSERT INTO UsersLogs (UL_user_key_r, UL_date, UL_oldname, UL_newname, UL_IsDeleted)
VALUES (#user_key, GETDATE(), #oldfullname, #newfullname, 0)
END
--
ELSE IF UPDATE (User_password)
BEGIN
DECLARE #newpassword nvarchar(10);
DECLARE #oldpassword nvarchar(10);
--
SELECT #oldpassword = i.User_password FROM deleted i;
SELECT #newpassword = i.User_password FROM inserted i;
--
INSERT INTO UsersLogs (UL_user_key_r,UL_date,UL_oldpass,UL_newpass,UL_IsDeleted)
VALUES (#user_key, GETDATE(), #oldpassword, #newpassword, 0)
END
--
ELSE IF UPDATE (User_username)
BEGIN
DECLARE #newusername nvarchar(10);
DECLARE #oldusername nvarchar(10);
--
SELECT #oldusername = i.User_username FROM deleted i;
SELECT #newusername = i.User_username FROM inserted i;
--
INSERT INTO UsersLogs (UL_user_key_r, UL_date, UL_oldusername, UL_newusername, UL_IsDeleted)
VALUES (#user_key, GETDATE(), #oldusername, #newusername, 0)
END
--
ELSE IF UPDATE (User_position_id_r)
BEGIN
DECLARE #newposid tinyint;
DECLARE #oldposid tinyint;
--
SELECT #oldposid = i.User_position_id_r FROM deleted i;
SELECT #newposid = i.User_position_id_r FROM inserted i;
--
INSERT INTO UsersLogs (UL_user_key_r, UL_date, UL_oldPosid, UL_newPosid, UL_IsDeleted)
VALUES (#user_key, GETDATE(), #oldposid, #newposid, 0)
END
END
This trigger works fine when I manually change the values in each column and inserts into a new table called UsersLogs.
However it does not work fine when I use the c# application I am developing to update the values...
CONSIDER:
I am trying to change the password of a user through my application
and using a Stored Procedure.
The Stored Procedure works fine and updates the values, BUT the trigger of UserOnUpdate inserts the old and new value of User_Fullnme (not oldpassword and newpassword) into the new table (UsersLgos) and set others to null (which is OK to be null).
I mean only this part of code will run:
IF UPDATE (User_fullname)
BEGIN
DECLARE #newfullname nvarchar(MAX);
DECLARE #oldfullname nvarchar(MAX);
--
SELECT #oldfullname = i.User_fullname FROM deleted i;
SELECT #newfullname = i.User_fullname FROM inserted i;
--
INSERT INTO UsersLogs (UL_user_key_r, UL_date, UL_oldname, UL_newname, UL_IsDeleted)
VALUES (#user_key, GETDATE(), #oldfullname, #newfullname, 0)
END
And by the things I just said... I change the password and SET a condition to check for the updated column.
But the question is why the trigger cannot realize which column was updated through the application ?
NOTE:
I say it again: IT WORKS FINE WITH THE MANUAL CHANGES AND UPDATES
The UPDATE() function only tells you if a column was present in the UPDATE statement, not if the value actually changed. Furthermore, te inserted and deleted tables may contain multiple rows, or none.
So, your trigger should really look like this:
ALTER TRIGGER [dbo].[UsersOnUPDATE]
ON [dbo].[Users]
After UPDATE
AS
SET NOCOUNT ON;
IF NOT (UPDATE(User_fullname) OR UPDATE(User_password) OR UPDATE(User_username) OR UPDATE(User_position_id_r))
RETURN; -- this only tells you if the column was present
INSERT INTO UsersLogs
(UL_user_key_r, UL_date, UL_IsDeleted,
UL_oldname, UL_newname,
UL_oldpass, UL_newpass,
UL_oldusername, UL_newusername,
UL_oldPosid, UL_newPosid)
SELECT
i.user_key, GETDATE(), 0,
d.fullname, i.fullname,
d.User_password, i.User_password,
d.User_username, i.User_username,
d.User_position_id_r, i.User_position_id_r
FROM inserted i
JOIN deleted d ON i.user_key = d.user_key
WHERE EXISTS ( -- this checks for any differences
SELECT i.fullname, i.User_password, i.User_username, i.User_position_id_r
EXCEPT -- this will deal with nulls correctly
SELECT d.fullname, d.User_password, d.User_username, d.User_position_id_r
);
In case of only some columns being updated, this does leave you with the other columns having the same before and after values. But some CASE expressions should sort that out.
ALTER TRIGGER [dbo].[UsersOnUPDATE]
ON [dbo].[Users]
After UPDATE
AS
SET NOCOUNT ON;
IF NOT (UPDATE(User_fullname) OR UPDATE(User_password) OR UPDATE(User_username) OR UPDATE(User_position_id_r))
RETURN; -- this only tells you if the column was present
INSERT INTO UsersLogs
(UL_user_key_r, UL_date, UL_IsDeleted,
UL_oldname, UL_newname,
UL_oldpass, UL_newpass,
UL_oldusername, UL_newusername,
UL_oldPosid, UL_newPosid)
SELECT
i.user_key, GETDATE(), 0,
CASE WHEN d.fullname <> i.fullname THEN d.fullname END, CASE WHEN d.fullname <> i.fullname THEN i.fullname END
CASE WHEN d.User_password <> i.User_password THEN d.User_password END, CASE WHEN d.User_password <> i.User_password THEN i.User_password END,
CASE WHEN d.User_username <> i.User_username THEN d.User_username END, CASE WHEN d.User_username <> i.User_username THEN i.User_username END,
CASE WHEN d.User_position_id_r <> i.User_position_id_r THEN d.User_position_id_r END, CASE WHEN d.User_position_id_r <> i.User_position_id_r THEN i.User_position_id_r END
FROM inserted i
JOIN deleted d ON i.user_key = d.user_key
WHERE EXISTS ( -- this checks for any differences
SELECT i.fullname, i.User_password, i.User_username, i.User_position_id_r
EXCEPT -- this will deal with nulls correctly
SELECT d.fullname, d.User_password, d.User_username, d.User_position_id_r
);
If you want separate rows for every value changed, you could unpivot with a CROSS APPLY
update() trigger function , returns true if the column is updated even if with the same value.
so seems like when you update password, you are updating User_fullname column and other columns probably (with the same value as before of course) . so UPDATE (User_fullname) returns true .
But, also the way you have've written your code , the trigger works for the situation only one column is updated and in that order in your code , for example if UPDATE (User_fullname) is true , your code doesn't check other conditions , because of ELSE IF. you might wanna remove else and check for each column , or totally change your strategy to log data inside trigger.
then based on your comment , get rid of all if else and have one single insert statement like so for all columns:
INSERT INTO UsersLogs (UL_user_key_r,UL_date,UL_oldpass,UL_newpass,<all columns>)
select (#user_key, GETDATE(), case when deleted.password <> new.password then deleted.password else null end , case when deleted.password <> new.password then inserted.password else null end , ....)
from inserted i
join deleted d on i.userkey = d.userkey

Counting field by day in mssql

I have a table with Scheduling slots called:
ScheduleSlots
Fields:
id (int)
scheduleID (int)
time (datetime)
availableslots (int)
CalendarGroupID (int)
Level (int)
enabled (bit)
I want to setup a gridview where I take all of the dates and count enabled and disabled for each day.
I am not sure how to go about writing the sql statement to do this.
ie.
Date Enabled Disabled
3/31/2021 20 20
4/1/2021 10 30
SELECT Time, scheduleID,
(SELECT COUNT(Enabled) FROM [dbo].[ScheduleSlots]
WHERE Cast(Time as Date)>='2021-03-31' AND Cast(Time as Date)<='2021-04-01' AND CalendarGroupID=1 AND Level=1 AND Enabled=1) as Enabled,
(SELECT COUNT(Enabled) FROM [dbo].[ScheduleSlots]
WHERE Cast(Time as Date)>='2021-03-31' AND Cast(Time as Date)<='2021-04-01' AND CalendarGroupID=1 AND Level=1 AND Enabled=0) as Disabled
FROM [dbo].[ScheduleSlots]
WHERE Cast(Time as Date)>='2021-03-31' AND Cast(Time as Date)<='2021-04-01' AND CalendarGroupID=1 AND Level=1
GROUP BY scheduleID, Time
The results I end up with:
[Results][1]
You could do it without inner selects:
SELECT [Time],
SUM([Enabled]) as [Enabled],
SUM([Disabled]) as [Disabled]
FROM [dbo].[ScheduleSlots]
WHERE
[Time]>='2021-03-31'
AND [Time]<='2021-04-01'
AND CalendarGroupID=1
AND Level=1
GROUP BY Cast([Time] as Date)
It is an easy grouping query:
SELECT
CONVERT(DATE, "Time") AS "Date",
SUM(CONVERT(INT, "Enabled")) AS "Enabled",
COUNT() - SUM(CONVERT(INT, "Enabled")) AS "Disabled"
FROM "dbo"."ScheduleSlots"
WHERE "CalendarGroupID" = 1
AND "Level" = 1
GROUP BY CONVERT(DATE, "Time")
I hope I understand you correctly where you want the enable slot and diable slot for each day.
;With CTE(Transdate) as (Select Distinct([time]) from ScheduleSlots)
Select CTE.Transdate,(Select COUNT(Id) from ScheduleSlots where enabled= 1
and Transdate = CTE.Transdate) as Enable,
(Select COUNT(Id) from ScheduleSlots where enabled= 0
and Transdate = CTE.Transdate) as Disable from CTE
I inserted some records to make it clear. If I am wrong with inserted data please send me the insert scripts so, that I can test the results.
CREATE TABLE ScheduleSlots
(
id int,
scheduleID int,
[time] datetime,
availableslots int,
CalendarGroupID int,
[Level] int,
[enabled] bit
)
----insert into ScheduleSlots values(1,1,'2021-03-31',40,1,1,20)
INSERT INTO ScheduleSlots VALUES(1,1,'2021-03-31',20,1,1,0)
INSERT INTO ScheduleSlots VALUES(1,1,'2021-03-31',20,1,1,1)
INSERT INTO ScheduleSlots VALUES(1,1,'2021-03-31',20,1,1,1)
INSERT INTO ScheduleSlots VALUES(1,1,'2021-04-01',40,1,1,1)
INSERT INTO ScheduleSlots VALUES(1,1,'2021-04-01',40,1,1,0)
SELECT DISTINCT
[time] AS [Date]
,SUM(availableslots) OVER(PARTITION BY [time] ORDER BY [time]) AS [avaibale]
,SUM(CAST([enabled] AS INT)) OVER(PARTITION BY [time] ORDER BY [time]) AS [Enabled]
,SUM(availableslots) OVER(PARTITION BY [time] ORDER BY [time]) -
SUM(CAST([enabled] AS INT)) OVER(PARTITION BY [time] ORDER BY [time]) AS [Disabled]
FROM ScheduleSlots
Answer I got:

Duplicate Entry Insertion while insertion of DataTable in Stored Procedure

I'm inserting DataTable in Database using StoredProcedure but the issue is, its inserting twice the actual number of entries of DataTable to be inserted, the procedure is below, kindly guide me, if I'm using wrong approach, why its duplicating the rows? The return which is required is working fine.
Thanks In Advance
ALTER PROCEDURE [dbo].[proc_InsertStore_Recvry]
(#dt_Recovery Recovery_Store READONLY)
AS
Declare #RecoveryIDs as Table (IDs int, ClientIds int)
declare #StoreID int
declare #ClientID int
declare #Arrears decimal(18, 2)
declare #NetDues decimal(18, 2)
declare #Received decimal(18, 2)
Declare #RecoveryRecID int
begin
select * into #tempTable from #dt_Recovery
declare #Count int
set #Count= (select COUNT(*) from #tempTable)
while(#Count > 0)
begin
set #Count = #Count-1
set #ClientID = (Select top 1 ClientID from #tempTable)
set #StoredID = (Select top 1 StoredID from #tempTable where ClientID=#ClientID)
set #Arrears = (Select top 1 Arrears from #tempTable where ClientID=#ClientID)
set #NetDues = (Select top 1 NDues from #tempTable where ClientID=#ClientID)
set #Received = (Select top 1 Received from #tempTable where ClientID=#ClientID)
Insert into tblRecovery (StoreID, ClientID, Arrears, NetDues, Received)
values (#StoreID,#ClientID,#Arrears,#NetDues,#Received)
select #RecoveryID = Scope_Identity()
insert into #RecoveryIDs (IDs,ClientIds) values (#RecoveryID, #ClientID )
delete from #tempTable where ClientID=#ClientID
end
Select * from #RecoveryIDs
it looks like you are using SQL Server. If yes then why are you using a while-loop to insert values into a table and return the inserted Ids?
The same can be accomplished in a far better way via the OUTPUT clause:
OUTPUT documentation
Example:
INSERT INTO tblRecovery(StoreID, ClientID, Arrears, NetDues, Received) OUTPUT INSERTED.ID, INSERTED.CLientId INTO #RecoveryIDs(IDs, ClientIds) SELECT StoredID, ClientID, Arrears, NDues, Received FROM #tempTable
Aside from that there seems to be no issue with your SQL code. So could you post the .NET code as well?

Stored Procedure Not Accepting Integer Parameter

I have been using a Stored Procedure created by our DB guy, who happens to be out of town for the next week. The SP used to work, but before he left, the DB guy edited the SP, causing my code to throw a server error: "Column name or number of supplied values does not match table definition". He claimed before he left the SP should mainly be the same, so I'm at a loss for why it's no longer matching.
Here is the c# code:
System.Data.SqlClient.SqlCommand objCmd = new
System.Data.SqlClient.SqlCommand("dci.webDonorStatistics", objConn);
objCmd.CommandTimeout = 950;
objCmd.CommandType = System.Data.CommandType.StoredProcedure;
objCmd.Parameters.Add(new
System.Data.SqlClient.SqlParameter("#FiscalYear", 2018));
GridView1.DataSource = objCmd.ExecuteReader();
GridView1.DataBind();
Here is the declaration of the SP:
ALTER PROCEDURE [dci].[webDonorStatistics] #FiscalYear INT
AS
BEGIN
--DECLARE #FiscalYear INT = 2018
DECLARE
#StartDate DATE = CONVERT(DATE, '01-OCT-' + CONVERT(CHAR(4), #FiscalYear - 1))
, #EndDate DATE = DATEADD(DAY, -1, GETDATE())
IF #EndDate >= CONVERT(DATE, '30-SEP-' + CONVERT(CHAR(4), #FiscalYear))
SELECT #EndDate = CONVERT(DATE, '30-SEP-' + CONVERT(CHAR(4), #FiscalYear))
ELSE
SELECT #EndDate = DATEADD(DAY, -1, CONVERT(DATE, '01-' + DATENAME(MONTH, GETDATE()) + '-' + CONVERT(CHAR(4), YEAR(GETDATE())))) -- End of previous month
IF DATEDIFF(DAY, #StartDate, #EndDate) < 0
SELECT #EndDate = GETDATE()
BEGIN TRY
DROP TABLE #webDonorStatistics
END TRY
BEGIN CATCH
END CATCH
Any help would be greatly appreciated. Thanks in advance.
First step is to isolate your error. Is your error thrown from your application code or database code?
If you follow 3Dave's suggestion, what do you get? Assuming you are pointed to the correct database server. Try running:
EXEC [dci].[webDonorStatistics] 2018
If the above call does not return any error, I would check the application code.
Your Error indicates that the data which you are trying to insert into the table is not valid, You would have to right-click on the stored procedure and click on execute stored procedure where you can insert the parameter for the fiscal year, The execution should fail. Then create a copy of same stored procedure with a different name and change the data type for the fiscal year and see if that would fix the issue and give you the result when you execute the stored procedure. Also on the Stored Proc could which you have I dont see any insert commands if there are any try checking the data type of what you are trying to insert and the data type of what is present inside the table schema if that doesn't match then you can change accordingly .

Displaying Column Headers As Dates Telerik Rad Grid

Normally I would have code to post. However, I'm not sure where to start on this one. Maybe I am incorrect but this request is a little different than most (from clients). So, they are needing a new feature added to their page. They want to be able to run a report which shows all employees total hours for a given set of weeks. They will use a DatePicker to select a start date and another to select and end date. Then, click a button to run the report. This report will have the employee name as the first column and then each column after that will have a header which is a date. So if they selected 8-5-2017 and 8-19-2017 the column headers will be 8-5-2017| 8-12-2017| 8-19-2017. Underneath those columns will be the total hours each employee worked for that given week.
I've attached an image of what I am needing to do. Hopefully this will provide additional clarification.
I've had a similar situation and managed to solve it by using a DataTable that contained my data. A simple way to fill your DataTable would be by creating a stored procedure.
In my example I'll simply do it for every day between 2 given dates, you should be able to change this code to have it work for once every 7 days, starting on a monday/sunday, depending on what your requirement is. If you need help with that as well, just leave a comment and I'll see what I can do if I find some time.
CREATE TYPE [dbo].[DayTableType] AS TABLE(
[Datum] [date] NOT NULL,
[DayCol] [int] NOT NULL
)
GO
CREATE PROCEDURE [dbo].[MyStoredProcedure]
-- Add the parameters for the stored procedure here
#d1 datetime, #d2 datetime
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
SET DATEFIRST 1;
-- Insert statements for procedure here
DECLARE #StartDate date = CONVERT(date, #d1);
DECLARE #EndDate date = CONVERT(date, #d2);
DECLARE #Days dbo.DayTableType;
WITH cte AS (
SELECT #StartDate AS Datum
UNION ALL
SELECT DATEADD(day,1,Datum) as Datum
FROM cte
WHERE DATEADD(day,1,Datum) <= #EndDate
)
INSERT INTO #Days
SELECT cte.Datum, DATEPART(DAY, cte.Datum)
FROM cte
OPTION(MAXRECURSION 0);
DECLARE #dPivot NVARCHAR(MAX)
SELECT #dPivot = ''
SELECT #dPivot = #dPivot + '[' + CONVERT(VARCHAR(8),d.Datum,3) + '],' FROM #Days d
SELECT #dPivot = SUBSTRING(#dPivot,1,LEN(#dPivot)-1)
DECLARE #SQLSTR NVARCHAR(MAX);
SET #SQLSTR =
'SELECT p.EmployeeId
,p.LastName
,p.FirstName
,'+ #dPivot + '
FROM (SELECT CONVERT(VARCHAR(8),d.Datum,3) AS DayCol
,e.EmployeeId
,e.LastName
,e.FirstName
,ISNULL((SELECT SUM(w.WorkedHours) FROM dbo.[EmployeeWorkDateTable] w
WHERE w.EmployeeId = e.EmployeeId AND CONVERT(DATE, w.WorkDate) = CONVERT(DATE, d.Datum)),0) AS DayInfo
FROM #Days d
LEFT OUTER JOIN dbo.[EmployeeTable] e ON e.IsActive = 1
) t
PIVOT (
MAX(t.DayInfo)
FOR t.DayCol IN (' + #dPivot + ')
) AS p
ORDER BY p.LastName'
EXECUTE SP_EXECUTESQL #SQLSTR, N'#Days DayTableType READONLY, #StartDate DATE, #EndDate DATE', #Days, #StartDate, #EndDate
END
This should return a DataTable that looks a lot like what you've posted in your screenshot.
To have this display correctly into your GridView you have need to first get this in your ViewModel as followed:
private DataTable _myDataTable;
public DataTable MyDataTable
{
get { return _myDataTable; }
set { SetProperty(ref _myDataTable, value); }
}
public void FillMyDataTable(DateTime startDate, DateTime endDate)
{
using (var conn = new SqlConnection("MyConnectionString"))
using (var cmd = new SqlCommand("MyStoredProcedure", conn) { CommandType = System.Data.CommandType.StoredProcedure })
{
cmd.Parameters.AddWithValue("#d1", startDate);
cmd.Parameters.AddWithValue("#d2", endDate);
var da = new SqlDataAdapter(cmd);
var ds = new DataSet();
da.Fill(ds);
MyDataTable = ds.Tables[0];
}
}
Now you should simply bind your GridView itemsource to the DefaultView property of your DataTable and have the AutoGenerateColumns="True", you can edit the column names and other stuff even more by writing your custom emplementation of AutoGeneratingColumn
<telerik:RadGridView x:Name="MyGridView"
AutoGenerateColumns="True"
ItemsSource="{Binding MyDataTable.DefaultView}"
AutoGeneratingColumn="MyGridView_OnAutoGeneratingColumn">
</telerik:RadGridView>
I hope this helps you out with your problem. Feel free to leave a comment if you have any more questions.

Categories

Resources