SQLCommand AddWithValue - What am I doing wrong? - asp.net

protected void gridOmniZone_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = gridOmniZone.Rows[e.RowIndex];
Int64 ID = Convert.ToInt64(gridOmniZone.DataKeys[e.RowIndex].Values[0]);
string Description = (row.Cells[2].Controls[1] as TextBox).Text;
string LatCenter = (row.Cells[3].Controls[1] as TextBox).Text;
string LongCenter = (row.Cells[4].Controls[1] as TextBox).Text;
string Radius = (row.Cells[5].Controls[1] as TextBox).Text;
string Address = (row.Cells[6].Controls[1] as TextBox).Text;
string City = (row.Cells[7].Controls[1] as TextBox).Text;
string State = (row.Cells[8].Controls[1] as TextBox).Text;
string PostalCode = (row.Cells[9].Controls[1] as TextBox).Text;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("dbo.usp_UpdateOmniZone"))
{
cmd.Connection = con;
cmd.Parameters.Add("#ID", SqlDbType.BigInt);
cmd.Parameters[0].Value = ID;
cmd.Parameters.AddWithValue("#Description", Description);
cmd.Parameters.AddWithValue("#LatCenter", LatCenter);
cmd.Parameters.AddWithValue("#LongCenter", LongCenter);
cmd.Parameters.AddWithValue("#Radius", Radius);
cmd.Parameters.AddWithValue("#Address", Address);
cmd.Parameters.AddWithValue("#City", City);
cmd.Parameters.AddWithValue("#State", State);
cmd.Parameters.AddWithValue("#PostalCode", PostalCode);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
gridOmniZone.EditIndex = -1;
this.BindGrid();
}
My code above throws an error on cmd.ExecuteNonQuery. The error is:
stored procedure expects parameter #ID which was not supplied.
As you can see, I did provide the parameter. Any idea what I am doing wrong? The debugger is telling me that the variable ID is a valid integer value.

I think the problem is that you forgot to set the CommandType to CommandType.StoredProcedure.

I up-voted the other answer - the issue is that message is common if you don't set the command type to stored procedure.
And you ARE better off to strong type the values.
So, this:
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("dbo.usp_UpdateOmniZone",con))
{
cmd.Parameters.Add("#ID", SqlDbType.BigInt).Value = ID;
cmd.Parameters.Add("#Description",SqlDbType.NVarChar).Value = Description;
cmd.Parameters.Add("#LatCenter", SqlDbType.NVarChar).Value = LatCenter;
cmd.Parameters.Add("#LongCenter", SqlDbType.NVarChar).Value = LongCenter;
cmd.Parameters.Add("#Radius", SqlDbType.NVarChar).Value = Radius;
cmd.Parameters.Add("#Address", SqlDbType.NVarChar).Value = Address;
cmd.Parameters.Add("#City", SqlDbType.NVarChar).Value = City;
cmd.Parameters.Add("#State", SqlDbType.NVarChar).Value = State;
cmd.Parameters.Add("#PostalCode", SqlDbType.NVarChar).Value = PostalCode;
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
cmd.ExecuteNonQuery();
}
}
And you don't need the "close" connection - quite much the WHOLE point of the "using" block.

Related

How do i fill up textbox from database in asp.net visual studio without id?

