SCOPE_IDENTITY returning wrong ID - c#

I'm attempting to return the ID of the newly created row. I've tried doing it with SCOPE_IDENTITY, but it returns a 3. I've searched around and can't determine what I'm doing incorrect.
Here is the code:
<asp:SqlDataSource ID="sourceRecruit" runat="server"
ProviderName="System.Data.SqlClient"
ConnectionString="<%$ ConnectionStrings:DBCS %>"
SelectCommand="SELECT * FROM [Players] WHERE ([ID] = #ID)"
UpdateCommand="UPDATE [Players] SET [FirstName] = #FirstName, [LastName]=#LastName, [Height]=#Height, [Weight]=#Weight, [FortyYardDash] = #FortyYardDash, [CombineVerified] = #CombineVerified, [HomeNumber] = #HomeNumber, [CellNumber] = #CellNumber, [Email] = #Email, [Position] = #Position, [Commitment] = #Commitment, [GraduationYear] = #GraduationYear, [LastUpdate] = #LastUpdate, [NetworkUpdate] = #NetworkUpdate, [DecisionDate] = #DecisionDate, [MiscContact] = #MiscContact, [RivalsID] = #RivalsID, [ScoutID] = #ScoutID, [ESPNID] = #ESPNID, [t247SportsID] = #t247SportsID, [PictureID] = #PictureID, [StarRating] = #StarRating, [NationalHot100Rank] = #NationalHot100Rank, [PositionRank] = #PositionRank, [JanuaryEnrollee] = #JanuaryEnrollee, [Recruiter] = #Recruiter, [RecruitedPosition] = #RecruitedPosition, [SummerCamp] = #SummerCamp, [JuniorDay] = #JuniorDay, [SpringGame] = #SpringGame, [UnofficialVisit] = #UnofficialVisit, [FootballGame] = #FootballGame, [OfficialVisitDate] = #OfficialVisitDate, [Status] = #Status, [Updates] = #Updates, [Favorites] = #Favorites, [Visits] = #Visits, [Odds] = #Odds WHERE [ID] = #ID"
InsertCommand="INSERT INTO Players ([FirstName], [LastName], [Height], [Weight], [FortyYardDash], [CombineVerified], [HomeNumber], [CellNumber], [Email], [Position], [Commitment], [GraduationYear], [LastUpdate], [NetworkUpdate], [DecisionDate], [MiscContact], [RivalsID], [ScoutID], [ESPNID], [t247SportsID], [PictureID], [StarRating], [NationalHot100Rank], [PositionRank], [JanuaryEnrollee], [Recruiter], [RecruitedPosition], [SummerCamp], [JuniorDay], [SpringGame], [UnofficialVisit], [FootballGame], [OfficialVisitDate], [Status], [Updates], [Favorites], [Visits], [Odds]) VALUES (#FirstName, #LastName, #Height, #Weight, #FortyYardDash, #CombineVerified, #HomeNumber, #CellNumber, #Email, #Position, #Commitment, #GraduationYear, #LastUpdate, #NetworkUpdate, #DecisionDate, #MiscContact, #RivalsID, #ScoutID, #ESPNID, #t247SportsID, #PictureID, #StarRating, #NationalHot100Rank, #PositionRank, #JanuaryEnrollee, #Recruiter, #RecruitedPosition, #SummerCamp, #JuniorDay, #SpringGame, #UnofficialVisit, #FootballGame, #OfficialVisitDate, #Status, #Updates, #Favorites, #Visits, #Odds); SET #ID=SCOPE_IDENTITY()"
OnInserted="reloadPage">
<SelectParameters>
<asp:QueryStringParameter QueryStringField="ID" Name="ID" Type="Int32" />
</SelectParameters>
<UpdateParameters>
<asp:Parameter Name="DecisionDate" ConvertEmptyStringToNull="true" />
<asp:Parameter Name="NetworkUpdate" ConvertEmptyStringToNull="true" />
<asp:Parameter Name="OfficialVisitDate" ConvertEmptyStringToNull="true" />
<asp:Parameter Name="LastUpdate" ConvertEmptyStringToNull="true" />
</UpdateParameters>
<InsertParameters>
<asp:Parameter Name="ID" DefaultValue="Int32" Direction="Output" />
<asp:Parameter Name="DecisionDate" ConvertEmptyStringToNull="true" />
<asp:Parameter Name="NetworkUpdate" ConvertEmptyStringToNull="true" />
<asp:Parameter Name="OfficialVisitDate" ConvertEmptyStringToNull="true" />
<asp:Parameter Name="LastUpdate" ConvertEmptyStringToNull="true" />
</InsertParameters>
</asp:SqlDataSource>
Here is my code behind:
protected void reloadPage(object sender, SqlDataSourceStatusEventArgs e)
{
object newid = e.Command.Parameters["#ID"].Value;
lblResults.Text = "Test "+Convert.ToString(newid);
}
Like I've mentioned, every time I've ran the code, lblResults displays a "3," but the ID is in the 3000 range.

