Object must implement IConvertible using ASP.NET - 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);

Related

SQLCommand AddWithValue - What am I doing wrong?

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.

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 + "'")

How to use local variable of Page_OnLoad method in OnClick event in asp.net C#

I am designing a website in which I need to update a table Company in my database through CompanyDetails page with respect to the auto increment field CompanyID which is being passed through Query string from previous page named Company and only one button is there for insert and update. So my problem is I am unable to get the value of Companyid of Page_OnLoad event in SaveButtonClick event.
Note: I have already tried Session and View state, IsPostBack but in Onclick event even their value are not being maintained and are updated to 0 or null.
Here is my code......(Please ignore my coding mistakes)
using System;
using System.Web.UI;
using System.Data;
using System.Data.SqlClient;
public partial class CompanyDetails : System.Web.UI.Page
{
int Companyid = 0;
string cmdName = null;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Companyid = Convert.ToInt32(Request.QueryString["CompanyID"]);
cmdName = Request.QueryString["CommandType"];
Session["something"] = Companyid;
}
if (cmdName == "Details")
{
BindTextBoxvalues();
}
}
protected void SaveButton_Click(object sender, EventArgs e)
{
string x = Session["something"].ToString();
try
{
if (SaveButton.Text == "Save")
{
SqlCommand cmd = new SqlCommand();
String mycon = "Data Source=.; Initial Catalog=something; Integrated Security=True";
SqlConnection con = new SqlConnection(mycon);
cmd = new SqlCommand("spInsertCompany", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#CompanyName", SqlDbType.VarChar).Value = Name.Text;
cmd.Parameters.Add("#CompanyCode", SqlDbType.VarChar).Value = CompanyCode.Text;
cmd.Parameters.Add("#LegalName", SqlDbType.VarChar).Value = LegalName.Text;
cmd.Parameters.Add("#TaxID", SqlDbType.Int).Value = TaxID.Text;
cmd.Parameters.Add("#BusinessPhone", SqlDbType.VarChar).Value = BusinessPhone.Text;
cmd.Parameters.Add("#Extension", SqlDbType.VarChar).Value = Extension.Text;
cmd.Parameters.Add("#FaxNumber", SqlDbType.VarChar).Value = FaxNumber.Text;
cmd.Parameters.Add("#Description", SqlDbType.VarChar).Value = Description.Value;
bool isstatus = IsActiveCheckBox.Checked;
cmd.Parameters.Add("#Status", SqlDbType.Int).Value = Convert.ToInt32(isstatus);
con.Open();
cmd.Connection = con;
cmd.ExecuteNonQuery();
Response.Write("<script language='javascript'>window.alert('Saved Successfully.');window.location='Company.aspx';</script>");
}
else if (SaveButton.Text == "Update")
{
SqlCommand cmd = new SqlCommand();
String mycon = "Data Source=.; Initial Catalog=something; Integrated Security=True";
SqlConnection con = new SqlConnection(mycon);
con.Open();
cmd = new SqlCommand("spUpdateCompany", con);
cmd.CommandType = CommandType.StoredProcedure;
int a = Convert.ToInt32(Companyid);
// I need the value here but it is being updated to zero here.
cmd.Parameters.Add("#CompanyID", SqlDbType.Int).Value = Companyid;
cmd.Parameters.Add("#CompanyName", SqlDbType.VarChar).Value = Name.Text;
cmd.Parameters.Add("#CompanyCode", SqlDbType.VarChar).Value = CompanyCode.Text;
cmd.Parameters.Add("#BusinessPhone", SqlDbType.VarChar).Value = BusinessPhone.Text;
cmd.Parameters.Add("#Extension", SqlDbType.VarChar).Value = Extension.Text;
cmd.Parameters.Add("#FaxNumber", SqlDbType.VarChar).Value = FaxNumber.Text;
cmd.Parameters.Add("#TaxID", SqlDbType.Int).Value = TaxID.Text;
cmd.Parameters.Add("#LegalName", SqlDbType.VarChar).Value = LegalName.Text;
cmd.ExecuteNonQuery();
cmd.Dispose();
con.Close();
Response.Write("<script language='javascript'>window.alert('Updated Successfully.');window.location='Company.aspx';</script>");
}
}
catch (SqlException ex)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message",
"alert('Oops!! following error occured : " + ex.Message.ToString() + "');", true);
}
}
protected void CancelButton_Click(object sender, EventArgs e)
{
Response.Redirect("Company.aspx");
}
private void BindTextBoxvalues()
{
SaveButton.Text = "Update";
string constr = "Data Source=.; Initial Catalog=something; Integrated Security=True";
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand("select * from Company where CompanyID=" + Companyid, con);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
Name.Text = dt.Rows[0][1].ToString();
CompanyCode.Text = dt.Rows[0][2].ToString();
LegalName.Text = dt.Rows[0][15].ToString();
TaxID.Text = dt.Rows[0][14].ToString();
BusinessPhone.Text = dt.Rows[0][3].ToString();
Extension.Text = dt.Rows[0][13].ToString();
FaxNumber.Text = dt.Rows[0][12].ToString();
Description.Value = dt.Rows[0][4].ToString();
IsActiveCheckBox.Checked = Convert.ToBoolean(dt.Rows[0][11]);
}
}
Any values stored in local variables need to be read from Request on every postback.
So do following
int Companyid = 0;
string cmdName = null;
protected void Page_Load(object sender, EventArgs e)
{
Companyid = Convert.ToInt32(Request.QueryString["CompanyID"]);
cmdName = Request.QueryString["CommandType"];
if (!IsPostBack)
{
if (cmdName == "Details")// be sure about string case
{
BindTextBoxvalues();
}
}
}
Or make viewstate properties
If you want to have your property available on the PostBack, do not use !IsPostBack
protected void Page_Load(object sender, EventArgs e)
{
Companyid = Convert.ToInt32(Request.QueryString["CompanyID"]);
}

how to display image from database to image control in asp.net

i want to retrieve image from database but this code did not display any thing.
image data type in database is image.I dont know what is wrong with this code
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(Session["pro_ID"]);
int id = Convert.ToInt32(Session["pro_id"]);
SqlConnection conn = new SqlConnection("Data source=DESKTOP-QPTTS3M;initial catalog=shopolic;integrated security=True;");
conn.Open();
SqlCommand cmd = new SqlCommand("spgetimage", conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter param = new SqlParameter() { ParameterName = "#id", Value = Session["pro_id"] };
cmd.Parameters.Add(param);
//cmd.ExecuteScalar();
SqlCommand cmd2 = new SqlCommand("select *from product where product_ID='" + Session["pro_id"] + "'", conn);
// cmd2.ExecuteNonQuery();
SqlDataReader dr = cmd2.ExecuteReader();
if (dr.Read())
{
name.Text = dr["name"].ToString();
byte[] img = (byte[])(dr["image"]);
if (img == null)
{
Image1.ImageUrl = "~/Images/bg.png";
}
else
{
string base64String = Convert.ToBase64String(img);
Image1.ImageUrl = String.Format("data:image/jpg;base64,{0}", base64String);
// MemoryStream ms = new MemoryStream(img);
}
}
// byte[] bytes = (byte[])cmd.ExecuteScalar();
// string strbase64 = Convert.ToBase64String(bytes);
//Image1.ImageUrl = "data:Image/png;base64,"+strbase64;
//SqlDataReader dr = cmd.ExecuteReader();
//DataTable DT = new DataTable();
conn.Close();
}

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'";

Resources