Im running an update query, it says it is not finding the second parameter (status), although I am clearly sending it. They are in different classes and are being called by a button which sends a mail and then changes the value of a variable (statusRef) in the main table (this field is new).
protected void sendMail(object sender, EventArgs e)
{
BO.Messages mail = new BO.Messages();
string body = "Cuerpo Mensaje";
string title = "Titulo";
string script = "alert(\"An email has been sent to the candidate! \");";
mail.refEmail(emailCandi.Text,title,body);
ScriptManager.RegisterStartupScript(this, GetType(),
"ServerControlScript", script, true);
Email_Sent.Visible = true;
changeRefStatus(Int32.Parse(idCand.Text), "1");
}
protected void changeRefStatus(int id, string status)
{
ASF.HC.JobApplication.BO.User u = new ASF.HC.JobApplication.BO.User();
u.saveStatusRef(id,status);
}
public int saveStatusRef(int id, string status)
{
Entity.User u = new Entity.User();
SqlCommand comando = new SqlCommand("dbo.[user_saveStatusRef]", base.Db);
SqlParameter spSearch = new SqlParameter("#id", System.Data.SqlDbType.Int);
SqlParameter spSearch2 = new SqlParameter("#status", System.Data.SqlDbType.VarChar);
spSearch.Value = id;
spSearch.Value = status;
comando.Parameters.Add(spSearch);
comando.Parameters.Add(spSearch2);
return base.ExecuteScalar(comando);
}
The stored procedure...
ALTER PROCEDURE dbo.user_saveStatusRef
#id int,
#status varchar(5)
AS
UPDATE tbl_user
set statusRef = #status
WHERE id = #id
Maybe a typo but you dont assign Value to spSearch2
spSearch.Value = id;
spSearch.Value = status;
Related
I have 2 link buttons on my page for each product.1 of them is delete that product and the other is redirect it by query string to the other page to Edit that product.
hereprotected void dlMusic_ItemCommand(object source, DataListCommandEventArgs e)
{
int id = Convert.ToInt32(e.CommandArgument);
if (e.CommandName == "EditItem")
{
Response.Redirect("~/Admin/EditMusic.aspx?id=" + id);
}
else if (e.CommandName == "DeleteItem")
{
SqlCommand cmd = new SqlCommand("", Connection);
cmd.CommandText = "DELETE FROM MusicTable WHERE MusicId=#id";
cmd.Parameters.AddWithValue("#id", id);
Connection.Open();
cmd.ExecuteNonQuery();
Connection.Close();
LoadData();
}
}
Delete button worked correctly but on edit I have problem.
protected void Page_Load(object sender, EventArgs e)
{
int id = int.Parse(Request.QueryString["id"]);
SqlDataAdapter da = new SqlDataAdapter("", Connection);
DataTable dt = new DataTable();
da.SelectCommand.CommandText = "SELECT * FROM MusicTable WHERE MusicId=#id";
da.SelectCommand.Parameters.AddWithValue("#id", id);
da.Fill(dt);
string name = dt.Rows[0]["MusicName"].ToString();
string signame = dt.Rows[0]["SingerName"].ToString();
string prodname = dt.Rows[0]["ProducerName"].ToString();
string albname = dt.Rows[0]["AlbumeName"].ToString();
string des = dt.Rows[0]["Description"].ToString();
string cover = dt.Rows[0]["Cover"].ToString();
txtMusicName.Text = name;
txtSingerName.Text = signame;
txtProducerName.Text = prodname;
txtAlbumeName.Text = albname;
coverImg.ImageUrl = "~/images/" + cover;
txtDes.InnerText = des;
}
It works correctly until requested by query string and the error come is
Additional information: Value cannot be null.
Thanks in advance
From your comment, it is apparent that field "id" is not part of your QueryString.
Please check your URL when the Edit Page is loaded by the browser (you can see it if you put a breakpoint and switch to the browser window).
If you think your URL is correct, please post a screenshot of your loading browser.
Another idea (quite desperate, though), change "id" in whatever else (i.e. "myid")
Response.Redirect("~/Admin/EditMusic.aspx?myid=" + id);
and
int id = int.Parse(Request.QueryString["myid"]);
I am trying to select a user from my default_information.aspx.cs page and display that user information on my registration.aspx page where I already created a registration form.
I am getting System.NullReferenceException:Object reference not set to an instance of an object error. Please help me. I've given the main part of it. I debugged it. I found every data is selected from my DB in string strusername,strpassword. But code breaks on usernametxt.Text = strusername; when i try to show username or password on that text field.
default_information contains
protected void gridviewprofile_SelectedIndexChanged(object sender, EventArgs e)
{
registration objdef = new registration();
string username = gridviewprofile.Rows[gridviewprofile.SelectedIndex].Cells[1].Text;
objdef.displayuser(username);
}
protected void update_Click(object sender, EventArgs e)
{
Response.Redirect("registration.aspx");
}
registration.aspx contains
protected void register_Click(object sender, EventArgs e)
{
user objuser = new user();
objuser.username = usernametxt.Text;
objuser.password = passwordtxt.Text;
objuser.email = emailtxt.Text;
objuser.Save();
}
public void displayuser(string username)
{ user obj = new user();
DataSet objDataset = obj.profile(username);
string strusername = objDataset.Tables[0].Rows[0][0].ToString();
string strpassword = objDataset.Tables[0].Rows[0][1].ToString();
string stremail = objDataset.Tables[0].Rows[0][2].ToString();
usernametxt.Text = strusername;
passwordtxt.Text = strpassword;
emailtxt.Text = stremail;
}
user class contains
public class user
{
public void Save()
{
clssqlserver obj = new clssqlserver();
obj.insertuser_info(Username,Password,Email);
}
public DataSet profile(string username)
{
clssqlserver obj = new clssqlserver();
return obj.getalluser_info(username);
}
}
clssqlserver contains
public DataSet getalluser_info(string username)
{
string connectionstring = "Data Source=localhost\\mssql;Initial Catalog=blooddb;Integrated Security=True";
SqlConnection objconnection = new SqlConnection(connectionstring);
objconnection.Open();
string command = "Select * from login_donor where username='" + username + "' ";
SqlCommand objcommand = new SqlCommand(command, objconnection);
DataSet objdataset = new DataSet();
SqlDataAdapter objadapter = new SqlDataAdapter(objcommand);
objadapter.Fill(objdataset);
objconnection.Close();
return objdataset;
}
public bool insertuser_info(string username,string password,string email)
{ string connectionstring = "Data Source=localhost\\mssql;Initial Catalog=blooddb;Integrated Security=True";
SqlConnection objconnection = new SqlConnection(connectionstring);
objconnection.Open();
string strInsertCommand = "insert into login_donor values('"+ username +"','"+ password + "','"+email+"')";
SqlCommand objcommand = new SqlCommand(strInsertCommand, objconnection);
objcommand.ExecuteNonQuery();
objconnection.Close();
return true;
}
It looks like you are using the asp.net create user wizard control.Because your controls are buried inside another container, you have to be rewarded after some little excavation..Lets start digging......
Using the wizard which is already accessible locate your text box
TextBox usernametxt= (TextBox)CreateUserWizard.FindControl("usernametxt");
usernametxt.Text = strusername;
Hope this will help.
You should check this line
string strusername = objDataset.Tables[0].Rows[0][0].ToString();
you are trying to access directly objDataset.Tables[0], what if there is no user with the supplied username to this method getalluser_info(string username), will the dataset fill the table.
you should first check whether there is any table in the dataset or not.
hope this helps
well i ve found the solution...i was passing Data Between Webforms in worng way..here is the link which helps me: http://dotnetslackers.com/community/blogs/haissam/archive/2007/11/26/ways-to-pass-data-between-webforms.aspx
here is the solution
default_information.aspx contains
protected void gridviewprofile_SelectedIndexChanged(object sender, EventArgs e)
{ string username = gridviewprofile.Rows[gridviewprofile.SelectedIndex].Cells[1].Text;
Response.Redirect("registration.aspx?id="+username);
}
registration.aspx contains:
protected void Page_Load(object sender, EventArgs e)
{
string queryStringID = Request.QueryString["id"];
displayuser(queryStringID);
}
public void displayuser(string username)
{ user obj = new user();
DataSet objDataset = obj.profile(username);
string strusername = objDataset.Tables[0].Rows[0][0].ToString();
string strpassword = objDataset.Tables[0].Rows[0][1].ToString();
string stremail = objDataset.Tables[0].Rows[0][2].ToString();
usernametxt.Text = strusername;
passwordtxt.Text = strpassword;
emailtxt.Text = stremail;
}
Okay I am a noob to parameterized queries. I understand why you should use them and all but I cannot find any resource that shows the correct way or at least one that shows the correct way that actually works.
So my question is about whether or not my code is right. It compiles and runs just fine but it returns absolutely nothing in the gridview.
protected void SearchButton_Click(object sender, EventArgs e)
{
string searchBoxValue = SearchBox.Text;
string columnNameValue = ColumnName.SelectedValue;
columnNameValue.ToLower();
SqlCommand searchCommand = new SqlCommand();
searchCommand.Connection = connection;
searchCommand.CommandText = "select firstname AS FirstName,lastname AS LastName, zipcode as ZipCode, phone AS Phone, email AS Email, cancersurvivor AS CancerSurvivor, ethnicity AS Ethnicity from registrants where #columnname = #searchterm";
SqlParameter columnParam = new SqlParameter();
columnParam.ParameterName = "#columnname";
columnParam.Value = columnNameValue;
SqlParameter searchBoxParam = new SqlParameter();
searchBoxParam.ParameterName = "#searchterm";
searchBoxParam.Value = searchBoxValue;
searchCommand.Parameters.Add(columnParam);
searchCommand.Parameters.Add(searchBoxParam);
UpdateTable(searchCommand);
}
The UpdateTable function takes in the an SqlCommand object and then uses a DataAdapter object to execute the command and fills a DataTable object then sets the gridview datasource to the datatable object and binds it.
Like I said before I am really looking for the proper way to do this? do I need a stored procedure in order to do this? I am confused by all this and why it is not working.
You cannot parameterise #columnname. This needs to be a literal in your query.
Your statement
select
/* .... */
from registrants where #columnname = #searchterm
will return all rows from registrants if the value of the parameters happens to be the same or no rows otherwise.
It will not look and see if you have a column of that name and see if #searchterm exists in it.
To do this in a safe way you would need to check that columnNameValue matches one of a whitelist of valid column names (as you must know the possible column names in that table) and concatenate it into your query. Do not concatenate unvalidated user input. as then you open yourself up to SQL injection.
So you might implement it something like
using System.Linq;
protected void SearchButton_Click(object sender, EventArgs e)
{
string columnNameValue = ColumnName.SelectedValue.ToLower();
var validColumnNames = new string[] { "firstname", "lastname", "zipcode" };
if (!validColumnNames.Contains(columnNameValue))
{
throw new Exception("Unexpected column name " + columnNameValue);
}
/* ... code omitted */
searchCommand.CommandText = "select firstname AS FirstName,lastname AS LastName, zipcode as ZipCode, phone AS Phone, email AS Email, cancersurvivor AS CancerSurvivor, ethnicity AS Ethnicity from registrants where " + columnNameValue + " = #searchterm";
/* ... code omitted */
}
The purpose of paramtrized command are to prevent sql injection. You cannot parametrize the name of the column, sql will take it as a string.
protected void SearchButton_Click(object sender, EventArgs e)
{
string searchBoxValue = SearchBox.Text;
string columnNameValue = ColumnName.SelectedValue;
columnNameValue.ToLower();
SqlCommand searchCommand = new SqlCommand();
searchCommand.Connection = connection;
//Put the column name directly in the request, but use a parameter for the search value
searchCommand.CommandText = "select firstname AS FirstName,lastname AS LastName, zipcode as ZipCode, phone AS Phone, email AS Email, cancersurvivor AS CancerSurvivor, ethnicity AS Ethnicity from registrants where " + columnNameValue + " = #searchterm";
/* No need for this part
SqlParameter columnParam = new SqlParameter();
columnParam.ParameterName = "#columnname";
columnParam.Value = columnNameValue;
*/
SqlParameter searchBoxParam = new SqlParameter();
searchBoxParam.ParameterName = "#searchterm";
searchBoxParam.Value = searchBoxValue;
//searchCommand.Parameters.Add(columnParam);
searchCommand.Parameters.Add(searchBoxParam);
UpdateTable(searchCommand);
}
Your issue is in how you're trying to make your column name as a parameter. You'll want to change the query as a whole to reflect which column you want to filter by. Try the following:
protected void SearchButton_Click(object sender, EventArgs e)
{
string searchBoxValue = SearchBox.Text;
string columnNameValue = ColumnName.SelectedValue;
columnNameValue.ToLower();
SqlCommand searchCommand = new SqlCommand();
searchCommand.Connection = connection;
searchCommand.CommandText = String.Format("select firstname AS FirstName,lastname AS LastName, zipcode as ZipCode, phone AS Phone, email AS Email, cancersurvivor AS CancerSurvivor, ethnicity AS Ethnicity from registrants where {0} = #searchterm",columnNameValue);
SqlParameter searchBoxParam = new SqlParameter();
searchBoxParam.ParameterName = "#searchterm";
searchBoxParam.Value = searchBoxValue;
searchCommand.Parameters.Add(columnParam);
searchCommand.Parameters.Add(searchBoxParam);
UpdateTable(searchCommand);
}
If you want this to work, you'd have to build the SQL statment dynamically and execute with sp_executesql inside the proc as so:
DECLARE #IntVariable int;
DECLARE #SQLString nvarchar(500);
DECLARE #ParmDefinition nvarchar(500);
/* Build the SQL string one time.*/
SET #SQLString =
N'SELECT BusinessEntityID, NationalIDNumber, JobTitle, LoginID
FROM AdventureWorks2012.HumanResources.Employee
WHERE BusinessEntityID = #BusinessEntityID';
SET #ParmDefinition = N'#BusinessEntityID tinyint';
/* Execute the string with the first parameter value. */
SET #IntVariable = 197;
EXECUTE sp_executesql #SQLString, #ParmDefinition,
#BusinessEntityID = #IntVariable;
/* Execute the same string with the second parameter value. */
SET #IntVariable = 109;
EXECUTE sp_executesql #SQLString, #ParmDefinition,
#BusinessEntityID = #IntVariable;
You still have the benefit of using parametrized queries and not exposing yourself to SQL Injection.
Source here.
Another very useful link is this.
I'm trying to insert data from a form to my database and it is throwing this error:
No mapping exists from object type System.Web.UI.WebControls.TextBox to a known managed provider native type.
Maybe it has to do with the fact that I try to get a data from a dropdownlist and I'm not really sure the syntax is great.
Here is the code:
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=MICROSOF-58B8A5\\SQL_SERVER_R2;Initial Catalog=Movie;Integrated Security=True");
conn.Open();
string titleName = Title.Text;
string sqlQuery = ("INSERT INTO Movies(Ganere, Title, Descreption) VALUES (#Ganere, #Title , #Descreption) ");
SqlCommand cmd = new SqlCommand(sqlQuery, conn);
cmd.Parameters.AddWithValue("Title", Title);
string genre = GenreDropDown.SelectedIndex.ToString();
cmd.Parameters.AddWithValue("Ganere", GenreDropDown);
string descp = Descreption.Text;
cmd.Parameters.AddWithValue("Descreption", Descreption);
if (titleName == null || genre == null)
{
ErrorMessege.Text = "Please fill all of the fields.";
}
else
{
ErrorMessege.Text = "You have successfully add a movie!";
cmd.ExecuteNonQuery();
}
conn.Close();
}
You -weren't using any of the vars where you had the values
string titleName = Title.Text;
string sqlQuery = ("INSERT INTO Movies(Ganere, Title, Descreption) VALUES (#Ganere, #Title , #Descreption) ");
SqlCommand cmd = new SqlCommand(sqlQuery, conn);
cmd.Parameters.AddWithValue("Title", titlename);
string genre = GenreDropDown.SelectedIndex.ToString();
cmd.Parameters.AddWithValue("Ganere", genre);
string descp = Descreption.Text;
cmd.Parameters.AddWithValue("Descreption", descp);
if (titleName == null || genre == null)
{
ErrorMessege.Text = "Please fill all of the fields.";
}
else
{
ErrorMessege.Text = "You have successfully add a movie!";
cmd.ExecuteNonQuery();
}
conn.Close();
}
The problem is that you are trying to use the entire textbox as the value to the parameter.
Change:
cmd.Parameters.AddWithValue("Title", Title);
to
cmd.Parameters.AddWithValue("Title", Title.Text);
I have few textboxes whose values are to be inserted into SQl table on Submit button click. But it gives me "Object reference not set to an instance of an object" Exception. Below is the code I have written for this. Please do help me in this.
contact_new.aspx.cs
protected void btnSubmit_Click(object sender, EventArgs e)
{
DateTime dtime;
dtime = DateTime.Now;
string ocode = offercode.Text;
string firstname = firstnamepreapp.Text;
string lastname = lastnamepreapp.Text;
string email = emailpreapp.Text;
string phoneno = phonepreapp.Text;
string timetocall = besttimepreapp.SelectedItem.Value;
string time = dtime.ToString();
//Insert the data into autoprequal table
<--- GIVES ME AN ERROR ON THIS LINE --->
Insert.insertINTOautoprequal(ocode, time, firstname, lastname, email, phoneno, timetocall);
}
Insert.cs (App_code class)
namespace InsertDataAccess
{
public class Insert
{
public Insert()
{
//
// TODO: Add constructor logic here
//
}
public static bool insertINTOautoprequal(string code, string time, string first, string last, string email, string phoneno, string timetocall)
{
bool success = false;
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connstring"].ConnectionString);
conn.Open();
string query = "Insert INTO autoprequal(offercode, timeofday, firstname, lastname, emailID, phone, besttimetocall) Values(#offercode, #time, #first, #last, #email, #phoneno, #timetocall);";
SqlCommand cmd = new SqlCommand(query, conn);
try
{
cmd.Parameters.AddWithValue("#offercode", code);
cmd.Parameters.AddWithValue("#time", time);
cmd.Parameters.AddWithValue("#first", first);
cmd.Parameters.AddWithValue("#last", last);
cmd.Parameters.AddWithValue("#email", email);
cmd.Parameters.AddWithValue("#phoneno", phoneno);
cmd.Parameters.AddWithValue("#timetocall", timetocall);
if (cmd.ExecuteNonQuery() == 1) success = true;
else success = false;
return success;
}
catch
{
throw;
}
finally
{
conn.Close();
}
}
}
}
Step through the code, as the error is most likely bubbling up from the SQL insert routine. I woulud guess the connection string is not being pulled from the configuration file, but without stepping through that is a wild guess. I would take time to learn how to debug in Visual Studio, as it will help you easily spot what cannot be a problem so you can focus on what is likely to be the problem.