Getting Date only instead of date and time - c#
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.
Related
Column data missing when i import data from .csv excel to grid view in Asp.net
I am trying to export my excel sheet data to my grid view in ASP.NET site. Grid view is populating the data but is missing the excel sheet column data EMP_CODE. Excel Data: Rendered GridView: ` Code for populating asp:GridView: protected void btnSave_Click(object sender, EventArgs e) { if (FileUpload1.FileName != "") { try { FileUpload1.SaveAs(Server.MapPath("~/Appraisal/" + FileUpload1.FileName)); CvsPath = null; string constr = null; //constr = System.Configuration.ConfigurationManager.ConnectionStrings("connStr").ToString; constr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; SqlConnection dwConn = new SqlConnection(constr); //con.Open() CvsPath = Server.MapPath("~/Appraisal/" + FileUpload1.FileName); //Response.Write(CvsPath) FileUpload1.Dispose(); // Dim constr As String System.Data.OleDb.OleDbConnection csvConn = new System.Data.OleDb.OleDbConnection(); //constr = System.Configuration.ConfigurationManager.ConnectionStrings("connStr").ToString //csvConn.ConnectionString = ("Provider=Microsoft.ACE.OLEDB.12.0;;Data Source=" + CvsPath + ";Extended Properties=\"Excel 8.0;HDR=YES;\""); csvConn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + CvsPath + ";Extended Properties=Excel 12.0;Persist Security Info=False"; // csvConn.Open(); System.Data.OleDb.OleDbCommand csvCmd = new System.Data.OleDb.OleDbCommand(); csvCmd.CommandText = ("Select * From [Sheet1$]"); //csv file being in localDir //assign the cmd to a connection csvCmd.Connection = csvConn; //create csv reader System.Data.OleDb.OleDbDataReader csvRdr = null; //insert the csv contents into a reader csvRdr = csvCmd.ExecuteReader(); //open sql connection dwConn.Open(); //create sqlbulk copy to insert the csv reader into db table SqlBulkCopy sqlBulk = new SqlBulkCopy(dwConn); sqlBulk.DestinationTableName = "[dbo].[MstAppointmentRegister]"; sqlBulk.WriteToServer(csvRdr); //close csv connection csvRdr.Close(); csvConn.Close(); //close sql connection dwConn.Close(); lblError.Visible = true; lblError.Text = "File Uploaded Successfully"; if (lblError.Text == "File Uploaded Successfully") { FillGridFromExcelSheet(); } } catch (Exception ex) { Response.Write("<br />" + ex.Message); } //Response.Redirect("upload_ClosingPrice.aspx?act=1"); } else { lblError.Visible = true; lblError.Text = "Please Select File"; } } GridView and SqlDataSource markup: <asp:GridView ID="ExcelGridView" runat="server" Cssclass="table table-striped" Visible="False" AutoGenerateColumns="False" DataKeyNames="SRID" OnPageIndexChanging="GridView1_PageIndexChanging" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowDeleting="GridView1_RowDeleting" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating"> <Columns> <asp:CommandField ShowEditButton="true" HeaderText="Modify" /> <asp:CommandField ShowDeleteButton="true" HeaderText="Remove" /> <asp:BoundField DataField="SRID" HeaderText="SRID" /> <asp:BoundField DataField="Emp_Code" HeaderText="Emp_Code" /> <asp:BoundField DataField="Letter" HeaderText="Letter" /> <asp:BoundField DataField="Letter" HeaderText="Letter" /> <asp:BoundField DataField="Name" HeaderText="Name" /> <asp:BoundField DataField="First_Name" HeaderText="First_Name" /> <asp:BoundField DataField="Address_Line1" HeaderText="Address_Line1" /> <asp:BoundField DataField="Address_Line2" HeaderText="Address_Line2" /> <asp:BoundField DataField="Address_Line3" HeaderText="Address_Line3" /> <asp:BoundField DataField="DOJ" HeaderText="DOJ" /> <asp:BoundField DataField="Designation" HeaderText="Designation" /> <asp:BoundField DataField="CTC" HeaderText="CTC" /> <asp:BoundField DataField="CTC_in_Words" HeaderText="CTC in Words" /> </Columns> </asp:GridView> <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="Data Source=103.21.58.193;Initial Catalog=jig_match_db;User ID=jig_match_db;Password=atheros#7412" DeleteCommand="DELETE FROM [MstAppointmentRegister] WHERE [SRID] = #SRID" SelectCommand="SELECT * FROM [MstAppointmentRegister]" UpdateCommand="UPDATE [MstAppointmentRegister] SET [Name] = #Name, [First_Name] = #First_Name, [Address_Line_1] = #Address_Line_1, [Address_Line_2] = #Address_Line_2, [Address_Line_3] = #Address_Line_3, [DOJ] = #DOJ, [Designation] = #Designation, [CTC] = #CTC, [CTC_in_Words] = #CTC_in_Word WHERE [SRID] = #SRID" InsertCommand="INSERT INTO [MstAppointmentRegister] ([Name],[First_Name],[Address_Line_1],[Address_Line_2],[Address_Line_3],[DOJ],[Designation],[CTC],[CTC_in_Words]) VALUES (#Name,#First_Name,#Address_Line_1,#Address_Line_2,#Address_Line_3,#DOJ,#Designation,#CTC,#CTC_in_Words)"> <DeleteParameters> <asp:Parameter Name="SRID" Type="Int64" /> </DeleteParameters> <UpdateParameters> <asp:Parameter Name="Emp_Code" Type="String" /> <asp:Parameter Name="Letter" Type="String" /> <asp:Parameter Name="Name" Type="String" /> <asp:Parameter Name="First_Name" Type="String" /> <asp:Parameter Name="Address_Line1" Type="String" /> <asp:Parameter Name="Address_Line2" Type="String" /> <asp:Parameter Name="Address_Line3" Type="String" /> <asp:Parameter Name="DOJ" Type="String" /> <asp:Parameter Name="Designation" Type="String" /> <asp:Parameter Name="CTC" Type="String" /> <asp:Parameter Name="CTC_in_Words" Type="String" /> </UpdateParameters> </asp:SqlDataSource> Database schema for the table MstAppointmentRegister: CREATE TABLE [dbo].[MstAppointmentRegister]( [SRID] [bigint] IDENTITY(1,1) NOT NULL, [EMP_Code] [varchar](150) NULL, [Letter][varchar](200) NULL, [Name] [varchar](150) NULL, [First_Name] [varchar](100) NULL, [Address_Line_1] [varchar](100) NULL, [Address_Line_2] [varchar](150) NULL, [Address_Line_3] [varchar](100) NULL, [DOJ] [varchar](100) NULL, [Designation] [varchar](150) NULL, [CTC] [varchar](150) NULL, [CTC_in_Words] [varchar](150) NULL, CONSTRAINT [PK_mstappointmentregister] PRIMARY KEY CLUSTERED ( [SRID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] Please help me out ?
In SqlBulkCopy the column mappings are case-sensitive regardless of the case sensitivity setting in target DB. As MSDN notes, Column mappings define the mapping between data source and the target table. If mappings are not defined—that is, the ColumnMappings collection is empty—the columns are mapped implicitly based on ordinal position. For this to work, source and target schemas must match. If they do not, an InvalidOperationException will be thrown. If the ColumnMappings collection is not empty, not every column present in the data source has to be specified. Those not mapped by the collection are ignored. In your case the excel returns the column Emp_Code and the table in the database has the column EMP_Code. The mapping fails as Emp_Code != EMP_Code. MSDN Link: SqlBulkCopyColumnMapping Class
Can I use the update statement with the select statement together in an SqlDataSource?
My query looks like this: <asp:SqlDataSource ID="UpdateFullNameSQL" runat="server" ConnectionString="<%$ ConnectionStrings:UserQueries %>" ProviderName="<%$ ConnectionStrings:UserQueries.ProviderName %>" UpdateCommand="update users set firstname = :changefirstname, lastname = :changelastname where username = :currentusername"> <UpdateParameters> <asp:ControlParameter ControlID="ChangeFirstNameBox" Name="changefirstname" PropertyName="Text" Type="Empty" /> <asp:ControlParameter ControlID="ChangeLastNameBox" Name="changelastname" PropertyName="Text" Type="Empty" /> </UpdateParameters> <SelectParameters> <asp:ControlParameter ControlID="UsernameBox" Name="currentusername" PropertyName="Text" Type="Empty" /> </SelectParameters> </asp:SqlDataSource> So I have two parameters that I want to update from and one parameter that I want to use to change the data where it matches withthe selectparameter's data. And when I want to execute it, it shows an ORA-01008 exception. My code-behind only has a updatefullnamesql.update(); function. What am I missing here/doing wrong?
In update command you should use # instead of :. I.E.: UpdateCommand="update users set firstname = #changefirstname, lastname = #changelastname where username = #currentusername;" Additionally you have to specify the #currentusername as update parameter <UpdateParameters> ... <asp:ControlParameter ControlID="UsernameBox" Name="currentusername" PropertyName="Text" Type="Empty" /> </UpdateParameters>
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)); } }
SCOPE_IDENTITY returning wrong ID
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.