Command object passing any values in asp.net web forms - c#

I have a table with 1 record and I made a stored procedure for it to use in my button click, but it's letting me pass any values and when I test it in sql, it works as expected. Just wondering if any of you can point out the bug in my code.
protected void btnLogin_Click(object sender, EventArgs e)
{
SqlDataReader dr = default(SqlDataReader);
SqlCommand cmd = default(SqlCommand);
string userName = txtUserName.Text;
string password = txtPassword.Text;
using (SqlConnection conn = new SqlConnection(strConn))
{
cmd = new SqlCommand("adminAuthentication", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Username", userName);
cmd.Parameters.AddWithValue("#Password", password);
conn.Open();
dr = cmd.ExecuteReader();
dr.Read();
if (dr.HasRows)
{
lblMessage.Text = "Successfull login!";
}
else
{
lblMessage.Text = "Wrong user/password";
conn.Close();
}
}
}
Stored procedure:
CREATE PROC adminAuthentication
(
#UserName varchar(15),
#Password varchar(25)
)
AS
BEGIN
SELECT COUNT(1)
FROM AdminLogin
WHERE UserName = #UserName AND Pwd = #Password
END

Related

expects parameter '#id', which was not supplied. the id is primary key and identity

I get this error:
expects parameter '#id', which was not supplied. the id is primary key and identity
My code:
namespace se_up_de_in
{
public partial class Form1 : Form
{
SqlConnection conn = new SqlConnection(#"Data Source=DESKTOP-R0N4ID3;Initial Catalog=DBTask2;Integrated Security=True");
SqlCommand comm;
SqlDataAdapter Adapter;
DataTable Table = new DataTable();
private void button2_Click(object sender, EventArgs e)
{
using (comm = new SqlCommand("proc_insertid", conn))
{
comm.CommandType = CommandType.StoredProcedure;
conn.Open();
SqlParameter[] parameter = new SqlParameter[5];
parameter[0] = new SqlParameter("#id", SqlDbType.Int);
parameter[0].Value = textBox5.Text;
parameter[1] = new SqlParameter("#username", SqlDbType.NChar);
parameter[1].Value = textBox1.Text;
parameter[2] = new SqlParameter("#password", SqlDbType.NChar);
parameter[2].Value = textBox2.Text;
parameter[3] = new SqlParameter("#email", SqlDbType.NVarChar);
parameter[3].Value = textBox3.Text;
parameter[4] = new SqlParameter("#Type", SqlDbType.NChar);
parameter[4].Value = textBox4.Text;
comm.ExecuteNonQuery();
comm.Parameters.AddRange(parameter);
conn.Close();
dataGridviewfill();
}
}
private void button4_Click(object sender, EventArgs e)
{
using (comm = new SqlCommand("proc_Dlelete", conn))
{
comm.CommandType = CommandType.StoredProcedure;
conn.Open();
SqlParameter param = new SqlParameter();
param = new SqlParameter("#id", SqlDbType.NChar);
param.Value = textBox5.Text;
comm.ExecuteNonQuery();
comm.Parameters.Add(param);
conn.Close();
dataGridviewfill();
}
}
}
}
My stored procedure:
CREATE PROCEDURE proc_insert
(#id INT,
#username NCHAR(10),
#password NCHAR(10),
#email NVARCHAR(MAX),
#Type NCHAR(10))
AS
BEGIN
INSERT INTO ttask2 (id, username, password, email, Type)
VALUES (#id, #username, #password, #email, #Type)
END
comm.ExecuteNonQuery();
comm.Parameters.AddRange(parameter);
Reverse these; you need to add the parameters before executing the command.
comm.Parameters.AddRange(parameter);
comm.ExecuteNonQuery();
(same for other places you use the command/parameters)

Calling an Oracle Stored Procedure in C#

I am trying to call an Oracle stored procedure from a C# program. I am using a SYS_REFCURSOR an the output of the stored procedure. I am getting invalid SQL error when I reach the line
OracleDataReader reader = cmd.ExecuteReader()
in my C# program. I can't figure out why I am getting this invalid SQL error.
Here is the C# code:
private void button1_Click(object sender, EventArgs e)
{
string custname;
int custnbr;
List<Customer> customers = new List<Customer>();
string oradb = "User Id=XXXXX;Password=XXXXX;Data Source=IP:PORT/xxxx;Pooling=false;";
OracleConnection conn = new OracleConnection(oradb);
try
{
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "PROCEDURE_TEST";
OracleParameter oraP = new OracleParameter();
oraP.ParameterName = "R_RECORDSET";
oraP.OracleDbType = OracleDbType.RefCursor;
oraP.Direction = System.Data.ParameterDirection.Output;
cmd.Parameters.Add(oraP);
cmd.CommandType = CommandType.Text;
OracleDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
custnbr = reader.GetInt32(0);
custname = reader.GetString(1);
Customer custTemp = new Customer(custnbr, custname);
customers.Add(custTemp);
}
foreach (var cust in customers)
{
textBox1.AppendText("Customer Number: " + cust.custnbr + "\t");
textBox1.AppendText("Customer Name: " + cust.custname + "\r\n");
}
}
catch(Exception ex)
{
textBox1.AppendText(ex.ToString());
conn.Close();
}
}
Here is the Oracle stored procedure:
create or replace PROCEDURE PROCEDURE_TEST
( R_RECORDSET OUT SYS_REFCURSOR) AS
BEGIN
OPEN R_RECORDSET FOR
SELECT POTCHARGECATEGORY, POTCHARGECODE, POTCHARGEDESCRIPTION,
POTCHARGEBASEAMT, SUM(POTCHARGEQTY), SUM(POTCHARGEAMOUNT)
FROM riowner.ccum_customer customer
WHERE ic.collection_Datetime =
TO_DATE('30-SEP-2015 23:59:59','DD-MON-YYYY HH24:MI:SS')
GROUP BY POTCHARGECATEGORY, POTCHARGECODE, POTCHARGEDESCRIPTION,
POTCHARGEBASEAMT;
END PROCEDURE_TEST;
cmd.CommandType = CommandType.Text;
should be
cmd.CommandType = CommandType.StoredProcedure;
As an alternative to MethodMan's answer, you should be able to keep the command type as Text, but change your SQL command to this:
cmd.CommandText = "BEGIN PROCEDURE_TEST END;";
MethodMan's method is better if you just need to call one procedure, but the way I did it above would allow you to do more procedures, so it's something to be aware of in the future.

I need to navigate windows forms based on login password

this is the code i have used to validate both username and password from the database. but it always navigates to the first if condition. But is HR group has the same password and SW dev group has the same password. i need to validate the password and need to navigate to the Form.
private void button1_Click(object sender, EventArgs e)
{
con.Open();
string usrnm = txtusrnm.Text;
string pass = txtpass.Text;
SqlDataReader reader = null;
string qry = "select username, password from login where username=#username and password=#password";
//SqlCommand cmd = new SqlCommand();
SqlCommand cmd = new SqlCommand(qry, con);
cmd.Parameters.AddWithValue("#username", txtusrnm.Text);
cmd.Parameters.AddWithValue("#password", txtpass.Text);
reader = cmd.ExecuteReader();
if (reader != null ||reader.HasRows)
{
//if username is matching
MessageBox.Show("Redirecting to HR..");
frm_hr fhr = new frm_hr();
fhr.Show();
this.Hide();
}
else
{
//if not matching do something
MessageBox.Show("Redirecting to Software Developer..");
frm_swdev fsw = new frm_swdev();
fsw.Show();
this.Hide();
}
con.Close();
}
in your code there is this :
reader = cmd.ExecuteReader();
if (reader != null ||reader.HasRows)
this will always be true, because reader will always != null
change it to
reader = cmd.ExecuteReader();
if (reader.HasRows)
An alternate idea to reader.HasRows - change your query to count the number of rows that contain the username/password, then you will always return a value of 0 or 1...
string qry = "select count(*) from login where username=#username and password=#password";
SqlCommand cmd = new SqlCommand(qry, con);
cmd.Parameters.AddWithValue("#username", txtusrnm.Text);
cmd.Parameters.AddWithValue("#password", txtpass.Text);
int iValue = (int)cmd.ExecuteScalar();

Full Email Address is not Showing in #Email Column

I have a page for registration where i am saving details of users.
Page is working fine data is shaving but 'full email address' is not showing in table of '#email' column.
Example: if i am saving 'cozm02011#gmail.com' it is showing only 'cozm02011' in table.
code behind
protected void ceratenewuser_Click(object sender, EventArgs e)
{
String ConnString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(ConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "User_pro";
cmd.Parameters.AddWithValue("#UserName", TextBox1.Text.Trim());
cmd.Parameters.AddWithValue("#Password", TextBox2.Text.Trim());
cmd.Parameters.AddWithValue("#Email", TextBox3.Text.Trim());
cmd.Parameters.AddWithValue("#LastSeen", DateTime.Now);
cmd.Parameters.AddWithValue("#CreatedDate", DateTime.Now);
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
Label2.Text = "User Created successfully";
TextBox1.Text = ""; TextBox2.Text = ""; TextBox3.Text = ""; TextBox4 .Text = "";
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
}
this.GridView1.DataBind();
}
store procedure
ALTER PROCEDURE dbo.User_pro
#UserName varchar(20),
#Password varchar(20),
#Email varchar(50),
#LastSeen datetime,
#CreatedDate datetime
AS
INSERT INTO User_tbl (UserName, Password, Email, LastSeen, CreatedDate)
VALUES (#UserName, #Password, #Email, #LastSeen, #CreatedDate)
RETURN
You are binding the "Confirm password" field to the E-mail column
cmd.Parameters.AddWithValue("#Email", TextBox3.Text.Trim());
TextBox3 is used for "Confirm password" field.
Try this,
cmd.Parameters.AddWithValue("#Email", TextBox4.Text.Trim());

SQL Server error: ExecuteNonQuery: Connection property has not been initialized

I am trying to develop a sample registration page using ASP.Net and C#. I am calling a stored procedure to insert the data to database. My database is SQL Server 2008.
This is my code:
public partial class Sample : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbconnection"].ToString());
string str;
protected void Page_Load(object sender, EventArgs e)
{
rbt_Male.Checked = true;
}
protected void btn_Submit_Click(object sender, EventArgs e)
{
string #Name = txtbx_Name.Text;
string #Gender_male = rbt_Male.Text;
string #Gender_Female = rbt_Female.Text;
string #Email = txtbx_Email.Text;
DateTime #Dob = Convert.ToDateTime(txt_Dob.Text);
submitdata();
}
protected void submitdata()
{
try
{
SqlCommand cmd = new SqlCommand();
cmd.Parameters.Clear();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "insertdata";
if (rbt_Male.Checked)
{
cmd.Parameters.AddWithValue("#Name", txtbx_Name.Text);
cmd.Parameters.AddWithValue("#Gender_Male", rbt_Male.Text);
cmd.Parameters.AddWithValue("#Email", txtbx_Email.Text);
cmd.Parameters.AddWithValue("#Dob", Convert.ToDateTime(txt_Dob.Text));
}
else if (rbt_Female.Checked)
{
cmd.Parameters.AddWithValue("#Name", txtbx_Name.Text);
cmd.Parameters.AddWithValue("#Gender_Female", rbt_Male.Text);
cmd.Parameters.AddWithValue("#Email", txtbx_Email.Text);
cmd.Parameters.AddWithValue("#Dob", Convert.ToDateTime(txt_Dob.Text));
}
if (con.State == ConnectionState.Closed)
con.Open();
cmd.ExecuteNonQuery();
lbl_Errormsg.Visible = true;
lbl_Errormsg.Text = "Record Inserted Successfully";
con.Close();
}
catch (Exception ex)
{
lbl_Errormsg.Visible = true;
lbl_Errormsg.Text = ex.Message;
}
I am getting the error message
ExecuteNonQuery: Connection property has not been initialized.
I am getting this error at cmd.ExecuteNonQuery();
Please help me.
My stored procedure is
ALTER Procedure insertdata
(
#Name Varchar(20),
#Gender Varchar(6),
#Email Varchar(20),
#Dob date
)
As
Begin
Insert into samplelogintable (Name, Gender, Email, Dob)
Values(#Name, #Gender, #Email, #Dob)
End
You haven't associated your command cmd with your SqlConnection, that is why you are getting the error.
You need to specify:
cmd.Connection = con;
in your submitdata() method.
Since SqlCommand implements IDisposable, its better if you use it within using block like:
using (SqlCommand cmd = new SqlCommand())
{
cmd.Parameters.Clear();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "insertdata";
cmd.Connection = con;
.... your code
}

Categories

Resources