i want the query to check database AdvID itself and delete when page is loaded. Why am i getting this error call "System.Data.SqlClient.SqlException: 'Procedure or function 'DeleteByDate' expects parameter '#AdvID', which was not supplied." Shouldnt it check the database itself and delete? why do i have to supply it with AdvID? Here is my page_load code
protected void Page_Load(object sender, EventArgs e)
{
//Generate auto ID
SqlDataAdapter sad = new SqlDataAdapter("Select isnull(max(cast(AdvID as int)),0)+1 from Advertisement", sqlCon);
DataTable dt = new DataTable();
sad.Fill(dt);
advertismentIdTb.Text = dt.Rows[0][0].ToString();
//PageLoadValidations
statusTb.Text = "1";
endDateTb.Attributes["min"] = DateTime.Now.ToString("yyyy-MM-dd");
btnDelete.Enabled = false;
btnUpdate.Enabled = false;
Image1.Visible = false;
//Delete from DB Condition (EndDate)
if (sqlCon.State == ConnectionState.Closed)
sqlCon.Open();
SqlCommand sqlCmd = new SqlCommand("DeleteByDate", sqlCon);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.ExecuteNonQuery();
sqlCon.Close();
//Show GridView
FillGridView();
}
And here is my script
ALTER PROC [dbo].[DeleteByDate]
#AdvID int
AS
BEGIN
DECLARE #CurrentDate DATE = GETDATE() -- to get current date
-- Assuming that Advertisement table has the column EndDate
IF EXISTS (SELECT * FROM Advertisement a WHERE a.EndDate < #CurrentDate )
BEGIN
UPDATE a SET a.Status = 0
FROM Advertisement a
WHERE a.AdvID = #AdvID
END
END
I think you are asking for a query which will delete all advertisements that ended earlier than right now? Your current query is checking if there are any advertisements that ended before right now then deleted the one with the ID you pass in.
Based on the above assumption, try the following query:
ALTER PROC [dbo].[DeleteByDate]
AS BEGIN
UPDATE a
SET a.Status = 0
FROM Advertisement a
WHERE a.EndDate < GETDATE()
END
Related
I need some help on how to achieved Inserting a foreign key value in MS SQL at the same time binding the result in gridview in the same aspx page.
I have my code which is works fine and no error upon Build Solution but it shows the following line error in the browser.
Line: 940 Error: Sys.WebForms.PageRequestManagerServerErrorException:
A field or property with the name 'TypeName' was not found on the
selected data source.
I'm using MS SQL 2008 & MS Visual Studio 2013
Below is my code in my project
ASPX Gridview:
<!-- Main Gridview -->
<asp:GridView ID="gvItemgrid" runat="server" AutoGenerateColumns="false" DataKeyNames="ItemID"
ShowHeader="false" CssClass="Grid">
<RowStyle Wrap="false" CssClass="row" />
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="imgbtn" ImageUrl="../images/Edit.jpg" runat="server" Width="12px" Height="12px" OnClick="imgbtn_Click" /></ItemTemplate>
</asp:TemplateField>
<asp:BoundField ItemStyle-Width="50px" DataField="ItemID" HeaderText="ItemID" />
<asp:BoundField ItemStyle-Width="500px" DataField="ItemName" HeaderText="ItemName" />
<asp:BoundField ItemStyle-Width="500px" DataField="TypeName" HeaderText="TypeName" />
</Columns>
</asp:GridView>
C# Code:
// C# Code
#region BindTypeList (ddlType)
// bind the Type list in drop down list..
private void BindTypeList(DropDownList ddlType)
{
SqlConnection con = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand("select * from inv_TypeList");
cmd.Connection = con;
con.Open();
this.ddlType.DataSource = cmd.ExecuteReader();
this.ddlType.DataTextField = "TypeName";
this.ddlType.DataValueField = "TypeID";
this.ddlType.DataBind();
con.Close();
}
#endregion
//button save
#region btnSave
protected void btnSave_Click(object sender, EventArgs e)
{
//Calling the database for Insert Statement
SqlConnection con = new SqlConnection(strConnString);
// call stored procedure
SqlCommand cmd = new SqlCommand("inv_ItemList_Insert", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
// add values
cmd.Parameters.AddWithValue("#ItemName", txtItemName.Text);
cmd.Parameters["#ItemName"].Value = txtItemName.Text;
cmd.Parameters.AddWithValue("#TypeID", ddlType.SelectedItem.Value);
cmd.Parameters["#TypeID"].Value = ddlType.SelectedItem.Value;
// add the result
cmd.Parameters.Add(new SqlParameter("#Result", SqlDbType.VarChar, 1000));
cmd.Parameters["#Result"].Direction = ParameterDirection.Output;
try
{
// open the database..
con.Open();
cmd.ExecuteNonQuery();
// perform some actions here..
//btnSave.Enabled = false;
string result = cmd.Parameters["#Result"].Value.ToString();
// label notification..
lblMsg.Visible = false;
lblMsg.Text = result;
BindGrid();
// if meets condition to perform some actions..
if ((lblMsg.Text == ("Item Name: " + (txtItemName.Text + (" " + "already exists..")))))
{
// controls set to active..
txtItemName.Enabled = true;
ddlType.Enabled = true;
//txtRegister.Text = DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss tt");
txtItemName.Focus();
// lblMsg notification display
lblMsg.Attributes.Add("style", "color: #FFFFFF");
lblMsg.Attributes.Add("style", "background-color: OrangeRed");
lblMsg.Visible = false;
btnNew.Enabled = false;
// javascript messagebox "IP Address exist!"
ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "msgExist", "msgExist();", true);
}
else
{
//Method in displaying data in reverse (last - first)
//Calling the database
SqlConnection con2 = new SqlConnection(strConnString);
string strConString = "select * from inv_ItemList order by ItemID DESC";
SqlCommand cmd2 = new SqlCommand(strConString);
gvItemgrid.DataSource = GetData(strConString);
gvItemgrid.DataBind();
//Highlighting the first row in gridview
object firstRowIndex = gvItemgrid.Rows[0];
gvItemgrid.Rows[0].BackColor = System.Drawing.Color.LemonChiffon;
//Display records
//current record per page
int val1 = Convert.ToInt32(gvItemgrid.Rows.Count.ToString());
int val2 = Convert.ToInt32(lblcurrentpage.Text.ToString());
int val3 = val1 * val2;
lblrecperpage.Text = Convert.ToString(val3);
//display page
lbltotalpage.Text = lblcurrentpage.Text;
//paging function disabled..
btnFirst.Enabled = false;
btnNext.Enabled = false;
btnPrevious.Enabled = false;
btnLast.Enabled = false;
//controls set to disabled
txtItemName.Enabled = false;
btnSave.Enabled = false;
////current date and time
//txtRegister.Text = DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss tt");
// lblMsg notification display
lblMsg.Attributes.Add("style", "color:#FFFFFF");
lblMsg.Attributes.Add("style", "background-color:Green");
// javascript messagebox "Data successfully saved"
ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "msgSave", "msgSave();", true);
}
}
//catching internal error
catch (SqlException ex)
{
// throw some internal error in case there is
string errorMessage = "Error in registring user";
errorMessage = (errorMessage + ex.Message);
throw new Exception(errorMessage);
}
finally
{
//close the database..
con.Close();
}
// button new enabled..
btnNew.Enabled = true;
}
#endregion
// bind grid..
#region BindGrid
private void BindGrid()
{
// Call the Database & Stored Procedure for total Records
SqlConnection myConnection = new SqlConnection(strConnString);
SqlCommand myCommand = new SqlCommand("inv_ItemList_BindGrid", myConnection);
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Parameters.AddWithValue("#startRowIndex", currentPageNumber);
myCommand.Parameters.AddWithValue("#maximumRows", PAGE_SIZE);
myCommand.Parameters.Add("#totalRows", SqlDbType.Int, 4);
myCommand.Parameters["#totalRows"].Direction = ParameterDirection.Output;
myCommand.Parameters.Add("#totalRec", SqlDbType.Int, 4);
myCommand.Parameters["#totalRec"].Direction = ParameterDirection.Output;
SqlDataAdapter ad = new SqlDataAdapter(myCommand);
DataSet ds = new DataSet();
ad.Fill(ds);
gvItemgrid.DataSource = ds;
gvItemgrid.DataBind();
// Display the total records & pages..
double totalRows = int.Parse(myCommand.Parameters["#totalRows"].Value.ToString());
double totalRec = int.Parse(myCommand.Parameters["#totalRec"].Value.ToString());
lbltotalrec.Text = CalculateTotalRow(totalRec).ToString();
lbltotalpage.Text = CalculateTotalPages(totalRows).ToString();
// current page value
lblcurrentpage.Text = currentPageNumber.ToString();
// conditional meets
if ((currentPageNumber == 1))
{
// button first & prev disabled..
btnFirst.Enabled = false;
btnPrevious.Enabled = false;
if ((Int32.Parse(lbltotalpage.Text.ToString()) > 0))
{
btnNext.Enabled = true;
btnLast.Enabled = true;
}
else
{
btnNext.Enabled = false;
}
}
else
{
btnPrevious.Enabled = true;
btnFirst.Enabled = true;
if ((currentPageNumber == Int32.Parse(lbltotalpage.Text.ToString())))
{
btnNext.Enabled = false;
btnLast.Enabled = false;
}
else
{
btnNext.Enabled = true;
btnLast.Enabled = true;
}
}
//current record per page
int val1 = Convert.ToInt32(gvItemgrid.Rows.Count.ToString());
int val2 = Convert.ToInt32(lblcurrentpage.Text.ToString());
int val3 = val1 * val2;
lblrecperpage.Text = Convert.ToString(val3);
// conditional meets equalize the last page value & records..
if ((btnLast.Enabled == false))
{
lblrecperpage.Text = "";
lblrecperpage.Text = totalRec.ToString();
}
else
{
// point out the record at the end of the page..
lblrecperpage.Text = Convert.ToString(val3);
}
// condition
if ((lblrecperpage.Text == lbltotalrec.Text))
{
btnNext.Enabled = false;
btnLast.Enabled = false;
}
else
{
btnNext.Enabled = true;
btnLast.Enabled = true;
}
}
#endregion
SQL Stored Procedure: inv_ItemList_Insert
ALTER PROCEDURE [dbo].[inv_ItemList_Insert]
-- Add the parameters for the stored procedure here
#ItemName VARCHAR(50),
#TypeID INT,
#Result VARCHAR (1000) OUTPUT
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
IF EXISTS (SELECT ItemName FROM dbo.inv_ItemList WHERE ItemName = RTRIM(#ItemName))
BEGIN
SET #Result = 'Item Name: '+ LTRIM(RTRIM(#ItemName)) + ' ' + 'already exists..'
END
ELSE
BEGIN
INSERT INTO [inv_ItemList] ([ItemName], [TypeID])
VALUES (#ItemName, #TypeID);
SET #Result = 'Item Name: '+ LTRIM(RTRIM(#ItemName)) + ' ' + 'is successfully added..'
End
END
SQL Stored Procedure: inv_ItemList_BindGrid
ALTER PROCEDURE [dbo].[inv_ItemList_BindGrid]
-- Add the parameters for the stored procedure here
#startRowIndex int,
#maximumRows int,
#totalRows int OUTPUT,
#totalRec int OUTPUT
AS
DECLARE #first_id int, #startRow int
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
SET #startRowIndex = ((#startRowIndex - 1) * #maximumRows) + 1
IF #startRowIndex = 0
SET #startRowIndex = 1
SET ROWCOUNT #startRowIndex
-- Insert statements for procedure here
SELECT #first_id = ItemID FROM inv_ItemList ORDER BY ItemID
PRINT #first_id
SET ROWCOUNT #maximumRows
SELECT ItemID, ItemName, inv_TypeList.TypeName FROM inv_ItemList
inner join inv_TypeList on inv_ItemList.TypeID=inv_TypeList.TypeID
WHERE
ItemID >= #first_id
ORDER BY ItemID
SET ROWCOUNT 0
-- GEt the total rows
SELECT #totalRows = COUNT(ItemID) FROM inv_ItemList
SELECT #totalRec = COUNT(*) FROM inv_ItemList
END
Is there anything I missed in my code or any other way to achieved my requirements.
Thank you in advance for your help!
I troubleshoot my code already and I found where the error occurs.
I revised the following SQL statement in my SAVE button
//Method in displaying data in reverse (last - first)
//Calling the database
SqlConnection con2 = new SqlConnection(strConnString);
string strConString = "select * from inv_ItemList order by ItemID DESC";
with this one
string strConString = "SELECT ItemID, ItemName, inv_TypeList.TypeName FROM inv_ItemList inner join inv_TypeList on inv_ItemList.TypeID=inv_TypeList.TypeID order by ItemID DESC";
The error doesn't show up anymore, That's where it solved the error.
Thank you guys for your help!:)
I have been created student library page in aspx and c#.
I added two buttons, one for book lending on submit click and another one is return button book returning.
For example:
I enter student id and book id and click submit means, it showed the staus as 'pending'.
or
If i enter same student id and book id for returning book, it showed the status as 'returned'.
The above process works fine.
But again if enter same student id and book id for book lending menas, it doesn't work.
May i know,?
I'm new to .net., can anyone guide me?
Any help would be highly appreciated.
Thanks.
source code:
book lending:
protected void btnsub_Click(object sender, EventArgs e)
{
SqlConnection con = Connection.DBconnection();
SqlCommand com = new SqlCommand("sp_lendingstatus", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#studentid", txtstudentid.Text.Trim());
com.Parameters.AddWithValue("#bookid", txtbookid.Text.Trim());
com.Parameters.AddWithValue("#date", Calendar1.TodaysDate.Date.ToString());
com.Parameters.AddWithValue("#returndate", Calendar2.SelectedDate.ToString());
SqlParameter retval = new SqlParameter("#output", SqlDbType.VarChar, 50);
retval.Direction = ParameterDirection.Output;
com.Parameters.Add(retval);
txtstudentid.Text = string.Empty;
txtbookid.Text = string.Empty;
com.ExecuteNonQuery();
string Output = retval.Value.ToString();
output.Text = Output;
}
return:
protected void btnrtn_Click(object sender, EventArgs e)
{
SqlConnection con = Connection.DBconnection();
SqlCommand com = new SqlCommand("sp_bookreturn", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#studentid", txtstudentid.Text.Trim());
com.Parameters.AddWithValue("#bookid", txtbookid.Text.Trim());
com.Parameters.AddWithValue("#returnstatus", txtbookid.Text.Trim());
com.ExecuteNonQuery();
}
page-load:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlConnection con = Connection.DBconnection();
{
SqlCommand com = new SqlCommand("sp_selectlendingstatus", con);
com.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adp = new SqlDataAdapter(com);
DataSet ds = new DataSet();
adp.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
}
sp_selectlendingstatus:(page_load for showing status)
select *, (CASE WHEN book_lending.bookid IS NULL THEN 'Available' ELSE 'Not
Available' END) as status from studentlibrary left outer join book_lending
ON book_lending.bookid=studentlibrary.Book_id and
book_lending.returnstatus='pending'
sp_lendingstatus for book lending:
ALTER PROCEDURE sp_lendingstatus
(
#studentid int,
#output varchar(50) output,
#bookid int,
#date varchar(50),
#returndate varchar(50)
)
AS
IF NOT EXISTS (SELECT * FROM student WHERE ID=#studentid)
BEGIN
SET #output = 'student id does not exist'
END
ELSE IF NOT EXISTS (SELECT * FROM studentlibrary WHERE Book_id=#bookid)
begin
SET #output = 'Book id does not exist'
END
ELSE IF EXISTS (SELECT * FROM book_lending inner join studentlibrary ON studentlibrary.Book_id=book_lending.bookid where Book_id=#bookid)
begin
SET #output = 'Book id not available'
return
End
ELSE
BEGIN
Insert into book_lending (studentid,bookid,date,returndate) values (#studentid,#bookid,#date,#returndate)
END
book_return:
ALTER PROCEDURE sp_bookreturn
(
#returnstatus varchar(50),
#bookid int,
#studentid int
)
AS
begin
update book_lending set returnstatus='Returned' where bookid=#bookid and studentid=#studentid
End
Note: I set foreign key for bookid and studentid.
Because of this statement in your stored procedure
ELSE IF EXISTS (SELECT * FROM book_lending inner join studentlibrary ON studentlibrary.Book_id=book_lending.bookid where Book_id=#bookid)
Once a book has been checked out once, no matter if it has been returned or not, this will always have a result. You are not deleting the record of the book being lent out (good idea). Update this to exclude those records showing that the book has been returned
ELSE IF EXISTS (SELECT * FROM book_lending inner join
studentlibrary ON studentlibrary.Book_id=book_lending.bookid
Where Book_id=#bookid AND book_lending.returnstatus<>'Returned')
This update should essentially return the book to ready for lending again.
Here is searchupdate_Click code:
protected void searchupdate_Click(object sender, EventArgs e)
{
SqlConnection con = Connection.DBconnection();
{
SqlCommand com = new SqlCommand("sp_searchupdate", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#id", textstudentid.Text);
SqlDataAdapter adp = new SqlDataAdapter(com);
DataSet ds = new DataSet();
adp.Fill(ds);
txttamil.Text = ds.Tables[0].Rows[0]["Tamil"].ToString();
txtenglish.Text = ds.Tables[0].Rows[0]["English"].ToString();
txtmaths.Text = ds.Tables[0].Rows[0]["Maths"].ToString();
txtscience.Text = ds.Tables[0].Rows[0]["Science"].ToString();
txtsocialscience.Text = ds.Tables[0].Rows[0]"SocialScience"].ToString();
}
}
When I enter student id and search, it showed student marks in textboxes.
After that I want to edit and update.
For that I have added above code, and here its stored procedure:
ALTER PROCEDURE sp_searchupdate
(
#id int,
#Tamil varchar(50),
#English varchar(50),
#Maths varchar(50),
#Science varchar(50),
#SocialScience varchar(50)
)
AS
IF EXISTS (SELECT * FROM studentresult WHERE id_student='#id')
begin
SELECT id_student FROM studentresult WHERE id_student='#id'
END
When I edit marks, and hit update button, it shows error.
Here is my output screenshot
May I know, what my mistake in the code, I'm new to .net.
Can anyone help me?
update:
ALTER PROCEDURE sp_searchupdate
(
#id int,
#Tamil Varchar (100),
#English varchar (50),
#Maths Varchar (50),
#Science Varchar (50),
#SocialScience Varchar (50)
)
AS
IF EXISTS (SELECT * FROM studentresult WHERE id_student=#id)
BEGIN
UPDATE studentresult SET Tamil = #Tamil,English = #English, Maths = #Maths,Science = #Science,SocialScience = #SocialScience WHERE id = #id
END
Since your SP expects parameters.
You have to pass the expected parameters to the stored procedure from C#. Like below,
btnSearch_Click
com.Parameters.AddWithValue("#Tamil", "");
com.Parameters.AddWithValue("#English", "");
com.Parameters.AddWithValue("#Maths", "");
com.Parameters.AddWithValue("#Science", "");
com.Parameters.AddWithValue("#SocialScience", "");
btnUpdate_Click
// Add your Parameter
cmd.Parameters.AddWithValue("#id", txtstudentid.Text);
cmd.Parameters.AddWithValue("#tamil", txttamil.Text);
cmd.Parameters.AddWithValue("#english", txtenglish.Text);
cmd.Parameters.AddWithValue("#math", txtmaths.Text);
cmd.Parameters.AddWithValue("#science", txtscience.Text);
cmd.Parameters.AddWithValue("#socialScience", txtsocialscience.Text);
First at all you must understand how your current code work...
Let's say when you click searchupdate this should do what kind of job?
Now base on your code now is actually setting the TextBox to the Database value you retrieve.
Is this what you expect ? Answer is NO
I have separated to 2 button due to your function 1 is for search and another 1 is for update....
// This is First Button
protected void btnSearch_Click(object sender, EventArgs e)
{
// What does theis code here do ??
SqlConnection con = Connection.DBconnection();
{
SqlCommand com = new SqlCommand("PROCEDURE_SELECT", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#id", txtstudentid.Text.Trim());
SqlDataAdapter adp = new SqlDataAdapter(com);
DataSet ds = new DataSet();
adp.Fill(ds);
// SEt value to TextBox & make sure your value below is not Null else it will throw you null exception due to you use .ToString()
txttamil.Text = ds.Tables[0].Rows[0]["Tamil"].ToString();
txtenglish.Text = ds.Tables[0].Rows[0]["English"].ToString();
txtmaths.Text = ds.Tables[0].Rows[0]["Maths"].ToString();
txtscience.Text = ds.Tables[0].Rows[0]["Science"].ToString();
txtsocialscience.Text = ds.Tables[0].Rows[0]["SocialScience"].ToString();
}
}
// This is second Button
protected void btnUpdate_Click(object sender, EventArgs e)
{
using (SqlConnection con = Connection.DBconnection())
{
using (SqlCommand cmd = new SqlCommand("PROCEDURE_UPDATE", con))
{
cmd.CommandType = CommandType.StoredProcedure;
// Add your Parameter
cmd.Parameters.AddWithValue("#id", txtstudentid.Text.Trim());
cmd.Parameters.AddWithValue("#tamil", txttamil.Text.Trim());
cmd.Parameters.AddWithValue("#english", txtenglish.Text.Trim());
cmd.Parameters.AddWithValue("#math", txtmaths.Text.Trim());
cmd.Parameters.AddWithValue("#science", txtscience.Text.Trim());
cmd.Parameters.AddWithValue("#socialScience", txtsocialscience.Text.Trim());
con.Open();
// Execute your Query
cmd.ExecuteNonQuery();
// Clear All The Data in Current TextBOx and press search again with the ID
txttamil.Text = string.Empty;
txtenglish.Text = string.Empty;
txtmaths.Text = string.Empty;
txtscience.Text = string.Empty;
txtsocialscience.Text = string.Empty;
Response.Write("You have updated the value... Try to Search again...");
}
// UPDATE Query as per below
// IF EXISTS (SELECT * FROM studentresult WHERE id_student='#id')
// BEGIN
// UPDATE TABLE SET tamil = #tamil and so on... WHERE id = #id
// END
// ELSE
// BEGIN
// INSERT DATA HERE
// END
}
}
SQL Proc
CREATE PROCEDURE proc_Upd_Student
-- Add the parameters for the stored procedure here
#id VARCHAR(100),
#tamil VARCHAR(100),
#english VARCHAR(100),
#maths VARCHAR(100),
#science VARCHAR(100),
#socialscience VARCHAR(100)
AS
BEGIN
-- CHECK IF THE TABLE CONTAIN THE SAME ID
IF (SELECT COUNT(1) FROM TABLE WHERE id = #id) > 0
BEGIN
-- I DO UPDATE TO THE TABLE
UPDATE TABLE
SET Column = VALUE
WHERE id = #id
END
ELSE
BEGIN
-- IF A NEW ID ? THEN I DO INSERT, IF YOUR ID IS IDENTITY THEN YOU CAN SKIP IT NO NEED TO INSERT
INSERT INTO TABLE (COLUMN)
VALUE
(PARAM)
END
END
The store procedure above is for Update & Insert... Your Select proc can remain due to is different procedure. If you want to combine you add one more parameter called #Action
I am trying to link my c# form to a database that can hold all the data that is inserted in the form.
the other four fields are being inserted into the database correctly.
the problem that I am having is that every time a new record is created, a unique identifier needs to be generated in the last field of the SQL table.
The only way I can do this is by using a guid. But the problem is that I need the Identifier to start from 1 and increment.
I'm not sure how to do this in C# so any help provided would be excellent.
Here is my code
protected void Unnamed1_Click(object sender, EventArgs e)
{
string box1value = TextBox1.Text;
string box2value = TextBox2.Text;
string box3value = TextBox3.Text;
SqlConnection myConnection = new SqlConnection(sConnection);
string sql = "INSERT INTO Part1Table (CustomerDetails, TechnologyPartner, ResponseDate, FormID, RowID) VALUES (#CustomerDetails, #TechnologyPartner, #ResponseDate, #FormID, #RowID)";
myConnection.Open();
try
{
// create a db command objet using the sql and db connection
SqlCommand cmdIns = new SqlCommand(sql, myConnection);
//box1value
cmdIns.Parameters.Add("#CustomerDetails", SqlDbType.Char);
cmdIns.Parameters["#CustomerDetails"].Value = box1value;
//box2value
cmdIns.Parameters.Add("#TechnologyPartner", SqlDbType.Char);
cmdIns.Parameters["#TechnologyPartner"].Value = box2value;
//box3value
cmdIns.Parameters.Add("#ResponseDate", SqlDbType.DateTime);
cmdIns.Parameters["#ResponseDate"].Value = box3value;
cmdIns.Parameters.Add("#FormID", SqlDbType.Int);
cmdIns.Parameters["#FormID"].Value = 1;
cmdIns.Parameters.Add("#RowID", SqlDbType.UniqueIdentifier);
cmdIns.Parameters["#RowID"].Value = Guid.NewGuid();
// run the query
cmdIns.ExecuteNonQuery();
// end the command object
cmdIns.Dispose();
cmdIns = null;
}
catch(Exception ex)
{
Response.Write(ex);
}
myConnection.Close();
You are looking for an IDENTITY COLUMN
For Example
CREATE TABLE [dbo].[Part1Table](
[CustomerDetail] [nvarchar](50) NULL,
....
[RowID] [int] IDENTITY(1,1) NOT NULL
CONSTRAINT [PK_City] PRIMARY KEY CLUSTERED
(
[RowID] ASC
)ON [PRIMARY]
If you have an identity column, the job to add an increment value to every new record, is passed to the database engine.
Of course you cannot pass a value yourself for this column, but you read the value assigned by the database using the command SCOPE_IDENTITY
SELECT SCOPE_IDENTITY()
So, summarizing you could write
string sql = #"INSERT INTO Part1Table (CustomerDetails, TechnologyPartner, ResponseDate,
FormID) VALUES (#CustomerDetails, #TechnologyPartner, #ResponseDate, #FormID)";
using(SqlConnection myConnection = new SqlConnection(sConnection))
SqlCommand cmdIns = new SqlCommand(sql, myConnection);
{
try
{
myConnection.Open();
cmdIns.Parameters.Add("#CustomerDetails", SqlDbType.Char);
cmdIns.Parameters["#CustomerDetails"].Value = box1value;
//box2value
cmdIns.Parameters.Add("#TechnologyPartner", SqlDbType.Char);
cmdIns.Parameters["#TechnologyPartner"].Value = box2value;
//box3value
cmdIns.Parameters.Add("#ResponseDate", SqlDbType.DateTime);
cmdIns.Parameters["#ResponseDate"].Value = box3value;
cmdIns.Parameters.Add("#FormID", SqlDbType.Int);
cmdIns.Parameters["#FormID"].Value = 1;
// No parameter for the ROWID column.
// It will be an error to try to insert
// a value for that column
cmdIns.ExecuteNonQuery();
// Read back the value using the SAME connection used for the insert
cmdIns.Parameters.Clear();
cmdIns.CommandText = "SELECT SCOPE_IDENTITY()";
object result = cmdIns.ExecuteScalar();
int newRowID = Convert.ToInt32(result);
}
}
I asked this question earlier and I thought I found what the problem was, but I didn't. I'm having a problem passing a boolean parameter to a stored procedure. Here's my c# code:
public bool upload = false;
protected void showDate(object sender, EventArgs e)
{
if (Radio1.Checked)
{
upload = true;
Radio2.Checked = false;
date_div.Visible = true;
date_div2.Visible = false;
}
}
protected void getMonthList()
{
selectedYear = year.SelectedValue.ToString();
SqlConnection connection = new SqlConnection(connString);
SqlCommand cmd = connection.CreateCommand();
cmd.CommandType = CommandType.StoredProcedure;
connection.Open();
cmd.CommandText = "getMonth";
cmd.Parameters.Add("#year", SqlDbType.Int, 0).Value = Convert.ToInt32(selectedYear);
cmd.Parameters.AddWithValue("#upload", upload);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
month.DataSource = dt;
month.DataTextField = "month";
month.DataValueField = "monthValue";
month.DataBind();
month.Items.Insert(0, new ListItem("Select", "0"));
}
And this is the stored procedure getMonth:
ALTER PROCEDURE [dbo].[getMonth]
#year int,
#upload Bit
AS
BEGIN
IF #upload = 1
BEGIN
SELECT distinct datename(mm, Upload_date) month
,month (upload_date) monthValue
FROM dbo.RESOLVED
WHERE datepart(yyyy, upload_date) = #year
ORDER by 2
END
ELSE
BEGIN
SELECT distinct datename(mm, substring(CREATE_DT,1,2) + '.' + substring(CREATE_DT,3,2) + '.' + substring(CREATE_DT,5,4)) month
,month (substring(CREATE_DT,1,2) + '.' + substring(CREATE_DT,3,2) + '.' + substring(CREATE_DT,5,4)) monthValue
FROM dbo.RESOLVED
WHERE datepart(yyyy, substring(CREATE_DT,1,2) + '.' + substring(CREATE_DT,3,2) + '.' + substring(CREATE_DT,5,4)) = #year
ORDER by 2
END
The stored procedure is supposed to populate dropdownlist. It supposed to execute the IF statement, but IF is skipped and ELSE is executed instead.
I'd be inclined to specify the type for the boolean parameter also. Maybe something like;
SqlParameter param = new SqlParameter();
param.ParameterName = "#upload";
param.Value = upload;
param.DbType = System.Data.DbType.Boolean
cmd.Parameters.Add(param);
Maybe also check using a breakpoint or even System.Diagnostics.Debug.Write("#Upload is " + upload) to ensure you are passing in what you think you are passing in.
Lastly, I'd suggest putting your SqlConnection and SqlCommand statments in a using block to ensure the resources are cleaned up after this has run.