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
Related
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.
c# asp.net - inserting data into database( dont knw where iam goin wrong) - this code is executing but not working at all ! i tried to feed data through the website i created but it wont reflect it in my database at all plz help !!!!
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
SqlConnection con = new SqlConnection("Data Source=GARGI-PC\\ROOT;Initial Catalog=master;Integrated Security=True");
protected void page_load(object sender, EventArgs e)
{}
public void refress()
{
comment1.Text = "";
software1.Checked = true;
hardware1.Checked = false;
both1.Checked = false;
others.Checked = false;
}
protected void btn(object sender, EventArgs e)
{
string type = string.Empty ;
if (hardware1.Checked == true)
{
type = "hardware";
}
if (software1.Checked == true)
{
type = "software";
}
if (both1.Checked == true)
{
type = "both";
}
if (others.Checked == true)
{
type = "others";
}
SqlCommand cmd = new SqlCommand("insert into main_page (type, discription,time) values('" + type + "','" + comment1.Text + "','" + "','"+"now()')", con);
cmd.CommandType = CommandType.Text;
try
{
con.Open();
cmd.ExecuteNonQuery();
con.Close();
refress();
}
catch (Exception ex)
{
}
}
public void btn_clear(object sender, EventArgs e)
{
refress();
}
}
Looks like you have a double comma in your INSERT statement.
+ "','" + "','"
The INSERT statement should look like:
INSERT INTO main_page (type, description, time) VALUES ('Type', 'Description', NOW())
Also you are vulnerable to SQL injection, you should paramerterize your queries for all of your inputs rather than trusting the data from your users. As a basic example:
MySqlCommand command = new MySqlCommand("INSERT INTO main_page (Description) VALUES #Description");
command.Parameters.AddWithValue("#Description", comment1.Text);
This would protect you if a user entered a SQL statement within the Comment1 textbox.
ArbitaryData; DROP TABLE main_page;
You really should use the command parameters. Here, try this as an example:
public static void AddSong(Songs s)
{
using (SqlConnection sqlcon = new SqlConnection(SQL_getConnectionString.conStr()))
{
sqlcon.Open();
try
{
string query = "INSERT INTO Songs VALUES(#Id, #Name, #Artist, #Album, #TrackNumber, #TrackNumberCount, " +
"#Genre, #Rating, #Tags, #Subject, #Categories, #Comments, #FileName, #FolderName, #FolderPath, " +
"#FullPath, #Length, #PlayCount, #SkipCount, #LastPlayed)";
using (SqlCommand cmd = new SqlCommand(query, sqlcon))
{
cmd.Parameters.Add("#Id", SqlDbType.Int).Value = s.Id;
cmd.Parameters.Add("#Name", SqlDbType.VarChar, 250).Value = s.Name;
cmd.Parameters.Add("#Album", SqlDbType.VarChar, 250).Value = s.Album;
cmd.Parameters.Add("#Artist", SqlDbType.VarChar, 250).Value = s.Artist;
cmd.Parameters.Add("#TrackNumber", SqlDbType.Int).Value = s.TrackNumber;
cmd.Parameters.Add("#TrackNumberCount", SqlDbType.Int).Value = s.TrackNumberCount;
cmd.Parameters.Add("#Genre", SqlDbType.VarChar, 500).Value = s.Genre;
cmd.Parameters.Add("#Rating", SqlDbType.Int).Value = s.Rating;
cmd.Parameters.Add("#Tags", SqlDbType.VarChar, 500).Value = s.Tags;
cmd.Parameters.Add("#Subject", SqlDbType.VarChar, 500).Value = s.Subject;
cmd.Parameters.Add("#Categories", SqlDbType.VarChar, 500).Value = s.Categories;
cmd.Parameters.Add("#Comments", SqlDbType.VarChar, -1).Value = s.Comments;
cmd.Parameters.Add("#FileName", SqlDbType.VarChar, 500).Value = s.FileName;
cmd.Parameters.Add("#FolderName", SqlDbType.VarChar, 500).Value = s.FolderName;
cmd.Parameters.Add("#FolderPath", SqlDbType.VarChar, -1).Value = s.FolderPath;
cmd.Parameters.Add("#FullPath", SqlDbType.VarChar, -1).Value = s.FullPath;
cmd.Parameters.Add("#Length", SqlDbType.VarChar, 50).Value = s.Length;
cmd.Parameters.Add("#PlayCount", SqlDbType.Int).Value = s.PlayCount;
cmd.Parameters.Add("#SkipCount", SqlDbType.Int).Value = s.SkipCount;
cmd.Parameters.Add("#LastPlayed", SqlDbType.VarChar, 50).Value = s.LastPlayed;
int rows = cmd.ExecuteNonQuery();
sqlcon.Close();
}
}
catch (Exception ex)
{
Console.WriteLine("Could not insert. {0}", s.Name);
Console.WriteLine("Error Message {0}", ex.Message);
}
}
}
How to achieve the requirements below:
The Retrieve button click event:
if user doesn't enter CustID in txtCustID need to inform them to enter Customer Id via lblMessage;
if entered CustId doesn't exist in database inform user that it doesn't exist via lblMessage.
The Update button click event - need to ensure that Customer ID already exists in the database.
The Delete button click event: same requirements as for Retrieve button.
I must use error/exception handling (try-catch) to achieve these (project requirement). I spent hours trying, but no success. I would be very grateful for some help! My code is below:
namespace ACME
{
public partial class Customer : System.Web.UI.Page
{
SqlConnection conn;
SqlDataAdapter adapter = new SqlDataAdapter();
DataTable table = new DataTable();
SqlCommand command = new SqlCommand();
protected void Page_Load(object sender, EventArgs e)
{
conn = new SqlConnection(ConfigurationManager.
ConnectionStrings["dbConnection1"].ConnectionString);
}
private void Page_PreInit(object sender, EventArgs e)
{
HttpCookie setTheme = Request.Cookies.Get("UserSelectedTheme");
if (setTheme != null)
{
Page.Theme = setTheme.Value;
}
}
protected void Clear()
{
txtCustID.Text = "";
txtFirstname.Text = "";
txtSurname.Text = "";
rbtGender.SelectedValue = "";
txtAge.Text = "";
txtAddress1.Text = "";
txtAddress2.Text = "";
txtCity.Text = "";
txtPhone.Text = "";
txtMobile.Text = "";
txtEmail.Text = "";
txtEmail2.Text = "";
}
protected void btnNew_Click(object sender, EventArgs e)
{
SqlDataAdapter adapter1 = new SqlDataAdapter();
DataTable table1 = new DataTable();
SqlCommand command1 = new SqlCommand();
Clear();
conn = new SqlConnection(ConfigurationManager.
ConnectionStrings["dbConnection1"].ConnectionString);
command1.Connection = conn;
command1.CommandType = CommandType.StoredProcedure;
command1.CommandText = "LargestCustID";
command1.Connection.Open();
int id = (int)command1.ExecuteScalar() + 1;
txtCustID.Text = id.ToString();
command1.Dispose();
conn.Close();
}
protected void btnAdd_Click(object sender, EventArgs e)
{
conn = new SqlConnection(ConfigurationManager.
ConnectionStrings["dbConnection1"].ConnectionString);
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "AddCustomer";
command.Connection.Open();
command.Parameters.AddWithValue("#CustID",
int.Parse(txtCustID.Text));
command.Parameters.AddWithValue("#Firstname", txtFirstname.Text);
command.Parameters.AddWithValue("#Surname", txtSurname.Text);
command.Parameters.AddWithValue("#Gender", rbtGender.SelectedValue);
command.Parameters.AddWithValue("#Age", int.Parse(txtAge.Text));
command.Parameters.AddWithValue("#Address1", txtAddress1.Text);
command.Parameters.AddWithValue("#Address2", txtAddress2.Text);
command.Parameters.AddWithValue("#City", txtCity.Text);
command.Parameters.AddWithValue("#Phone", txtPhone.Text);
command.Parameters.AddWithValue("#Mobile", txtMobile.Text);
command.Parameters.AddWithValue("#Email", txtEmail.Text);
adapter.InsertCommand = command;
adapter.InsertCommand.ExecuteNonQuery();
lblMessage.Text = "The new record has been added to the database!";
command.Connection.Close();
Clear();
}
protected void btnRetrieve_Click(object sender, EventArgs e)
{
conn = new SqlConnection(ConfigurationManager.
ConnectionStrings["dbConnection1"].ConnectionString);
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "GetCustID";
command.Connection.Open();
SqlParameter param = new SqlParameter();
param.ParameterName = "#CustID";
param.SqlDbType = SqlDbType.Int;
param.Direction = ParameterDirection.Input;
param.Value = int.Parse(txtCustID.Text);
command.Parameters.Add(param);
adapter.SelectCommand = command;
adapter.Fill(table);
int id = table.Rows.Count;
if (id == 0)
{
lblMessage.Text = "Customer ID does not exists!";
}
else
{
lblMessage.Text = "";
txtFirstname.Text = table.Rows[0].Field<string>("Firstname");
txtFirstname.DataBind();
txtSurname.Text = table.Rows[0].Field<string>("Surname");
txtSurname.DataBind();
txtAge.Text = table.Rows[0].Field<int>("Age").ToString();
txtAge.DataBind();
txtAddress1.Text = table.Rows[0].Field<string>("Address1");
txtAddress1.DataBind();
txtAddress2.Text = table.Rows[0].Field<string>("Address2");
txtAddress2.DataBind();
txtCity.Text = table.Rows[0].Field<string>("City");
txtCity.DataBind();
txtPhone.Text = table.Rows[0].Field<string>("Phone");
txtPhone.DataBind();
txtMobile.Text = table.Rows[0].Field<string>("Mobile");
txtMobile.DataBind();
txtEmail.Text = table.Rows[0].Field<string>("Email");
txtEmail.DataBind();
}
command.Connection.Close();
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
conn = new SqlConnection(ConfigurationManager.
ConnectionStrings["dbConnection1"].ConnectionString);
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "UpdateCustomer";
command.Connection.Open();
command.Parameters.AddWithValue("#CustID",
int.Parse(txtCustID.Text));
command.Parameters.AddWithValue("#Firstname", txtFirstname.Text);
command.Parameters.AddWithValue("#Surname", txtSurname.Text);
command.Parameters.AddWithValue("#Gender", rbtGender.SelectedValue);
command.Parameters.AddWithValue("#Age", int.Parse(txtAge.Text));
command.Parameters.AddWithValue("#Address1", txtAddress1.Text);
command.Parameters.AddWithValue("#Address2", txtAddress2.Text);
command.Parameters.AddWithValue("#City", txtCity.Text);
command.Parameters.AddWithValue("#Phone", txtPhone.Text);
command.Parameters.AddWithValue("#Mobile", txtMobile.Text);
command.Parameters.AddWithValue("#Email", txtEmail.Text);
lblMessage.Text = "The record has been updated!";
command.Connection.Close();
Clear();
}
protected void btnDelete_Click(object sender, EventArgs e)
{
try
{
conn = new SqlConnection(ConfigurationManager.
ConnectionStrings["dbConnection1"].ConnectionString);
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "DeleteCustomer";
command.Connection.Open();
SqlParameter param = new SqlParameter();
param.ParameterName = "#CustID";
param.SqlDbType = SqlDbType.Int;
param.Direction = ParameterDirection.Input;
param.Value = int.Parse(txtCustID.Text);
command.Parameters.Add(param);
adapter.DeleteCommand = command;
adapter.DeleteCommand.ExecuteNonQuery();
int id = (int)param.Value;
command.Connection.Close();
}
catch (Exception ex)
{
lblMessage.Text += "Please enter Customer ID!";
}
try
{
lblMessage.Text = "";
SqlParameter param = new SqlParameter();
param.ParameterName = "#CustID";
param.SqlDbType = SqlDbType.Int;
param.Direction = ParameterDirection.Input;
param.Value = int.Parse(txtCustID.Text);
command.Parameters.Add(param);
adapter.DeleteCommand = command;
adapter.DeleteCommand.ExecuteNonQuery();
int id = table.Rows.Count;
id = (int)param.Value;
lblMessage.Text += "Customer record has been deleted";
command.Connection.Close();
}
catch (Exception ex)
{
lblMessage.Text = "Customer ID doesnot exists!";
}
Clear();
}
public string CustID { get; set; }
}
}
It sounds like you are trying to control flow of your application by use of exceptions. There are many reasons against this approach:
1) Code is difficult to understand and to debug.
2) Throwing exceptions in .Net is expensive.
3) If exception control flow of application how do you differentiate them from a real exceptions (thrown when something doesn't work as expected)?
If, on the other hand, you want to throw an exception when any of the scenarios you listed in the question happens then you can use standard .Net Exception class:
if (string.IsNullOrWhiteSpace(txtCustID.Text))
{
throw new Exception("Id not provided.");
}
Or you can create a custom exception to provide some more specific information:
public class IdNotProvidedException : Exception
{
public string MyCommandName { get; set; }
public IdNotProvidedException(string msg)
: base(msg)
{
}
public IdNotProvidedException(string msg, string myCommandName)
: base(msg)
{
this.MyCommandName = myCommandName;
}
}
And then you initialize and throw your custom exception.
Lastly, there are already places in your code, though not mentioned in your question, that are worth wrapping in a try...catch block. Basically, any place where you connect with the server may result in something unexpected (for instance, the server may not be available).
I have some problem with update and insert data in sql server database BUT I can select data from it. I'm using visual studio 2012 , sql server 2012.
Please help ,Thank a lot.
This is my connectionstring in app.config
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;`enter code here`
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace ProjectAppWIn
{
public partial class Refill : Form
{
ProjectAppWIn.Login.user s;
ProjectAppWIn.Home.userr r;
public string sa;
public string se;
public Refill(ProjectAppWIn.Login.user s1, ProjectAppWIn.Home.userr s2) //string user)
{
InitializeComponent();
s = s1;
// label2.Text = "Welcome : " + " " + (user);
sa = s.name;
//on which control you want to show the username....
label2.Text = "Welcome..." + s.name;
r = s2;
se = r.id;
textBox8.Text = r.id + "";
}
private void button1_Click(object sender, EventArgs e)
{
this.Hide();
Form targetform = new Login();
targetform.Show();
}
private void button2_Click(object sender, EventArgs e)
{
using (SqlConnection con1 = new SqlConnection("Data Source=KHUNP\\SQLEXPRESS;Initial Catalog=kmuttssc;User ID=sa;Password=db2admin;"))
{
if (textBox1.Text.Contains("g") || textBox1.Text.Contains("G") == true)
{
DataTable dte = new DataTable();
con1.Open();
SqlDataReader myRead = null;
//SqlCommand myCommand = new SqlCommand("select * from card,user where card.card_id='" + textBox1.Text + "'", con1);
SqlCommand myCom = new SqlCommand("select card_balance,card_id from card where guest_id = '" + textBox1.Text + "'", con1);
myRead = myCom.ExecuteReader();
while (myRead.Read())
{
textBox6.Text = (myRead["card_balance"].ToString());
textBoxcardid.Text = (myRead["card_id"].ToString());
//TextBox8.Text = (myReader[].ToString());
//DropDownListGender.SelectedItem.Text = (myReader["gender"].ToString());
//DropDownListMonth.Text = (myReader["birth"].ToString());
//DropDownListYear.Text = (myReader["birth"].ToString());
//TextBoxAddress.Text = (myReader["address"].ToString());
//TextBoxCity.Text = (myReader["city"].ToString());
//DropDownListCountry.SelectedItem.Text = (myReader["country"].ToString());
//TextBoxPostcode.Text = (myReader["postcode"].ToString());
//TextBoxEmail.Text = (myReader["email"].ToString());
//TextBoxCarno.Text = (myReader["carno"].ToString());
}
con1.Close();
//textBox5.Text = string.Empty;
//textBox7.Text = string.Empty;
// *****textBox8.Text = Session["id"] + "";
}
else
{
DataTable dt = new DataTable();
con1.Open();
SqlDataReader myReader = null;
//SqlCommand myCommand = new SqlCommand("select * from card,user where card.card_id='" + textBox1.Text + "'", con1);
SqlCommand myCommand = new SqlCommand("select u.user_id, u.user_fname, u.user_lname, c.user_id, c.card_balance,c.card_id from [user] u JOIN [card] c ON u.user_id = c.user_id where c.user_id = '" + textBox1.Text + "'", con1);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
textBox6.Text = (myReader["card_balance"].ToString());
textBox2.Text = (myReader["user_fname"].ToString());
textBox3.Text = (myReader["user_lname"].ToString());
textBoxcardid.Text = (myReader["card_id"].ToString());
}
con1.Close();
textBox5.Text = string.Empty;
textBox7.Text = string.Empty;
label9.Text = string.Empty;
// ****textBox8.Text = Session["id"] + "";
}//end using
}
}
private void button3_Click(object sender, EventArgs e)
{
textBox7.Text = (Convert.ToInt32(textBox5.Text) + Convert.ToInt32(textBox6.Text)).ToString();
using (SqlConnection con1 = new SqlConnection("Data Source=KHUNP\\SQLEXPRESS;Initial Catalog=kmuttssc;User ID=sa;Password=db2admin;"))
{
if (textBox1.Text.Contains("g") || textBox1.Text.Contains("G") == true)
{
DataTable dt = new DataTable();
con1.Open();
SqlDataReader myReader = null;
//SqlCommand myCommand = new SqlCommand("select * from card,user where card.card_id='" + TextBox1.Text + "'", con1);
SqlCommand myCommand = new SqlCommand("UPDATE card c join guest g on c.guest_id = g.guest_id SET c.card_balance = #card_balance,g.guest_status=#guest_status WHERE c.guest_id = '" + textBox1.Text + "'", con1);
myCommand.Parameters.Add("#card_balance", System.Data.SqlDbType.SmallInt);
//myCommand.Parameters.Add("#staff_id", System.Data.SqlDbType.SmallInt);
myCommand.Parameters["#card_balance"].Value = textBox7.Text;
//myCommand.Parameters["#staff_id"].Value = textBox8.Text;
myCommand.Parameters.AddWithValue("#guest_status", textBox9.Text);
//myCommand.Parameters["#staff_id"].Value = Session["];
try
{
myCommand.ExecuteNonQuery();
//TextBox1.Text = string.Empty;
//TextBox2.Text = string.Empty;
//TextBox3.Text = string.Empty;
//TextBox5.Text = string.Empty;
//TextBox6.Text = string.Empty;
using (SqlConnection conn = new SqlConnection("Data Source=KHUNP\\SQLEXPRESS;Initial Catalog=kmuttssc;User ID=sa;Password=db2admin;"))
{
SqlCommand cmd = new SqlCommand("INSERT INTO transactionc (tranc_total, card_id,staff_id,date) VALUES (#tranc_total, #staff_id,#card_id, #date)");
cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
cmd.Parameters.AddWithValue("#tranc_total", textBox5.Text);
cmd.Parameters.AddWithValue("#card_id", textBoxcardid.Text);
cmd.Parameters.AddWithValue("#staff_id",textBox8.Text);
cmd.Parameters.AddWithValue("#date", DateTime.Now);
//cmd.Parameters.AddWithValue("#Address", txtAddress.Text);
conn.Open();
cmd.ExecuteNonQuery();
}
label9.Text = "<b><big><big> Complete !!!</big></big> </b>";
}
catch
{
textBox7.Text = string.Empty;
label9.Text = "<b> <big> <big> Not Complete!!!</big> </big> </b>";
}
finally
{
con1.Close();
}
//myCommand.Parameters.AddWithValue("#card_balance", TextBox7.Text);
//myCommand.ExecuteNonQuery();
}
else
{
DataTable dt = new DataTable();
con1.Open();
SqlDataReader myReader = null;
//SqlCommand myCommand = new SqlCommand("select * from card,user where card.card_id='" + TextBox1.Text + "'", con1);
SqlCommand myCommand = new SqlCommand("UPDATE card set card_balance=#card_balance , WHERE user_id = '" + textBox1.Text + "'", con1);
myCommand.Parameters.Add("#card_balance", System.Data.SqlDbType.SmallInt);
//myCommand.Parameters.Add("#staff_id", System.Data.SqlDbType.SmallInt);
myCommand.Parameters["#card_balance"].Value = textBox7.Text;
//myCommand.Parameters["#staff_id"].Value = textBox8.Text;
//myCommand.Parameters.AddWithValue("#guest_status", TextBox9.Text);
//myCommand.Parameters["#staff_id"].Value = Session["];
try
{
myCommand.ExecuteNonQuery();
//TextBox1.Text = string.Empty;
//TextBox2.Text = string.Empty;
//TextBox3.Text = string.Empty;
//TextBox5.Text = string.Empty;
//TextBox6.Text = string.Empty;
using (SqlConnection conn = new SqlConnection("Data Source=KHUNP\\SQLEXPRESS;Initial Catalog=kmuttssc;User ID=sa;Password=db2admin;"))
{
SqlCommand cmd = new SqlCommand("INSERT INTO transactionc (tranc_total, card_id,staff_id, date) VALUES (#tranc_total, #card_id,#staff_id, #date)");
cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
cmd.Parameters.AddWithValue("#tranc_total", textBox5.Text);
cmd.Parameters.AddWithValue("#card_id", textBoxcardid.Text);
cmd.Parameters.AddWithValue("#staff_id", textBox8.Text);
cmd.Parameters.AddWithValue("#date", DateTime.Now);
//cmd.Parameters.AddWithValue("#Address", txtAddress.Text);
conn.Open();
cmd.ExecuteNonQuery();
}
label9.Text = "<b><big><big> Complete !!!</big></big> </b>";
}
catch
{
textBox7.Text = string.Empty;
label9.Text = "<b> <big> <big> Not Complete!!!</big> </big> </b>";
}
finally
{
con1.Close();
}
}
}
}
private void button5_Click(object sender, EventArgs e)
{
Form targetform = new Return(s, r);
targetform.Show();
this.Hide();
}
private void button6_Click(object sender, EventArgs e)
{
Form targetform = new Home1(s, r);
targetform.Show();
this.Hide();
}
}
}
I think you need to provide permission to your user. Go to your database and execute the below query:-
USE [DBName]
GO
EXEC sp_addrolemember N'db_datawriter', N'UserName'
GO
EXEC sp_addrolemember N'db_datareader', N'UserName'
There is one more approach to give the permsion which is by using the GRANT privilage.
I am trying to update my database table ExpenseManagement. But it is not Updated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
public partial class UserProfile : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
txtUserId.Text = Request.Cookies["txtUserName"].Value;
string con_string = #"data Source= 10.10.10.5; initial catalog= test; user= xx; password= xxxxxxxxx;";
SqlConnection con = new SqlConnection(con_string);
SqlCommand cmd = new SqlCommand("select FirstName, LastName, Password, EmailId, MobileNumber from ExpenseManagement where UserId ='"+txtUserId.Text+"'", con);
cmd.Parameters.AddWithValue("#UserId", txtUserId.Text);
con.Open();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
txtFirstName.Text = dt.Rows[0]["FirstName"].ToString();
txtLastName.Text = dt.Rows[0]["LastName"].ToString();
txtPassword.Text= dt.Rows[0]["Password"].ToString();
txtEmailId.Text = dt.Rows[0]["EmailId"].ToString();
txtMobileNumber.Text = dt.Rows[0]["MobileNumber"].ToString();
con.Close();
txtUserId.Enabled = false;
txtFirstName.Enabled=false;
txtLastName.Enabled=false;
txtPassword.Enabled = false;
txtEmailId.Enabled = false;
txtMobileNumber.Enabled = false;
btnUpdate.Visible = false;
}
protected void Button1_Click1(object sender, EventArgs e)
{
txtUserId.Enabled = true;
txtUserId.ReadOnly = true;
txtFirstName.Enabled = true;
txtLastName.Enabled = true;
txtPassword.Enabled = true;
txtMobileNumber.Enabled = true;
txtEmailId.Enabled = true;
btnUpdate.Visible = true;
btnEdit.Visible = false;
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
string con_string = #"data Source= 10.10.10.5; initial catalog= test; user= xx; password= xxxxxxxxx;";
SqlConnection con = new SqlConnection(con_string);
string qryUpdate = "Update ExpenseManagement set FirstName= #FirstName, LastName=#LastName, Password=#Password, EmailId=#EmailId,MobileNumber=#MobileNumber where UserId= #UserId";
SqlCommand cmd = new SqlCommand(qryUpdate, con);
cmd.Parameters.AddWithValue("#UserId", txtUserId.Text);
cmd.Parameters.AddWithValue("#FirstName", txtFirstName.Text);
cmd.Parameters.AddWithValue("#LastName", txtLastName.Text);
cmd.Parameters.AddWithValue("#Password", txtPassword.Text);
cmd.Parameters.AddWithValue("#EmailId", txtEmailId.Text);
cmd.Parameters.AddWithValue("#MobileNumber", txtMobileNumber.Text);
con.Open();
if (Page.IsValid)
{
cmd.ExecuteNonQuery();
btnEdit.Visible = true;
}
con.Close();
}
}
I have next database fields:
UserId, FirstName, LastName, Password, EmailId, MobileNumber.
Missing the Page.IsPostBack check on the Page_Load event.
In ASP.NET, when you raise an event on a server side control, the Page_Load event is always executed before the code in the control event.
In your case, your user changes the textboxes, then presses the Update button. This raises the Page_Load event followed by the btnUpdate_Click event. Without a check on the property IsPostBack, the Page_Load event reloads the textboxes from the database with the original values effectively destroying the data typed by the user, then the button event code is called. But at this point the values in the textboxes are the original ones, so your code runs correctly, but doesn't change anything.
Change the Page_Load event adding
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
txtUserId.Text = Request.Cookies["txtUserName"].Value;
string con_string = #"data Source= 10.10.10.5; initial catalog= test; user= xx; password= xxxxxxxxx;";
SqlConnection con = new SqlConnection(con_string);
SqlCommand cmd = new SqlCommand(#"select FirstName, LastName, Password,
EmailId, MobileNumber
from ExpenseManagement
where UserId =#usedId", con);
cmd.Parameters.AddWithValue("#UserId", txtUserId.Text);
con.Open();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
......
btnUpdate.Visible = false;
}
}
I could recommend for the command to be more readable to user # instead of concatenating strings with "+" sign as below:
protected void btnUpdate_Click(object sender, EventArgs e)
{
string con_string = #"data Source= 10.10.10.5;initial catalog= test; user= xx; password= xxxxxxxxx;";
SqlConnection con = new SqlConnection(con_string);
string qryUpdate = #"Update ExpenseManagement
set FirstName= #FirstName,
LastName=#LastName,
Password=#Password,
EmailId=#EmailId,
MobileNumber=#MobileNumber
where UserId= #UserId";
SqlCommand cmd = new SqlCommand(qryUpdate, con);
cmd.Parameters.AddWithValue("#UserId", Convert.ToInt32(txtUserId.Text));
cmd.Parameters.AddWithValue("#FirstName", txtFirstName.Text);
cmd.Parameters.AddWithValue("#LastName", txtLastName.Text);
cmd.Parameters.AddWithValue("#Password", txtPassword.Text);
cmd.Parameters.AddWithValue("#EmailId", txtEmailId.Text);
cmd.Parameters.AddWithValue("#MobileNumber", txtMobileNumber.Text);
con.Open();
if (Page.IsValid)
{
cmd.ExecuteNonQuery();
btnEdit.Visible = true;
}
con.Close();
}
Also I agree with RezaRahmati to convert the userId and other parameters to correct types you have defined in your database, table columns.
I think the problem is using cmd.Parameters.AddWithValue("#UserId", txtUserId.Text); because it add a parameter of type string (because txtUserId.Text is string) instead of int or long, so change it to cmd.Parameters.AddWithValue("#UserId", int.parse(txtUserId.Text)); or use cmd.Parameters.Add() which takes type as argument.