I'm trying to do an add to cart function for my website but I'm getting an error when trying to convert a textbox number in to a value for visual studio to understand.
This is the error message:
(Link to full-size image)
This is my code
aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
public partial class ProductDetails : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
qtytxt.Attributes.Add("placeholder", "Your Quantity");
}
static readonly string scriptStockOut = "<script language=\"javascript\">\n" +
"alert (\"Sorry Stock Out! Please choose a smaller quantity or another product \");\n" +
"</script>";
static readonly string scriptErrorLogin = "<script language=\"javascript\">\n" + "alert (\"Please login or create account first to facilitate buying\");\n</script>";
protected void atcbtn_Click(object sender, EventArgs e)
{
string strProductId, strSQL;
int intQuantityOnHand, intBuyQuantity, newQty, intOrderNo;
decimal decUnitPrice;
if ((string)Session["sFlag"] != "T")
{
Type csType = this.GetType();
ClientScript.RegisterStartupScript(csType, "Error", scriptErrorLogin); return;
}
SqlConnection sqlCon = new SqlConnection(#"Data Source=teafamily;Initial Catalog=BolsenF1;Integrated Security=True;MultipleActiveResultSets=true;");
sqlCon.Open();
Type csTypee = this.GetType();
SqlCommand sqlcmd;
SqlDataReader rdr;
string strSQLSelect = "SELECT pProductID FROM Products";
sqlcmd = new SqlCommand(strSQLSelect, sqlCon);
rdr = sqlcmd.ExecuteReader();
DetailsViewRow row0 = DetailsView1.Rows[0];
strProductId = row0.Cells[1].Text;
strSQLSelect = "SELECT pQty FROM Products WHERE pProductID=#ProductID";
sqlcmd = new SqlCommand(strSQLSelect, sqlCon);
sqlcmd.Parameters.AddWithValue("#ProductID", strProductId);
object oQty = sqlcmd.ExecuteScalar();
intQuantityOnHand = (int)oQty;
strSQLSelect = "SELECT pPrice FROM Products WHERE pProductID=#ProductID";
sqlcmd = new SqlCommand(strSQLSelect, sqlCon);
sqlcmd.Parameters.AddWithValue("#ProductID", strProductId);
object oUnitPrice = sqlcmd.ExecuteScalar();
decUnitPrice = (decimal)oUnitPrice;
intBuyQuantity = int.Parse(qtytxt.ToString());
newQty = intQuantityOnHand - intBuyQuantity;
if (intQuantityOnHand < intBuyQuantity)
{
Type csType = this.GetType();
ClientScript.RegisterStartupScript(csType, "StockOut", scriptStockOut);
}
Session["sProductId"] = strProductId;
Session["sUnitPrice"] = decUnitPrice.ToString();
Session["sQuantity"] = newQty.ToString();
intOrderNo = (int)Session["sOrderNo"];
strSQL = "INSERT INTO orderItems(iOrderNo,iProductID, iQty, iUnitPrice)"
+ "VALUES (#OrderNo, #ProductID, #Qty, #UnitPrice)";
sqlcmd = new SqlCommand(strSQL, sqlCon);
sqlcmd.Parameters.AddWithValue("#OrderNo", intOrderNo);
sqlcmd.Parameters.AddWithValue("#ProductID", strProductId);
sqlcmd.Parameters.AddWithValue("#Qty", intBuyQuantity);
sqlcmd.Parameters.AddWithValue("#UnitPrice", decUnitPrice);
sqlcmd.ExecuteNonQuery();
strSQL = "UPDATE Products SET pQty=#NewQty WHERE pProductID = #ProductID";
sqlcmd = new SqlCommand(strSQL, sqlCon);
sqlcmd.Parameters.AddWithValue("#NewQty", newQty);
sqlcmd.Parameters.AddWithValue("#ProductID", strProductId);
sqlcmd.ExecuteNonQuery();
sqlCon.Close();
Response.Redirect("ShoppingCart.aspx");
}
}
I assume that qtytxt is a TextBox. If it is the case, you must use qtytxt.Text to access its text/value. The Text property of a TextBox contains its "user provided"/posted value.
So you should write :
intBuyQuantity = int.Parse(qtytxt.Text);
Don't forget to specify the expected CultureInfo to the appropriate int.Parse() method overload if necessary.
Related
For a program I'm making, I want to add the countrycode, the zipcode of the city and the name of the city in a table. If this information is already in the table, nothing needs to happen.
However, new records won't insert in my table.
For example: with only 'BE, '3580', 'Beringen' in my table. I start my program.
First I insert the values that are already in my table and nothing happends.
Second I try to add a new value (for example: ('BE' '3500', 'Hasselt')). I get the messagebox with: "Data added succesfully!".
After that, I try to add the same value as before ('BE' '3500', 'Hasselt'). My program does nothing.
But when I open Access, to take a look in the table. No new data was added.
What did I do wrong?
connection.ConnectionString = #"Provider = Microsoft.Jet.OLEDB.4.0; Data Source = DeJongDatabase.mdb; Persist Security Info = True";
This is the rest of my code
static class Zipcodes
{
public static void checkAndSavePostCode(String country, String zipcode, string city)
{
Globals.connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = Globals.connection;
command.CommandText = string.Format("SELECT * FROM Zipcodes WHERE CountryCode = #countryCode AND City= #city AND Zipcode= #zipcode");
command.Parameters.AddWithValue("#countyCode", country);
command.Parameters.AddWithValue("#city", city);
command.Parameters.AddWithValue("#zipcode", zipcode);
OleDbDataReader postcodeReader = command.ExecuteReader();
bool exists = false;
while (postcodeReader.Read())
{
exists = true;
}
postcodeReader.Close();
command.Dispose();
Globals.connection.Close();
OleDbCommand writeCommand = new OleDbCommand();
writeCommand.Connection = Globals.connection;
try
{
Globals.connection.Open();
if (!exists)
{
if (Globals.connection.State == System.Data.ConnectionState.Open)
{
/*writeCommand.CommandText = "INSERT INTO Zipcodes(CountryCode, ZipCode, City) VALUES(#countryCode, #zipcode, #city)";
writeCommand.Parameters.AddWithValue("#countyCode", country);
writeCommand.Parameters.AddWithValue("#city", city);
writeCommand.Parameters.AddWithValue("#zipcode", zipcode); */
writeCommand.CommandText = "INSERT INTO Zipcodes(CountryCode, ZipCode, City) VALUES(?, ?, ?)";
writeCommand.Parameters.Add(new OleDbParameter("#countryCode", OleDbType.VarChar)).Value = country;
writeCommand.Parameters.Add(new OleDbParameter("#zipcode", OleDbType.VarChar)).Value = zipcode;
writeCommand.Parameters.Add(new OleDbParameter("#city", OleDbType.VarChar)).Value = city;
if (writeCommand.ExecuteNonQuery() > 0)
{
MessageBox.Show("Data saved successfuly...!");
}
}
else
{
MessageBox.Show("FAILED");
}
}
}
catch(OleDbException ex)
{
MessageBox.Show(ex.Source);
MessageBox.Show(ex.ToString());
}
finally
{
Globals.connection.Close();
}
This works fine for me.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OleDbConnection conn;
conn = new OleDbConnection(#"Provider=Microsoft.Jet.OleDb.4.0;Data Source=C:\Users\your_path_here\Northwind.mdb");
conn.Open();
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandText = #"INSERT INTO MyExcelTable([Fname], [Lname], [Address])VALUES('" + textBox1.Text + "', '" + textBox2.Text + "','" + textBox3.Text + "')";
cmd.ExecuteNonQuery();
conn.Close();
}
public OleDbConnection myCon { get; set; }
private void button2_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Ryan\Desktop\Coding\Microsoft Access\Northwind.mdb";
string fstName = textBox1.Text.Trim();
string lstName = textBox2.Text.Trim();
string adres = textBox3.Text.Trim();
OleDbCommand cmd = new OleDbCommand(#"INSERT INTO MyExcelTable (FName, LName, Address) VALUES (#FName, #LName, #Address)")
{
Connection = conn
};
conn.Open();
if (conn.State == ConnectionState.Open)
{
// you should always use parameterized queries to avoid SQL Injection
cmd.Parameters.Add("#FName", OleDbType.VarChar).Value = fstName;
cmd.Parameters.Add("#LName", OleDbType.VarChar).Value = lstName;
cmd.Parameters.Add("#Address", OleDbType.VarChar).Value = adres;
try
{
cmd.ExecuteNonQuery();
MessageBox.Show(#"Data Added");
conn.Close();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Source + "\n" + ex.Message);
conn.Close();
}
}
else
{
MessageBox.Show(#"Connection Failed");
}
}
}
}
I am using .ashx file for ImageHandler.
The is the error message that I received An exception of type 'System.InvalidOperationException' occurred in System.Data.dll but was not handled in user code
Additional information: Invalid attempt to read when no data is present.
This part showing the error
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
context.Response.ContentType = dr["Image_Type"].ToString();
context.Response.BinaryWrite((byte[])dr["Profile_Picture"]);
dr.Close();
This is my ImageHandler.ashx:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.IO;
public class ImageHandler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
SqlConnection myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["Register"].ConnectionString);
myConnection.Open();
string sql = "Select Profile_Picture, Image_Type from Member where Login_Id=#Name";
SqlCommand cmd = new SqlCommand(sql, myConnection);
cmd.Parameters.Add("#Name", SqlDbType.NVarChar).Value = context.Request.QueryString["Login_Id"];
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
context.Response.ContentType = dr["Image_Type"].ToString();
context.Response.BinaryWrite((byte[])dr["Profile_Picture"]);
dr.Close();
myConnection.Close();
}
public bool IsReusable {
get {
return false;
}
}
}
This is my UpdateProfile.aspx.cs:
protected void btnSave_Click(object sender, EventArgs e)
{
string constr = ConfigurationManager.ConnectionStrings["Register"].ConnectionString;
string filename = Path.GetFileName(fuProfilePicture.PostedFile.FileName);
string contentType = fuProfilePicture.PostedFile.ContentType;
using (Stream fs = fuProfilePicture.PostedFile.InputStream)
{
using (BinaryReader br = new BinaryReader(fs))
{
byte[] bytes = br.ReadBytes((Int32)fs.Length);
using (SqlConnection con1 = new SqlConnection(constr))
{
string query1 = "Update Member Set Name = #name,
Email = #email, Phone_Number = #phonenumber,
Gender = gender, Date_Of_Birth = #dob,
Password = #password, Login_Id = #loginid,
Student_ID = #studentid,
Profile_Picture = #profilepicture
WHERE Login_Id = '" + Request.QueryString["Login_Id"] + "'";
using (SqlCommand cmd1 = new SqlCommand(query1))
{
cmd1.Connection = con1;
cmd1.Parameters.AddWithValue("#imagename", filename);
cmd1.Parameters.AddWithValue("#imagetype", contentType);
cmd1.Parameters.AddWithValue("#profilepicture", bytes);
cmd1.Parameters.AddWithValue("#name", txtName.Text);
cmd1.Parameters.AddWithValue("#email", txtEmail.Text);
cmd1.Parameters.AddWithValue("#phonenumber", txtContactNumber.Text);
cmd1.Parameters.AddWithValue("#gender", ddlGender.SelectedItem.ToString());
cmd1.Parameters.AddWithValue("#dob", ddlDay.SelectedItem.ToString() + "/" + ddlMonth.SelectedItem.ToString() + "/" + txtYear.Text);
cmd1.Parameters.AddWithValue("#password", txtPassword.Text);
cmd1.Parameters.AddWithValue("#loginid", txtUsername.Text);
cmd1.Parameters.AddWithValue("#studentid", txtStudentID.Text);
con1.Open();
cmd1.ExecuteNonQuery();
con1.Close();
}
}
}
}
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("<script type = 'text/javascript'>");
sb.Append("window.onload=function(){");
sb.Append("alert('");
sb.Append("Update Successfuly!");
sb.Append("')};");
sb.Append("</script>");
ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", sb.ToString());
}
}
Maybe because you forget the # sign on gender:
Phone_Number = #phonenumber, Gender = gender,
I want to use the function "MyPlaces". What should I use instead of commandType.StoredProcedure
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string connStr = ConfigurationManager.ConnectionStrings["MyDbConn"].ToString();
SqlConnection conn = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand("MyPlaces", conn);
cmd.CommandType = CommandType.StoredProcedure; //This part gives me an error
string email = Session["oldemailuser"].ToString();
cmd.Parameters.Add(new SqlParameter("#email", email));
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
string s = "<br />";
while (rdr.Read())
{
string name = s + " " + rdr.GetString(rdr.GetOrdinal("name"))
+ " located in ";
string location = rdr.GetString(rdr.GetOrdinal("location"))
+ "  ";
Label lbl_name = new Label();
lbl_name.Text = email;
form1.Controls.Add(lbl_name);
Label lbl_location = new Label();
lbl_location.Text = email;
form1.Controls.Add(lbl_location);
}
}
Hope your sql function name is "Myplaces".If So,Then Modify your code with this :
string email = Session["oldemailuser"].ToString();
SqlConnection conn = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand(conn);
cmd.CommandText = "SELECT MyPlaces(#email)";
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add(new SqlParameter("#email", email));
conn.Open();
I have three textbox in the web form, which is username, password and IC number that the user have to enter to register. if the IC number the person entered, matches the IC value of any record in the database, it will update the username and password that the person have typed into the username field and password field of that record that have the matching IC. The updating part is fine but What I would want to do is if the record in the database for username and password of the nric entered is filled up, I would like to have a error in a label saying that this NRIC already have a username and password. Help
Etc, If I entered S9583728F in the NRIC box, and want to register a account, but since in my table S9583728F already have a username and password which is settsser and ddddd, I want it to give me, this NRIC already have a username and password.
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.SqlClient;
using System.Configuration;
using System.Data;
using System.Web.Security;
using System.Globalization;
using System.Text;
using System.Threading;
public partial class register : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnCreate_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["sacpConnectionString"].ConnectionString))
{
try
{
SqlCommand cmd = new SqlCommand();
Guid guid;
guid = Guid.NewGuid();
string sql = #"UPDATE patient
SET
pUserName = #pUserName,
pPassword = #pPassword
WHERE pIC = #pIC";
cmd.Parameters.AddWithValue("#pIC", txtIC.Value);
cmd.Parameters.AddWithValue("#pUsername", txtUsername.Value);
cmd.Parameters.AddWithValue("#pPassword", txtPassword.Value);
cmd.Connection = con;
cmd.CommandText = sql;
con.Open();
cmd.ExecuteNonQuery();
cmd.CommandText = "SELECT patientID, pUsername, pPassword FROM patient WHERE pIC = #pIC;";
int id = (cmd.ExecuteScalar() != null) ? Convert.ToInt32(cmd.ExecuteScalar()) : 0;
if (id > 0)
{
Session.Add("ID", id);
Session.Add("Username", txtUsername.Value);
Session.Add("Password", txtPassword.Value);
FormsAuthentication.SetAuthCookie(txtUsername.Value, true);
Response.Redirect("registered.aspx");
}
else
{
lblErrorMessage.Text = "IC does not exist";
}
}
/*
catch (Exception)
{
lblErrorMessage.Text = "IC does not exist";
}
*/
finally
{
con.Close();
}
}
}
}
}
Just change your UPDATE Query as below:
string sql = #"UPDATE patient
SET
pUserName = #pUserName,
pPassword = #pPassword
WHERE pIC = #pIC and pUserName='' and pPassword =''";
Solution 2: write a seperate function and continue with UPDATE if it returns false else display warning message.
boolean IsIDExist()
{
SqlCommand cmd = new SqlCommand();
string sql = #"SELECT count(*) from patient
WHERE pIC = #pIC" and pUserName!='' and pPassword !=''";
cmd.Parameters.AddWithValue("#pIC", txtIC.Value);
cmd.Connection = con;
cmd.CommandText = sql;
con.Open();
if(Convert.ToInte32(cmd.ExecuteScalar())>0)
return true;
return false;
}
Complete Code:
boolean IsIDExist()
{
SqlCommand cmd = new SqlCommand();
string sql = #"SELECT count(*) from patient
WHERE pIC = #pIC" and pUserName!='' and pPassword !=''";
cmd.Parameters.AddWithValue("#pIC", txtIC.Value);
cmd.Connection = con;
cmd.CommandText = sql;
con.Open();
if(Convert.ToInte32(cmd.ExecuteScalar())>0)
return true;
return false;
}
if (Page.IsValid)
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["sacpConnectionString"].ConnectionString))
{
try
{
SqlCommand cmd = new SqlCommand();
Guid guid;
guid = Guid.NewGuid();
string sql = #"UPDATE patient
SET
pUserName = #pUserName,
pPassword = #pPassword
WHERE pIC = #pIC and pUserName='' and pPassword=''";
cmd.Parameters.AddWithValue("#pIC", txtIC.Value);
cmd.Parameters.AddWithValue("#pUsername", txtUsername.Value);
cmd.Parameters.AddWithValue("#pPassword", txtPassword.Value);
cmd.Connection = con;
cmd.CommandText = sql;
con.Open();
cmd.ExecuteNonQuery();
if (!IsIDExist())
{
Session.Add("ID", id);
Session.Add("Username", txtUsername.Value);
Session.Add("Password", txtPassword.Value);
FormsAuthentication.SetAuthCookie(txtUsername.Value, true);
Response.Redirect("registered.aspx");
}
else
{
lblErrorMessage.Text = "IC Already Exist";
}
}
/*
catch (Exception)
{
lblErrorMessage.Text = "IC does not exist";
}
*/
finally
{
con.Close();
}
}
}
On Registration page I have the error
"C# .net ExecuteNonQuery: CommandText property has not been initialized"
But If I give comments to "cmd.ExecuteNonQuery" on Registration page the this error goes to login page. I am unable to register and login on this.
Login Page:
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;
using System.Security;
using System.Web.Security;
public partial class Login : System.Web.UI.Page
{
//SqlConnection con = new SqlConnection("Data Source=LENOVO;Initial Catalog=Onl9Shopping;Persist Security Info=True;User ID=sa;Password=123");
SqlConnection con = new SqlConnection("Data Source=localhost;Initial Catalog=Onl9Shopping;Trusted_Connection=Yes;;Pooling=False");
protected void Page_Load(object sender, EventArgs e)
{
}
protected void ImageButton4_Click(object sender, ImageClickEventArgs e)
{
SqlCommand cmd = new SqlCommand();
cmd.CommandText="checksecurity ";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
con.Open();
cmd.Parameters.AddWithValue("#username", Txtusername.Text);
cmd.Parameters.AddWithValue("#password", Txtpassword.Text);
SqlParameter p1 = new SqlParameter("#ret", SqlDbType.Int);
p1.Direction = ParameterDirection.ReturnValue;
cmd.Parameters.Add(p1);
SqlParameter p2 = new SqlParameter("#status", SqlDbType.VarChar, 50);
p2.Direction = ParameterDirection.Output;
cmd.Parameters.Add(p2);
SqlParameter p3 = new SqlParameter("#name", SqlDbType.VarChar, 50);
p3.Direction = ParameterDirection.Output;
cmd.Parameters.Add(p3);
cmd.ExecuteNonQuery();
int r = Convert.ToInt16(cmd.Parameters["#ret"].Value);
string status = cmd.Parameters["#status"].Value.ToString();
string loggedname = cmd.Parameters["#name"].Value.ToString();
if (r == -1)
{
Label1.Text = "Wrong Username";
}
else if (r == -2)
{
Label1.Text = "wrong Password";
}
else
{
Session["name"] = loggedname;
FormsAuthenticationTicket tk = new FormsAuthenticationTicket(1, Txtusername.Text, DateTime.Now, DateTime.Now.AddHours(2), false, status);
string s = FormsAuthentication.Encrypt(tk);
HttpCookie ck = new HttpCookie(FormsAuthentication.FormsCookieName,s);
Response.Cookies.Add(ck);
Response.Redirect("Welcome.aspx");
}
Label1.Visible = true;
}
}
Registration Page:
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 Registartion : System.Web.UI.Page
{
SqlConnection con = new SqlConnection("Data Source=localhost;Initial Catalog=Onl9Shopping;Trusted_Connection=Yes");
protected void Page_Load(object sender, EventArgs e)
{
}
private void getregno()
{
string query = "select max (registrationno) from register";
SqlDataAdapter adp = new SqlDataAdapter(query, con);
DataSet ds = new DataSet();
adp.Fill(ds);
Txtreg.Text = (Convert.ToInt16(ds.Tables[0].Rows[0][0]) + Convert.ToInt16(1)).ToString();
}
protected void btncheck_Click(object sender, EventArgs e)
{
string query = "select username from register";
SqlDataAdapter adp = new SqlDataAdapter(query, con);
DataSet ds = new DataSet();
adp.Fill(ds);
int b = 0;
int c = 0;
int a = 0;
a = ds.Tables[0].Rows.Count;
while (a > b)
{
if (ds.Tables[0].Rows[b][0].ToString().Equals(TxtUserName.Text))
{
c = 1;
}
b++;
}
if (c == 1)
{
Label1.Text = "Name already exist !!..";
}
else
{
Label1.Text = "Name available";
}
Label1.Visible=true;
}
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
string query = "select username from register";
SqlDataAdapter adp = new SqlDataAdapter(query, con);
DataSet ds = new DataSet();
adp.Fill(ds);
int b = 0;
int c = 0;
int a = 0;
a = ds.Tables[0].Rows.Count;
while (a > b)
{
if (ds.Tables[0].Rows[b][0].ToString().Equals(TxtUserName.Text))
{
c = 1;
}
b++;
}
if (c == 1)
{
Label1.Text = "Name already exist !!..";
}
else
{
SqlCommand cmd = new SqlCommand();
string query1 = "Insert into register(Name,FatherName,Gender,Address,Country,State,City,Pin,Phn,Email,Username,Password,SecurityQuestion,Hint)values(#Name,#Fathername,#Gender,#Address,#Country,#State,#City,#Pin,#Phn,#Email,#Username,#Password,#SecurityQuestion,#Hint)";
cmd.CommandText = query1;
cmd.Connection = con;
con.Open();
cmd.Parameters.AddWithValue("#Name", Txtname.Text);
cmd.Parameters.AddWithValue("#FatherName", Txtfname.Text);
cmd.Parameters.AddWithValue("#Gender", DropDownList1.Text);
cmd.Parameters.AddWithValue("#Address", Txtaddress.Text);
cmd.Parameters.AddWithValue("#Country", Txtcountry.Text);
cmd.Parameters.AddWithValue("#State", Txtstate.Text);
cmd.Parameters.AddWithValue("#City", Txtcity.Text);
cmd.Parameters.AddWithValue("#Pin", Txtpin.Text);
cmd.Parameters.AddWithValue("#Phn", Txtphn.Text);
cmd.Parameters.AddWithValue("#Email", Txtemail.Text);
cmd.Parameters.AddWithValue("#Username", TxtUserName.Text);
cmd.Parameters.AddWithValue("#Password", Txtpassword.Text);
cmd.Parameters.AddWithValue("#SecurityQuestion", DropDownList2.Text);
cmd.Parameters.AddWithValue("#Hint", Txthint.Text);
cmd.ExecuteNonQuery();
cmd.Dispose();
con.Close();
Txtname.Text = string.Empty;
Txtfname.Text = string.Empty;
Txtaddress.Text = string.Empty;
Txtcountry.Text = string.Empty;
Txtstate.Text = string.Empty;
Txtcity.Text = string.Empty;
Txtpin.Text = string.Empty;
Txtphn.Text = string.Empty;
Txtemail.Text = string.Empty;
TxtUserName.Text = string.Empty;
Txtpassword.Text = string.Empty;
Txtaddress.Text = string.Empty;
Txthint.Text = string.Empty;
Label2.Text = "Data sumitted ";
Label2.Visible = true;
}
}
}
There no commandtype for the click event for ImageButton1:
SqlCommand cmd = new SqlCommand();
string query1 = "Insert intoregister(Name,FatherName,Gender,Address,Country,State,City,Pin,Phn,Email,Username,Password,SecurityQuestion,Hint)values(#Name,#Fathername,#Gender,#Address,#Country,#State,#City,#Pin,#Phn,#Email,#Username,#Password,#SecurityQuestion,#Hint)";
cmd.CommandText = query1;
cmd.CommandType=CommandType.Text;
cmd.Connection = con;
con.Open();
Had the same issue today. You get this exception when the user you are using doesn't have the permissions to use the database. For testing it, you can login with the user using MS SQL Management Studio, and try to execute the query.
Check which groups the user is assigned to, make it a db_owner f.e., and check that it does not belong to db_denydatareader or db_denydatawriter