You need to use the OnInserted event, and specify the output direction of the parameter:
<asp:Parameter Direction="Output" Name="ID" Type="Int32" />
Code-behind:
protected void SqlDataSource1_Inserted(object sender, SqlDataSourceStatusEventArgs e)
{
int id = Convert.ToInt32(e.Command.Parameter["#ID"].Value);
}
I also noticed that you set DefaultValue="Int32". You should change that to Type="Int32".
If you still have problems after applying the above changes, try changing SET #ID = SCOPE_IDENTITY to SELECT #ID = SCOPE_IDENTITY. Shouldn't make a difference, but if all else fails...

Did you try
SELECT #ID = SCOPE_IDENTITY()
instead of
SET #ID = SCOPE_IDENTITY()
that is what I have and works perfect.

Related

Parameterized Query OR Control

I want to be able to use a QueryString parameter with a control parameter in an OR Clause on the ASPX page.
The below works for QueryString Parameter
Select * From Data1
WHERE ([Customer Name] = #C)
AND ([Order Number] = #O)
AND ('AD\' + Salesperson_AD_User_ID = #U)
AND ([Warehouse Id] = #W)
AND ([Use Description] is NOT NULL)
<SelectParameters>
<asp:querystringparameter QueryStringField="C" Name="C" />
<asp:querystringparameter QueryStringField="O" Name="O" />
<asp:querystringparameter QueryStringField="U" Name="U" />
<asp:querystringparameter QueryStringField="W" Name="W" />
</SelectParameters>
Below does not work
select * From Data1
WHERE ([Customer Name] = #Customer_Name OR [Customer Name] = #C)
AND ([Order Number] = #Order_Number OR [Order Number] = #O)
AND ('AD\' + Salesperson_AD_User_ID = #username OR'AD\' + Salesperson_AD_User_ID = #U)
AND ([Warehouse Id] = #Warehouse_Id OR [Warehouse Id] = #W)
AND ([Use Description] IS NOT NULL)
The full name is the control parameter (textbox, dropdown, etc.)
(#Customer_Name, #Order_Number, #username, #Warehouse_Id)
and the letter is the Querystring
(#C,#O,#W, #U)
<SelectParameters>
<asp:controlparameter ControlID="DropDownListCustomer" PropertyName="SelectedValue" Name="Customer_Name" />
<asp:querystringparameter QueryStringField="C" Name="C" />
<asp:controlparameter ControlID="DropDownListContract" PropertyName="SelectedValue" Name="Order_Number" />
<asp:querystringparameter QueryStringField="O" Name="O" />
<asp:controlparameter ControlID="UserID" PropertyName="Text" Name="username" />
<asp:querystringparameter QueryStringField="U" Name="U" />
<asp:controlparameter ControlID="DropDownListLocation" PropertyName="SelectedValue" Name="Warehouse_Id" />
<asp:querystringparameter QueryStringField="W" Name="W" />
</SelectParameters>
How can I add An OR Clause to default to the control if the QueryString is not provided or if the QueryString contains a value use it?

Getting QueryStringParameter value for InsertParameter in C# codebehind

I am dealing with a gridview in an ASP.NET Web Form that is using a QueryStringParameter as its Select Parameter. As I am having to do the Insert for the GridView in code-behind, I am trying to find an example of how I get the value of the QueryStringParameter for my SQLDataSource.InsertParameters.Add() chunk and I am coming up blank.
SQL DataSource:
<asp:SqlDataSource ID="gvProjectTaskSQL" runat="server" ConnectionString="<%$ ConnectionStrings:SQLConnectionString %>"
SelectCommand="SELECT tt.TaskID,
tt.EmployeeID,
tt.ProjectID,
tt.ReleaseID,
tt.TaskStatusID,
tt.TaskPriorityID,
tt.DueDate,
tt.Notes,
tt.CompDate,
p.ProjectName,
tc.TaskCodeAbbr
FROM tblTaskTracker tt INNER JOIN
tblProject p ON tt.ProjectID = p.ProjectID INNER JOIN
tblTaskCode tc ON tt.TaskCodeID = tc.TaskCodeID INNER JOIN
tblTaskStatus ts on tt.TaskStatusID = ts.TaskStatusID
WHERE tt.ProjectID = #ProjectID AND ts.TaskStatusType <> 'Z'
ORDER BY ts.TaskStatusType, tt.TaskPriorityID, tt.DueDate"
InsertCommand="INSERT INTO [tblTaskTracker]
([EmployeeID], [ProjectID], [ReleaseID], [TaskCodeID], [TaskStatusID], [TaskPriorityID], [DueDate], [Notes], [CompDate])
VALUES (#EmployeeID, #ProjectID, #ReleaseID, #TaskCodeID, #TaskStatusID, #TaskPriorityID, #DueDate, #Notes, #CompDate)"
UpdateCommand="UPDATE [tblTaskTracker] SET [EmployeeID] = #EmployeeID, [TaskStatusID] = #TaskStatusID, [TaskPriorityID] = #TaskPriorityID,
[DueDate] = #DueDate, [Notes] = #Notes, [CompDate] = #CompDate WHERE [TaskID] = #TaskID"
DeleteCommand="DELETE FROM [tblTaskTracker] WHERE [TaskID] = #TaskID">
<SelectParameters>
<asp:QueryStringParameter Name="ProjectID" Type="Int32" QueryStringField="PID" />
</SelectParameters>
<InsertParameters>
<asp:Parameter Name="EmployeeID" Type="Int32" />
<asp:Parameter Name="ProjectID" Type="Int32" />
<asp:Parameter Name="ReleaseID" Type="Int32" />
<asp:Parameter Name="TaskCodeID" Type="Int32" />
<asp:Parameter Name="TaskStatusID" Type="Int32" />
<asp:Parameter Name="TaskPriorityID" Type="Int32" />
<asp:Parameter Name="DueDate" Type="DateTime" />
<asp:Parameter Name="Notes" Type="String" />
<asp:Parameter Name="CompDate" Type="DateTime" />
</InsertParameters>
<UpdateParameters>
<asp:Parameter Name="EmployeeID" Type="Int32" />
<asp:Parameter Name="TaskID" Type="Int32" />
<asp:Parameter Name="TaskStatusID" Type="Int32" />
<asp:Parameter Name="TaskPriorityID" Type="Int32" />
<asp:Parameter Name="DueDate" Type="DateTime" />
<asp:Parameter Name="Notes" Type="String" />
<asp:Parameter Name="CompDate" Type="DateTime" />
</UpdateParameters>
<DeleteParameters>
<asp:Parameter Name="TaskID" Type="Int32" />
</DeleteParameters>
</asp:SqlDataSource>
Codebehind for OnRowCommand:
protected void gvProjectTask_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "FooterInsert" && Page.IsValid)
{
GridView gv = (GridView)MultiView1.Views[10].FindControl("gvProjectTask");
GridViewRow gvr = (GridViewRow)gv.FooterRow;
if (gvr == null) { return; }
// Get Controls
DropDownList ddlEmployee = gvr.FindControl("ddlNewEmployee") as DropDownList;
TextBox txtReleaseID = gvr.FindControl("txtNewReleaseID") as TextBox;
DropDownList ddlTaskCode = gvr.FindControl("ddlNewTaskCode") as DropDownList;
DropDownList ddlStatus = gvr.FindControl("ddlNewStatus") as DropDownList;
DropDownList ddlPriority = gvr.FindControl("ddlNewPriority") as DropDownList;
TextBox txtDueDate = gvr.FindControl("txtNewDueDate") as TextBox;
TextBox txtNotes = gvr.FindControl("txtNewNotes") as TextBox;
TextBox txtCompDate = gvr.FindControl("txtNewCompDate") as TextBox;
// Test for nulls
if (string.IsNullOrWhiteSpace(txtDueDate.Text))
{
// Throw error message
ClientScript.RegisterStartupScript(GetType(), "error", "alert('Enter Due Date.');", true);
}
else
{
// Initialize Insert Parameters
gvProjectTaskSQL.InsertParameters.Clear();
gvProjectTaskSQL.InsertParameters.Add("EmployeeID", ddlEmployee.SelectedValue);
// gvProjectTaskSQL.InsertParameters.Add("ProjectID", gvProjectTaskSQL.SelectParameters.ToString());
gvProjectTaskSQL.InsertParameters.Add("ReleaseID", txtReleaseID.Text);
gvProjectTaskSQL.InsertParameters.Add("TaskCodeID", ddlTaskCode.SelectedValue);
gvProjectTaskSQL.InsertParameters.Add("TaskStatusID", ddlStatus.SelectedValue);
gvProjectTaskSQL.InsertParameters.Add("TaskPriorityID", ddlPriority.SelectedValue);
gvProjectTaskSQL.InsertParameters.Add("DueDate", txtDueDate.Text);
gvProjectTaskSQL.InsertParameters.Add("Notes", txtNotes.Text);
gvProjectTaskSQL.InsertParameters.Add("CompDate", txtCompDate.Text);
gvProjectTaskSQL.Insert();
}
} // end FooterInsert
if (e.CommandName == "EmptyInsert" && Page.IsValid)
{
GridView gv = (GridView)MultiView1.Views[10].FindControl("gvProjectTask");
GridViewRow gvr = (GridViewRow)gv.Controls[0].Controls[0];
if (gvr == null) { return; }
// Get Controls
DropDownList ddlEmployee = (DropDownList)gvr.FindControl("ddlEmptyEmployee");
TextBox txtReleaseID = (TextBox)gvr.FindControl("txtEmptyReleaseID");
DropDownList ddlTaskCode = (DropDownList)gvr.FindControl("ddlEmptyTaskCode");
DropDownList ddlStatus = (DropDownList)gvr.FindControl("ddlEmptyStatus");
DropDownList ddlPriority = (DropDownList)gvr.FindControl("ddlEmptyPriority");
TextBox txtDueDate = (TextBox)gvr.FindControl("txtEmptyDueDate");
TextBox txtNotes = (TextBox)gvr.FindControl("txtEmptyNotes");
TextBox txtCompDate = (TextBox)gvr.FindControl("txtEmptyCompDate");
// Test for nulls
if (string.IsNullOrWhiteSpace(txtDueDate.Text))
{
// Throw error message
ClientScript.RegisterStartupScript(GetType(), "error", "alert('Enter Due Date.');", true);
}
else
{
// Initialize Insert Parameters
gvProjectTaskSQL.InsertParameters.Clear();
gvProjectTaskSQL.InsertParameters.Add("EmployeeID", ddlEmployee.SelectedValue);
// gvProjectTaskSQL.InsertParameters.Add("ProjectID", gvProjectTaskSQL.SelectParameters.ToString());
gvProjectTaskSQL.InsertParameters.Add("ReleaseID", txtReleaseID.Text);
gvProjectTaskSQL.InsertParameters.Add("TaskCodeID", ddlTaskCode.SelectedValue);
gvProjectTaskSQL.InsertParameters.Add("TaskStatusID", ddlStatus.SelectedValue);
gvProjectTaskSQL.InsertParameters.Add("TaskPriorityID", ddlPriority.SelectedValue);
gvProjectTaskSQL.InsertParameters.Add("DueDate", txtDueDate.Text);
gvProjectTaskSQL.InsertParameters.Add("Notes", txtNotes.Text);
gvProjectTaskSQL.InsertParameters.Add("CompDate", txtCompDate.Text);
gvProjectTaskSQL.Insert();
}
} // end EmptyInsert
} // end gvTask_Command
I've commented out the InsertParameter for the ProjectID as I am sure it's incorrect. I just can't find any examples of how to pass a QueryString value to an InsertParameter.
Just add this code to you OnRowCommand event to get the query string value:
string projectID = Request.QueryString["PID"];

Getting Date only instead of date and time

Ok so i have sorted the difference of Dates, it's working great. The problem i am facing now is that when i click on date from the Calender (AJAX calender that appears when you click on TextBox) It adds Date along with the null time to database. I only want Date not Time.
Please note: that the DataType of AdmitDate and DischargeDate is set to datetime.
Here is my C# code:
string str = "update Patient set Department= #Department,Ward=#Ward,Bed=#Bed,Status=#Status,AdmitDate=#AdmitDate,DischargeDate=#DischargeDate, NumOfDays=#NumOfDays where PID = '" + TextBox3.Text + "'";
cmd = new SqlCommand(str, con);
con.Open();
cmd.Parameters.AddWithValue("#Department", DropDownList4.SelectedItem.Text);
cmd.Parameters.AddWithValue("#Ward", DropDownList3.SelectedItem.Text);
cmd.Parameters.AddWithValue("#Bed", DropDownList1.SelectedItem.Text);
cmd.Parameters.AddWithValue("#Status", DropDownList2.SelectedItem.Text);
cmd.Parameters.AddWithValue("#AdmitDate", TextBox1.Text);
DateTime AdmitDate = DateTime.Parse(TextBox1.Text);
// AdmitDate.ToString("d");
AdmitDate.ToShortDateString();
cmd.Parameters.AddWithValue("#DischargeDate", TextBox2.Text);
DateTime DischargeDate = DateTime.Parse(TextBox2.Text);
// DischargeDate.ToString("d");
DischargeDate.ToShortDateString();
var diff = (DischargeDate - AdmitDate).Days;
cmd.Parameters.AddWithValue("#NumOfDays", diff);
cmd.ExecuteNonQuery();
con.Close();
As you can see i tried 2 methods, they don't give any error but don't work the way they are supposed to. I tried some other things as well (mentioned here and on other sites) but they didn't work either. Any kind of help will be appreciated.
Additional Info: I am using SQL server 2008 R2 with VS2013.
EDIT: here is my SQL table structure:
CREATE TABLE [dbo].[Patient] (
[PID] INT IDENTITY (1, 1) NOT NULL,
[Department] NVARCHAR (50) NULL,
[Ward] NVARCHAR (50) NULL,
[Bed] NVARCHAR (50) NULL,
[Status] NVARCHAR (50) NULL,
[AdmitDate] DATETIME NULL,
[DischargeDate] DATETIME NULL,
[NumOfDays] INT NULL,
CONSTRAINT [PK__Patient__C57755200BC6C43E] PRIMARY KEY CLUSTERED ([PID] ASC)
i have removed the fields that are not relevant.
EDIT: my gridview code:
<div id="mbody"> <br />
<div class="gview">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1" HeaderStyle-HorizontalAlign="Center" FooterStyle-HorizontalAlign="Center" CssClass="gview" DataKeyNames="PID" Width="613px">
<Columns>
<asp:CommandField ShowDeleteButton="True" />
<asp:BoundField DataField="PID" HeaderText="PID" SortExpression="PID" InsertVisible="False" ReadOnly="True" />
<asp:BoundField DataField="Pname" HeaderText="Pname" SortExpression="Pname" />
<asp:BoundField DataField="Gender" HeaderText="Gender" SortExpression="Gender" />
<asp:BoundField DataField="Department" HeaderText="Department" SortExpression="Department" />
<asp:BoundField DataField="Ward" HeaderText="Ward" SortExpression="Ward" />
<asp:BoundField DataField="Bed" HeaderText="Bed" SortExpression="Bed" />
<asp:BoundField DataField="Status" HeaderText="Status" SortExpression="Status" />
<asp:BoundField DataField="AdmitDate" HeaderText="AdmitDate" SortExpression="AdmitDate" />
<asp:BoundField DataField="DischargeDate" HeaderText="DischargeDate" SortExpression="DischargeDate" />
<asp:BoundField DataField="NumOfDays" HeaderText="NumOfDays" SortExpression="NumOfDays" />
</Columns>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:SMCConnectionString %>" SelectCommand="SELECT [PID], [Pname], [Gender], [Department], [Ward], [Bed], [Status], [AdmitDate], [DischargeDate], [NumOfDays] FROM [Patient]" DeleteCommand="DELETE FROM [Patient] WHERE [PID] = #PID" InsertCommand="INSERT INTO [Patient] ([Pname], [Gender], [Department], [Ward], [Bed], [Status], [AdmitDate], [DischargeDate], [NumOfDays]) VALUES (#Pname, #Gender, #Department, #Ward, #Bed, #Status, #AdmitDate, #DischargeDate, #NumOfDays)" UpdateCommand="UPDATE [Patient] SET [Pname] = #Pname, [Gender] = #Gender, [Department] = #Department, [Ward] = #Ward, [Bed] = #Bed, [Status] = #Status, [AdmitDate] = #AdmitDate, [DischargeDate] = #DischargeDate, [NumOfDays] = #NumOfDays WHERE [PID] = #PID">
<DeleteParameters>
<asp:Parameter Name="PID" Type="Int32" />
</DeleteParameters>
<InsertParameters>
<asp:Parameter Name="Pname" Type="String" />
<asp:Parameter Name="Gender" Type="String" />
<asp:Parameter Name="Department" Type="String" />
<asp:Parameter Name="Ward" Type="String" />
<asp:Parameter Name="Bed" Type="String" />
<asp:Parameter Name="Status" Type="String" />
<asp:Parameter Name="AdmitDate" Type="DateTime" />
<asp:Parameter Name="DischargeDate" Type="DateTime" />
<asp:Parameter Name="NumOfDays" Type="Int32" />
</InsertParameters>
<UpdateParameters>
<asp:Parameter Name="Pname" Type="String" />
<asp:Parameter Name="Gender" Type="String" />
<asp:Parameter Name="Department" Type="String" />
<asp:Parameter Name="Ward" Type="String" />
<asp:Parameter Name="Bed" Type="String" />
<asp:Parameter Name="Status" Type="String" />
<asp:Parameter Name="AdmitDate" Type="DateTime" />
<asp:Parameter Name="DischargeDate" Type="DateTime" />
<asp:Parameter Name="NumOfDays" Type="Int32" />
<asp:Parameter Name="PID" Type="Int32" />
</UpdateParameters>
</asp:SqlDataSource>
</div>
From what I understand you want to save up the only date part of the datetime you can do that as below:
DateTime AdmitDate = DateTime.Parse(TextBox1.Text);
cmd.Parameters.AddWithValue("#AdmitDate", AdmitDate.ToShortDateString());
DateTime DischargeDate = DateTime.Parse(TextBox2.Text);
cmd.Parameters.AddWithValue("#DischargeDate", DischargeDate.ToShortDateString());
In your code you are not assigning the ToShortDateString() value to anything that's why the changes aren't reflecting.
And you might want to change your query to use it parametrized values to avoid SQL injection. Here is more info on it
string str = "update Patient set Department = #Department, Ward = #Ward, Bed = #Bed, Status = #Status, AdmitDate = #AdmitDate, DischargeDate = #DischargeDate, NumOfDays = #NumOfDays where PID = #PID";
cmd.Parameters.AddWithValue("#PID", TextBox3.Text);
UPDATE
As from your comments it is clear that the date you are showing up in the UI is showing time because you need to make sure that the value is converted to to only date before setting it to the UI control.
OR
If you have full control of the tables and you never ever want to store time then the ultimate solution would be Change the DateTime to the Date.
In this case to when you fetch it and if you store it in the DateTime type variable it will add the Time part to it. So you have to apply the .ToShortDateString() before assigning it to the UI control.
UPDATE
TO change the UI you need to put the DataformatString property of the boundfield of the date columns. In your gridview for these 2 lines add the DataformatString property with the value {0:MM/dd/yyyy}
<asp:BoundField DataField="AdmitDate" HeaderText="AdmitDate" SortExpression="AdmitDate" DataFormatString="{0:MM/dd/yyyy}"/>
<asp:BoundField DataField="DischargeDate" HeaderText="DischargeDate" SortExpression="DischargeDate" DataFormatString="{0:MM/dd/yyyy}"/>
If you want only date part to be stored in DB then use datatype of column as date.
For example -
DECLARE #date1 date= '02-24-15 23:20:51'; -- will take only the date
SELECT #date1 AS 'date1'
Will have -
date1
--------------
2015-02-24
EDIT-
From your edition and of table structure I ran simple test and it is working fine.
CREATE TABLE #Patient (
[PID] INT IDENTITY (1, 1) NOT NULL,
[Department] NVARCHAR (50) NULL,
[Ward] NVARCHAR (50) NULL,
[Bed] NVARCHAR (50) NULL,
[Status] NVARCHAR (50) NULL,
[AdmitDate] Date NULL,
[DischargeDate] Date NULL,
[NumOfDays] INT NULL
);
Insert into #Patient Values('ABC','Ward1','Bed2','Active','02-24-15 23:20:51','02-26-15 23:20:51',2);
Select * from #Patient;
Results-
PID Department Ward Bed Status AdmitDate DischargeDate NumOfDays
----------- -------------------------------------------------- -------------------------------------------------- -------------------------------------------------- -------------------------------------------------- ---------- ------------- -----------
1 ABC Ward1 Bed2 Active 2015-02-24 2015-02-26 2
If you check I modified datetime data type to date
[AdmitDate] Date NULL,
[DischargeDate] Date NULL,
Accordimg to :
the DataType of AdmitDate and DischargeDate is set to datetime.
you can't insert only date-part to these column.if you tried then it'll automatically save the time as a 12:00 AM(starting time of the day).
if you really want to insert only date then change the column datatype to date.
ALTER TABLE table_name
ALTER COLUMN column_name datatype
See:Alter_Table_datatype
DateTime AdmitDate = DateTime.Parse(TextBox1.Text);
string admitDate = AdmitDate.Date; // it gives you only Date
If you want only Date in SQL SERVER means you need to change the datatype of the column from datetime to date.

SQL Datasource Nulling Update Parameter values?

I have a data source that has the update statement:
UpdateCommand="Update Apps Set AppDate = Convert(Datetime,#AppDate,103), Slot = #Slot,
Duration = #Duration, TPMId = #TPMId, AppTypeId = #AppTypeId,
AppStatusId = #AppStatusId, Location = #Location,
OtherLocation = #OtherLocation, Comments = #Comments
where AppId = #AppId;
update Profile Set PrimaryContact = #PrimaryContact,
ContactTel = #ContactTel, ContactMob = #ContactMob,
ContactEmail = #ContactEmail where CompanyID = #CompanyID"
and my update parameters are set as such:
<UpdateParameters>
<asp:Parameter Name="AppDate" />
<asp:Parameter Name="Slot" />
<asp:ControlParameter Name="Duration" ControlID="HFDuration" />
<asp:Parameter Name="TPMId" />
<asp:Parameter Name="AppTypeId" />
<asp:Parameter Name="AppStatusId" />
<asp:Parameter Name="Location" />
<asp:Parameter Name="OtherLocation" />
<asp:Parameter Name="Comments" />
<asp:QueryStringParameter Name="AppId" QueryStringField="AppID" />
<asp:Parameter Name="PrimaryContact" />
<asp:Parameter Name="ContactTel" />
<asp:Parameter Name="ContactMob" />
<asp:Parameter Name="ContactEmail" />
<asp:QueryStringParameter Name="CompanyID" QueryStringField="CompanyID" />
</UpdateParameters>
I have all the controls on the form view set for two way binding and are sitting with bind and not eval eg (<
asp:TextBox ID="LocationTB" runat="server" Text='<%# Bind("Location") %>'
TextMode="MultiLine"></asp:TextBox>
)
yet when it comes to running the update query the only values that actually get pulled through are the query string and control parameters the rest of the fields all get a null value.
I have had multiple form views with more than one update query before so I know this is not likely to be the issue.
Anyone have any suggestions as to why my datasource update is leaving my table full of nulls?

Get ID in insert command asp and use it in code behind c#

I have a listview
<asp:ListView ID="ListViewNews" runat="server" DataSourceID="SqlDataSourceAddNews" DataKeyNames="Id" InsertItemPosition="LastItem" OnItemCommand="ListViewNews_ItemCommand">
<InsertItemTemplate>
<asp:FileUpload ID="FileUpload2" runat="server" />
</InsertItemTemplate>
and the sqldatasource:
<asp:SqlDataSource runat="server" ID="SqlDataSourceAddNews"
ConnectionString='<%$ ConnectionStrings:ConnectionStringSchool %>'
DeleteCommand="DELETE FROM [News] WHERE [Id] = #Id"
InsertCommand="INSERT INTO News(TITLE, SUMMARY, TEXT, DATETIME, PHOTO, [FILE])
VALUES (#TITLE, #SUMMARY, #TEXT, #DATETIME, #PHOTO, #FILE)"
SelectCommand="SELECT * FROM [News] ORDER BY DATETIME DESC">
<DeleteParameters>
<asp:Parameter Name="Id" Type="Int32"></asp:Parameter>
</DeleteParameters>
<InsertParameters>
<asp:Parameter Name="TITLE" Type="String"></asp:Parameter>
<asp:Parameter Name="SUMMARY" Type="String"></asp:Parameter>
<asp:Parameter Name="TEXT" Type="String"></asp:Parameter>
<asp:Parameter Name="DATETIME" Type="DateTime"></asp:Parameter>
<asp:Parameter Name="PHOTO" Type="String"></asp:Parameter>
<asp:Parameter Name="FILE" Type="String"></asp:Parameter>
</InsertParameters>
</asp:SqlDataSource>
I want to get the id of insert command to name the uploaded photo
protected void ListViewNews_ItemCommand(object sender, ListViewCommandEventArgs e)
{
if (e.CommandName == "Insert")
{
string strID= ....get id here....;
FileUpload fu2 = (FileUpload)ListViewNews.InsertItem.FindControl("FileUpload2");
if (fu2.HasFile)
{
string aut = strID + ".jpg";
fu2.SaveAs(Server.MapPath("~/images/NewsPhotos/" + aut));
}
}
}
Any idea for a simple solution how to get the id here?
Try this,
Change your insert command to:
InsertCommand="INSERT INTO News(TITLE, SUMMARY, TEXT, DATETIME, PHOTO, [FILE])
VALUES (#TITLE, #SUMMARY, #TEXT, #DATETIME, #PHOTO, #FILE);
SELECT #Id = SCOPE_IDENTITY();"
Add New Output Parameter to InsertParameters List
<asp:Paramter Direction="Output" Name="Id" Type="Int32" />
Move your file saving code to SQLDataSource Inserted method, you cannot access this generated id in ItemCommand Event directly
protected void SqlDataSourceAddNews_Inserted(object sender, EventArgs e)
{
string strId = e.Command>parameters("#Id").Value.ToString();
FileUpload fu2 = (FileUpload)ListViewNews.InsertItem.FindControl("FileUpload2");
if (fu2.HasFile)
{
string aut = strID + ".jpg";
fu2.SaveAs(Server.MapPath("~/images/NewsPhotos/" + aut));
}
}

Categories