I am trying to get details of an account in a row using the Username instead of id. I have limited knowledge on this matter so im only stuck with the code that i learned in class.
I have tried changing variables, but probably wont help and the code i have provided below, would not retrieve any data from the database...
(Username are retrieved from previous page and yes it did show up in this page)
This is the code used on previous page: (code is placed on a button)
string username = Session["Username"].ToString();
Response.Redirect("EditAccountDetail.aspx?Username="+ username);
private DataTable GetData()
{
string constr = ConfigurationManager.ConnectionStrings["myDbConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Guest"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
return dt;
}
}
}
}
}
This is the code im working on right now:
String Uname = Request.QueryString["Username"];
string constr = ConfigurationManager.ConnectionStrings["MyDbConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Guest WHERE Username='" + Uname+"'"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
foreach (DataRow row in dt.Rows)
{
string id = row["Id"].ToString();
string Full_name = row["Full_name"].ToString();
string Username = row["Username"].ToString();
string Password = row["Password"].ToString();
string Email = row["Email"].ToString();
string DOB = row["DOB"].ToString();
string Gender = row["Gender"].ToString();
this.HiddenField1.Value = id;
this.TextBox_Name.Text = Full_name;
this.TextBox_Username.Text = Username;
this.TextBox_Password.Text = Password;
this.TextBox_Email.Text = Email;
this.TextBox_DOB.Text = DOB;
this.RadioButtonList_Gender.Text = Gender;
}
}
}
}
}
This is the code in the button:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["myDbConnectionString"].ConnectionString);
try
{
string query = "UPDATE Guest SET Full_name=#Full_name, Username=#Username, Password=#Password, Email=#Email, DOB=#DOB, Gender=#Gender WHERE Id=#id";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#id", HiddenField1.Value);
cmd.Parameters.AddWithValue("#Full_name", TextBox_Name.Text);
cmd.Parameters.AddWithValue("#Username", TextBox_Username.Text);
cmd.Parameters.AddWithValue("#Password", TextBox_Password.Text);
cmd.Parameters.AddWithValue("#Email", TextBox_Email.Text);
cmd.Parameters.AddWithValue("#DOB", TextBox_DOB.Text);
cmd.Parameters.AddWithValue("#Gender", RadioButtonList_Gender.Text);
con.Open();
cmd.ExecuteNonQuery();
Response.Redirect("GuestMenu.aspx");
con.Close();
}
catch (Exception ex)
{
Response.Write("Error: " + ex.ToString());
}
If you are redirecting to the "GuestMenu" page, then you have to add username in the query string so that you can retrieve this on the page.
Response.Redirect("GuestMenu.aspx?Username="+TextBox_Username.Text);
By seeing your current code, you should be getting some error. Please post the error details if any.
You can try changing the query as below and check for database result
new SqlCommand("SELECT * FROM Guest WHERE Username='" + Uname + "'")

Using datareader to count Asp.net

