here,using request.Querystring i find the companyname and job title of particular Job.when user logsin using username in texbix.i want the Companyname,jobtitle and username in the same row of a table.But when i generate my query it inserts the (companyName & jobtitle) in the first row and username in second row.How can i fulfill my task.Some people said,i have to keep the companyname and jobtitle in a variable...then execute.
is it a parfect solution?
if it is,how can i do that?
code:
protected void ButtonApply_Click(object sender, EventArgs e) {
String str = Request.QueryString.Get("JobNo");
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
conn.Open();
string apply = "INSERT INTO Company (CompanyName,JobTitle) select CompanyName,JobTitle from Jobs where JobNo='"+str+"'" ;
SqlCommand insertApply = new SqlCommand(apply, conn);
try {
insertApply.ExecuteScalar();
conn.Close();
Response.Redirect("ApplyJob.aspx?JobNo="+str);
}
in the apply.aspx i have following code:
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
conn.Open();
string apply = "INSERT INTO Company (CandidateInformation) Values (#CandidateInformation)" ;
SqlCommand insertApply = new SqlCommand(apply, conn);
insertApply.Parameters.AddWithValue("#CandidateInformation", TextBoxaun.Text);
insertApply.ExecuteNonQuery();
conn.Close();
Response.Redirect("CompanyInfo.aspx");
Inserting two times will always result in two new rows.
You can do it all in the first insert statement:
string apply = "INSERT INTO Company (CompanyName,JobTitle, CandidateInformation) select
CompanyName,JobTitle, #CandidateInformation from Jobs where JobNo=#JobNo ;
SqlCommand insertApply = new SqlCommand(apply, conn);
insertApply.Parameters.AddWithValue("#CandidateInformation",
TextBoxaun.Text);
insertApply.Parameters.AddWithValue("#JobNo", str);
try
{
insertApply.ExecuteScalar();
conn.Close();
Response.Redirect("CompanyInfo.aspx");
}
Then you won't need the second page.
Use
Update Company Set CandidateInformation = #CandidateInformation where JobNo='"+str+"'" ;
instead of
string apply = "INSERTINTO Company (CandidateInformation) Values
(#CandidateInformation)" ;
If you will use Insert statement again, then it will always create new record in the table.
Update is used to update an already existing record of the table.
Related
I have a list box in Asp.Net from where the user selects one or multiple parameters and send it to a stored procedure. The selected of number of parameters depends completely on the user so I don't know how many parameters the user is going to choose from the list box. I also want to retrieve data back from the table with those parameters when I click on the Submit button and display on a gridview. The issue I am having is I can send one parameter and retrieve data back from my stored procedure but I really don't know how to send multiple parameters from the list box to my stored procedure.
Below is the code for single parameter in Asp.Net
protected void Button_Click(object sender, EventArgs e)
{
string s = "Submit";
SqlCommand cmd = new SqlCommand(s, con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = lbCT.SelectedItem.Value;
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
gvDS.DataSource = ds;
gvDS.DataBind();
con.Close();
}
Below is my stored procedure in SQL Server
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [Submit]
#Name VARCHAR(12)
AS
BEGIN
SELECT *
FROM Employee
WHERE Name = #Name
END
You are sending just parameter and using equals "=" operator. Instead of this, you should send all selected items and split your parameter by delimiter.
Please follow these steps:
1.Create a new sql function for split name/names
CREATE FUNCTION dbo.splitstring (#stringToSplit VARCHAR(MAX))
RETURNS
#returnList TABLE ([Name] [nvarchar] (500))
AS
BEGIN
DECLARE #name NVARCHAR(255)
DECLARE #pos INT
WHILE CHARINDEX(',', #stringToSplit) > 0
BEGIN
SELECT #pos = CHARINDEX(',', #stringToSplit)
SELECT #name = SUBSTRING(#stringToSplit, 1, #pos-1)
INSERT INTO #returnList
SELECT #name
SELECT #stringToSplit = SUBSTRING(#stringToSplit, #pos+1, LEN(#stringToSplit)-#pos)
END
INSERT INTO #returnList
SELECT #stringToSplit
RETURN
END
2.Update your procedure
WHERE Name in (Select dbo.splitstring (#Names))
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [Submit]
#Names VARCHAR(MAX)
AS
BEGIN
SELECT *
FROM Employee
WHERE Name in (Select dbo.splitstring (#Names))
END
3.Update your Codebehind parameter
cmd.Parameters.Add("#Names", SqlDbType.VarChar).Value = join all
selected items with ','
protected void Button_Click(object sender, EventArgs e)
{
string s = "Submit";
SqlCommand cmd = new SqlCommand(s, con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#Names", SqlDbType.VarChar).Value = /*join all selected items with ','*/
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
gvDS.DataSource = ds;
gvDS.DataBind();
con.Close();
}
I have a method to check if the id exists in a table and if it does insert into another database table; additionally I have label that will display the number of data entered. The query to insert into the database and select from the database works fine; but my problem is I'm not able to count, only receiving a count of 1 at all times. It is not incrementing; my question how do I get the counter to increment rather than just showing 1 at all times. This is what I have so far
protected void btnComplete_Click(object sender, EventArgs e)
{
string id = txtid.Text;
string user = lblUsername.Text;
string date = lblDate.Text;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TWCL_OPERATIONSConnectionString"].ToString());
//commands identifying the stored procedure
SqlCommand cmd = new SqlCommand("selectId", conn);
SqlCommand cmd1 = new SqlCommand("CreateUserId", con);
// execute the stored procedures
cmd.CommandType = CommandType.StoredProcedure;
cmd1.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#id", id);
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
cmd1.Parameters.Add("#id", SqlDbType.NVarChar).Value = barcode);
cmd1.Parameters.Add("#Username", SqlDbType.NVarChar).Value = user;
cmd1.Parameters.Add("#Date", SqlDbType.DateTime).Value = date;
counter = counter + 1;
}
reader.Close();
cmd1.ExecuteNonQuery();
lblCount.Text = counter.ToString();
}
else
{
lblError.Text = barcode + " does not exist!!";
}
}
Before you are asked for stored procedures and before giving you a concrete answer, you should fix some problems in your code
1) use using{} blocks with command and connection to make sure they are disposed.
2) In while loop, you are adding parameters to cmd1. Think what will happen if while loop runs more than 1 time!!
Now, if you want to show max in counter, just get max from database !!
In your cmd object you are sending some ID to stored procedure. It will always return 1 record if id is unique in your table.
So your counter is always 1
Solution
Not modifying much of your code, add count(id) as counter in your storedprocedure query returning result of cmd.
And in the while loop assign that to counter variable.
counter = Convert.ToInteger(reader[“counter”].ToString());
Above is not best solution though. As it will count records for all rows and will reduce performance over time.
For best solution, you need to make another command object that executes a query like select count(id) from YourTableName
This will give you number of records in your table.
Edit
From your comment.
You only want total records after inserting from cmd1.
Just do following:
1) In your storedProcedure for cmd 1, write Select Isnull(count(*),0) from YourTableNameHere
2) In your code, use ExecuteScalar instead of ExecuteNonQuery.
var result = cmd1.ExecuteScalar();
lblCount.Text = result.ToString();
Edit 2
You want to keep track of number of records inserted in current session. Use viewstate or session, depending on your requirement to save counter for session Or only untill user stays on current page.
var recordsAdded = cmd1.ExecuteNonQuery();
if(Session[“counter”] == null)
{
Session[“counter”] = 0;
}
if(recordsAdded>0)
{
Session[“counter”] = Convert.ToInteger(Session[“counter”]) + 1;
}
lblCount.Text = Session[“counter”];
Above will keep track of inserted records in session
I have a table Registration with many columns. I need to get customer_id and put that value into a variable for use that in a session for moving & use between ASP Webforms. How can I do this?
You can use ExecuteScalar method to get single column value. Below is a very basic example of how to get single column value.
string connectionString = ConfigurationManager.ConnectionStrings["YourConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("select Customer_id from Registration", con);
con.Open();
string id = cmd.ExecuteScalar().ToString();
}
Here is how you can store the value in session
Session["CustomerID"] = id;
And here is how you can retrieve the value on second page
int ID = 0;
int.TryParse((string)Session["CustomerID"], out ID);
I have a table containing name, surname and email. I want to retrieve them from the table and so i write:
if (LoginAs.SelectedValue == "Administrator")
{
string result;
string query = "Select * from AdminTable where ID='"+ idBox.Text +"'";
cmd1 = new SqlCommand(query, con);
result = Convert.ToString(cmd1.ExecuteScalar());
Response.Redirect("Admin.aspx");
//Admin user = new Admin(idBox.Text, "Active", mail, firstName, LastName, passwordBox.Text);
}
The problem is, it only returns the name field of the specified row even though i wrote "Select *". What is wrong here?
ExecuteScalar returns just the first column of the first row, and ignores the rest.
So you should use ExecuteReader method. An example from MSDN:
using (SqlConnection connection = new SqlConnection(
connectionString))
{
connection.Open();
SqlCommand command = new SqlCommand(queryString, connection);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(String.Format("{0}", reader[0]));
}
}
Note that the while (reader.Read()) checks whether your query returned (more) results and positions the cursor on the next record, that you can then read. This example prints the first column's value.
The using statement makes sure the connection is closed after use, whatever happens.
Also, don't build your query directly with input from the user (such as the value of a TextBox), use parameters instead to prevent SQL injection attacks.
You must try ExecuteReader() instead of using ExecuteScalar()
ExecuteScaler is used in situation where we have to read a single value.eg:
select count(*) from tablename.
while
ExecuteReader is used for any result set with multiple rows/columns
(e.g., SELECT * from TableName)
Sample code:
string myQuery="Select * from AdminTable where ID=#myid";
SqlCommand cmd=new SqlCommand(myQuery,conn);
cmd.Parameters.AddWithValue("#myid", value);
conn.Open();
SqlDataReader dreader;
dreader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
while (dreader.Read())
{
string Value1= dreader["COl1"].ToString();
string Value2= dreader["COl2"].ToString();
}
dreader.Close();
Always use parameterized Query
You may try cmd1.ExecuteReader() instead.
I have to compare a value in a string array to that of a particular column in a database. How do i do this ?
public void setvisibility(string user_ID)
{
SqlDataReader reader = null;
SqlConnection connection = new SqlConnection(WebConfigurationManager.ConnectionStrings["ctd_prrity_dbConnectionSting"].ConnectionString);
connection.Open();\
SqlCommand cmd = new SqlCommand("Select * from Admins );
I need to compare the value of user_ID to the only column in the Admins table !
Here's how you can do it:
using( SqlConnection connection = new SqlConnection(WebConfigurationManager.ConnectionStrings["ctd_prrity_dbConnectionSting"].ConnectionString))
{
connection.Open();
SqlCommand cmd = new SqlCommand("Select 1 from Admins where User_ID=#userid",connection );
cmd.Parameters.AddWithValue("#userid",user_ID);
SqlDataReader reader= cmd.ExecuteReader();
if(reader.HasRows)
{
//user id found
}
}
This method uses a parametrized queries, which are safer than the option given in the answer by Tony since his is prone to SQL Injection attacks.
BTW: you mention "string array" in your question, yet your code only shows a single string as parameter. What did you mean by that?
sqlcommand("SELECT * FROM Admins WHERE column = " & user_ID );
That should work. What that does is it returns the value in the column if it is the same as the user_ID. Basically, if your query returns a value you have a match, if not then you don't.