I'm checking if a barcode from a database table(using a select query) exists and insert the details into another database table else the barcode does not exist. The inserts fine but I would like to count the number of barcodes entered. Say within a session an user enters 5 barcodes then the total count is 5 but my code keeps returning 1 and not incrementing.
protected void btnReturn_Click(object sender, EventArgs e)
{
string barcode = txtBarcode.Text;
string location = lblLocation.Text;
string user = lblUsername.Text;
string actType = lblAct.Text;
string date = lblDate.Text;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TWCL_OPERATIONSConnectionString"].ToString());
//commands identifying the stored procedure
SqlCommand cmd = new SqlCommand("selectCrate", conn);
SqlCommand cmd1 = new SqlCommand("CreateCrateBox", con);
// execute the stored procedures
cmd.CommandType = CommandType.StoredProcedure;
cmd1.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#crateno", barcode);
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows) {
while (reader.Read())
{
lblResult.Text = reader[0].ToString();
lblResult1.Text = reader[1].ToString();
cmd1.Parameters.Add("#crateno", SqlDbType.NVarChar).Value = barcode);
cmd1.Parameters.Add("#CurrentLocation", SqlDbType.NVarChar).Value = location;
cmd1.Parameters.Add("#Username", SqlDbType.NVarChar).Value = user;
cmd1.Parameters.Add("#Date", SqlDbType.DateTime).Value = date;
cmd1.Parameters.Add("#status", SqlDbType.NVarChar).Value = actType;
counter = counter + 1;
}
reader.Close();
cmd1.ExecuteNonQuery();
txtCount.Text = counter.ToString();
lblCount.Text = string.Format("Number of rows: {0}", counter);
}
else
{
lblError.Text = barcode + " does not exist!!";
}
}
You can store the number in session then do something with it when the session ends (store it in a database or whatever you want). Declare a session variable:
Session[“NumInserts”] = 0;
Then update it with each insert:
Session[“NumInserts”] = (int) Session[“NumInserts”] + 1;
That variable will be maintained as long as the session exists. Also, make sure you only declare the session variable once and don’t ever allow it to reset during the session’s life cycle. Otherwise, it will go back to 0 and give you inaccurate results.
i rechecked to make sure and i misunderstood your question which led to some confusion.
And to answer your question i don't think there is any easy solution to update realtime the numbers. Any solution of i can think of is websocket connection which I personally have no knowledge of inside webforms(Don't even know if its possible).
I formatted your code. This should give you the total rows back in one go(no realtime update on screen).
protected void btnReturn_Click(object sender, EventArgs e)
{
int counter = 0;
string barcode = txtBarcode.Text;
string location = lblLocation.Text;
string user = lblUsername.Text;
string actType = lblAct.Text;
string date = lblDate.Text;
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TWCL_OPERATIONSConnectionString"].ToString()))
{
con.Open();
//commands identifying the stored procedure
using (SqlCommand cmd = new SqlCommand("selectCrate", con))
{
using (SqlCommand cmd1 = new SqlCommand("CreateCrateBox", con))
{
// execute the stored procedures
cmd.CommandType = CommandType.StoredProcedure;
cmd1.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#crateno", barcode));
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
lblResult.Text = reader[0].ToString();
lblResult1.Text = reader[1].ToString();
cmd1.Parameters.Add("#crateno", SqlDbType.NVarChar).Value = barcode;
cmd1.Parameters.Add("#CurrentLocation", SqlDbType.NVarChar).Value = location;
cmd1.Parameters.Add("#Username", SqlDbType.NVarChar).Value = user;
cmd1.Parameters.Add("#Date", SqlDbType.DateTime).Value = date;
cmd1.Parameters.Add("#status", SqlDbType.NVarChar).Value = actType;
counter++;
}
cmd1.ExecuteNonQuery();
txtCount.Text = counter.ToString();
lblCount.Text = string.Format("Number of rows: {0}", counter);
}
else
{
lblError.Text = barcode + " does not exist!!";
}
}
}
}
}
}

Object must implement IConvertible using ASP.NET

i'm experiencing this error called Object must implement IConvertible.
please help me!
i think it is because of the drop down list for user type. even if i delete / comment out the drop down list i am still experiencing this error.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class Admin_Register : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(Helper.GetCon());
protected void Page_Load(object sender, EventArgs e)
{
GetUserTypes();
}
void GetUserTypes()
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT TypeID, TypeName FROM UserTypes";
SqlDataReader data = cmd.ExecuteReader();
ddlUserTypes.DataSource = data;
ddlUserTypes.DataTextField = "TypeName";
ddlUserTypes.DataValueField = "TypeID";
ddlUserTypes.DataBind();
con.Close();
}
bool IsRecordExisting(string email)
{
bool existing = true;
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT EmailAddress FROM Users WHERE EmailAddress=#EmailAddress";
cmd.Parameters.Add("#EmailAddress", SqlDbType.VarChar).Value = email;
SqlDataReader data = cmd.ExecuteReader();
if (data.HasRows)
existing = true;
else
existing = false;
con.Close();
return existing;
}
protected void btnRegister_Click(object sender, EventArgs e)
{
if (!IsRecordExisting(txtEmail.Text))
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "INSERT INTO Users VALUES (#EmailAddress, #Password, #TypeID, #FirstName, #LastName, #MiddleInitial, #Address, #TelNo, #CelNo, #Status";
cmd.Parameters.Add("#EmailAddress", SqlDbType.VarChar).Value = txtEmail.Text;
cmd.Parameters.Add("#Password", SqlDbType.VarChar).Value = Helper.CreateSHAHash(txtPassword.Text);
cmd.Parameters.Add("#TypeID", SqlDbType.Int).Value = ddlUserTypes.SelectedValue;
cmd.Parameters.Add("#FirstName", SqlDbType.VarChar).Value = txtFN;
cmd.Parameters.Add("#LastName", SqlDbType.VarChar).Value = txtLN;
cmd.Parameters.Add("#MiddleInitial", SqlDbType.VarChar).Value = "";
cmd.Parameters.Add("#Address", SqlDbType.VarChar).Value = "";
cmd.Parameters.Add("#TelNo", SqlDbType.VarChar).Value = "";
cmd.Parameters.Add("#CelNo", SqlDbType.VarChar).Value = "";
cmd.Parameters.Add("#Status", SqlDbType.VarChar).Value = "Active";
cmd.ExecuteNonQuery();
con.Close();
Helper.Log("0", "Register", "User Registration");
Helper.ClearTextboxes(this.Controls);
register.Visible = true;
}
else
{
register.Visible = false;
error.Visible = true;
}
}
}
I found two problems in your code
First
Please check these lines
cmd.Parameters.Add("#FirstName", SqlDbType.VarChar).Value = txtFN;
cmd.Parameters.Add("#LastName", SqlDbType.VarChar).Value = txtLN;
You are setting parameter value as Texbox. You need to set text of the textbox as parameter values.
cmd.Parameters.Add("#FirstName", SqlDbType.VarChar).Value = txtFN.Text;
cmd.Parameters.Add("#LastName", SqlDbType.VarChar).Value = txtLN.Text;
Second
Dropdown list SelectedValue property return string value. That menas you need to convert string value to int type at assigning time.
Please change this line
cmd.Parameters.Add("#TypeID", SqlDbType.Int).Value = ddlUserTypes.SelectedValue;
to
cmd.Parameters.Add("#TypeID", SqlDbType.Int).Value = Convert.ToInt32(ddlUserTypes.SelectedValue);

Data list where clause

i am using a datalist to display videos but i am trying to get it working now with the where clasue ...where the name is equal to wrd.mp4 i am getting the following error,
$exception {"The multi-part identifier \"wrd.mp4\" could not be bound."} System.Exception {System.Data.SqlClient.SqlException}
private void BindGrid()
{
string strConnString = ConfigurationManager.ConnectionStrings["DatabaseConnectionString1"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select Id, Name from tblFiles where Name=wrd.mp4";
cmd.Connection = con;
con.Open();
DataList1.DataSource = cmd.ExecuteReader();
DataList1.DataBind();
con.Close();
}
}
}
}
You need to use quotes:
cmd.CommandText = "select Id, Name from tblFiles where Name='wrd.mp4'";

Error: Object reference not set to an instance of an object

I'm not really good at programming and I don't know what's happening in my codes, it works well before but now I get this error:
NullReferenceException was unhadled by user code.
Object Reference not set to an instance of an object.
Here's my code:
void GetProfileInfo()
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT FirstName, LastName, Address, ContactNo, EmailAddress FROM Users " +
"WHERE UserID=#UserID";
cmd.Parameters.Add("#UserID", SqlDbType.Int).Value = Session["userid"].ToString();
SqlDataReader data = cmd.ExecuteReader();
while (data.Read())
{
txtFN.Text = data["FirstName"].ToString();
txtLN.Text = data["LastName"].ToString();
txtAddress.Text = data["Address"].ToString();
txtContact.Text = data["ContactNo"].ToString();
txtEmail.Text = data["EmailAddress"].ToString();
}
con.Close();
}
First you have to check all occurrences where Session["userid"] is initialized,
then in order to avoid exception error you have to check this variable value whether is null or wrap the code with try catch finally blocks
Ex:
try
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT FirstName, LastName, Address, ContactNo, EmailAddress FROM Users " +
"WHERE UserID=#UserID";
cmd.Parameters.Add("#UserID", SqlDbType.Int).Value = Session["userid"].ToString();
SqlDataReader data = cmd.ExecuteReader();
while (data.Read())
{
txtFN.Text = data["FirstName"].ToString();
txtLN.Text = data["LastName"].ToString();
txtAddress.Text = data["Address"].ToString();
txtContact.Text = data["ContactNo"].ToString();
txtEmail.Text = data["EmailAddress"].ToString();
}
}
catch(Exception e)
{
string message = e.Message;
MessageBox.Show(message);
}
finally
{
con.Close();
}

Resources