Inserting data into Oracle database using c# - c#

I get this error "ora-00928 missing select keyword" when using a button to submit the query. I have other queries on other buttons and the select statements work but for some reason the insert statement doesnt work.
I've seen other posts on this error but nothing seems to help mine
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
namespace Oracle
{
public partial class Register : Form
{
string name;
int pass;
int repass;
string email;
public Register()
{
InitializeComponent();
}
OleDbConnection con = new OleDbConnection("Provider=MSDAORA;Data Source=DESKTOP-HQCK6F1:1521/CTECH;Persist Security Info=True;User ID=system;Password=G4ming404;Unicode=True");
OleDbCommand cmd = new OleDbCommand();
private void button1_Click(object sender, EventArgs e)
{
name = txtname.Text;
pass = Convert.ToInt32(txtpass.Text);
repass = Convert.ToInt32(txtrepass.Text);
email = txtemail.Text;
cmd.Connection = con;
cmd.CommandText = "INSERT INTO SYSTEM.CUSTOMER('CUSTOMER_ID', 'CUSTOMER_NAME', 'CUSTOMER_EMAIL', 'CUSTOMER_PASSWORD')" + "VALUES('%"+ null + "%','%'" + txtname.Text + "%','%'" + txtemail.Text + "%','%'" + txtpass.Text + "%')";
con.Open();
if (pass == repass)
{
int rowsUpdated = cmd.ExecuteNonQuery();
if (rowsUpdated == 0)
{
MessageBox.Show("Record not inserted");
}
else {
MessageBox.Show("Success!");
}
MessageBox.Show("User has been created");
this.Close();
Form1 login = new Form1();
login.Show();
}
else {
MessageBox.Show("Password mismatch");
}
con.Dispose();
}

There are some problems in your query.
First you don't need single quotes around the column names, You need double quotes only if any of your columns has the same name as a reserved keyword.
Second problem is the string concatenation of the input boxes text to the query command. This should be avoided at all cost because it is the source of parsing problems and sql injection hacks. Use parameters instead.
Finally your OleDbConnection should be local to your method and inside a using statement to ensure correct disposing of the unmanaged resources also in case of exceptions
private void button1_Click(object sender, EventArgs e)
{
name = txtname.Text;
pass = Convert.ToInt32(txtpass.Text);
repass = Convert.ToInt32(txtrepass.Text);
email = txtemail.Text;
if (pass != repass)
{
MessageBox.Show("Password mismatch");
return;
}
string cmdText = #"INSERT INTO SYSTEM.CUSTOMER
(CUSTOMER_NAME, CUSTOMER_EMAIL, CUSTOMER_PASSWORD)
VALUES(?,?,?)";
using(OleDbConnection con = new OleDbConnection(.......))
using(OleDbCommand cmd = new OleDbCommand(cmdText, con))
{
con.Open();
cmd.Parameters.Add("p1", OleDbType.VarChar).Value = txtname.Text;
cmd.Parameters.Add("p2", OleDbType.VarChar).Value = txtemail.Text;
cmd.Parameters.Add("p3", OleDbType.VarChar).Value = txtpass.Text ;
int rowsUpdated = cmd.ExecuteNonQuery();
if (rowsUpdated == 0)
{
MessageBox.Show("Record not inserted");
}
else
{
MessageBox.Show("Success!");
MessageBox.Show("User has been created");
}
}
Form1 login = new Form1();
login.Show();
}
I have also removed the passing of a parameter for the CUSTOMER_ID field. This seems to be a field that is calculated automatically by Oracle (a Sequence?) and thus you don't need to provide a value for it.
Finally an advice. Do not store password in plain text in the database. This is a security risk very seriours. You should read Best way to store passwords in a database

Your CommandText seems wrong. Why do you wrap all values with '%'? And you should pass null as string. Concatination with null does not changes any string value.
I think it should be:
cmd.CommandText = $#"INSERT INTO SYSTEM.CUSTOMER
('CUSTOMER_ID', 'CUSTOMER_NAME', 'CUSTOMER_EMAIL', 'CUSTOMER_PASSWORD')
VALUES(NULL, {txtname.Text}, {txtemail.Text}, {txtpass.Text})";

Related

Login Authentication from SQL Server database

I have login issue authentication on windows form C# application. Once I register user it send user data to a SQL Server database. When I am trying to log in. Even if credentials match to data in data base message box showing up. Please see the code below.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using travel_booking.UserControlers;
using System.Data.SqlClient;
namespace travel_booking
{
public partial class UserContrLogin : UserControl
{
internal Action<object, EventArgs> OnUserLogin;
UserContrRegister userContrRegister;
public UserContrLogin()
{
InitializeComponent();
}
public void setUserContrRegister(UserContrRegister userContrRegister)
{
this.userContrRegister = userContrRegister;
}
private void Exit_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void LoginButton_Click(object sender, EventArgs e)
{
SqlConnection sqlConnection = new SqlConnection(#"//Removed by me as it is sensitive data");
sqlConnection.Open();
string query = "Select * from tblUser Where Email = ' " + txtEmail.Text.Trim() + "' and Password = '" + txtPassword.Text.Trim() + "'";
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(query, sqlConnection);
DataTable dataTable = new DataTable();
sqlDataAdapter.Fill(dataTable);
if (dataTable.Rows.Count > 0)
this.Hide();
else
MessageBox.Show("Email or/and Password is/are invalid. Please try again");
sqlConnection.Close();
}
}
}
You can use this code to work much better
public void Login()
{
SqlConnection sqlConnection = new SqlConnection(#"//Removed by me as it is sensitive data");
sqlConnection.Open();
string query = "Select * from tblUser Where Email = #Email and Password = #Password";
SqlCommand command = new SqlCommand();
command.Connection = sqlConnection;
command.CommandType = CommandType.Text;
command.Text = query;
command.Parameters.AddWithValue("#Email", txtEmail.Text.Trim());
command.Parameters.AddWithValue("#Password", txtPassword.Text.Trim());
SqlDataReader reader = command.ExecuteReader();
if(reader.Read() == true)
{
this.Hide();
}
else
{
MessageBox.Show("Email or/and Password is/are invalid. Please try again");
}
}
I use the command.Parameters.AddWithValue() to avoid the concatenation of the string of your query that can cause an SQL INJECTION

C# ASP Web Form Logic

Could someone tell me what I'm doing wrong? I've tried to accomplish this in numerous different ways, but have not been able to. Without adding the parameters in, the form runs, but I need the parameters so that I can update records if it so evaluates. I may be off track, so any help is very appreciated.
For example, if a product code is entered and doesn't have a date already, the form should update the date with the current date/time. If the product code does have a date already, it should notify the user that the product has already shipped, else telling the user that the product is not in the database.
It evaluates by querying if there is a product code and if the date is null. If that evaluates to be true, then it should update that product code with a current timestamp in the date column. If that evaluates to be false, it checks to see if the product code exists in the table at all. If it does and the date column is not null, it reports that the product has already shipped, else, it reports that the product doesn't exist in the database.
Without the following parameters, it runs fine, providing the correct responses but, of course, it doesn't ever call to update a record.
command2.Parameters.AddWithValue("#Value1", TextBox1.Text);
command2.Parameters.AddWithValue("#Value2", DateTime.Now);
With these parameters added in, I get an error stating the "The name 'command2' does not exist in the current context. But, I only get this error one. Sorry if my code is way out of line. Thanks in advance for your help!
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
private string GetConnectionString()
{
return ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
}
protected void Button1_Click(object sender, EventArgs e)
{
using (SqlConnection connection = new SqlConnection(GetConnectionString()))
{
try
{
connection.Open();
string sql = #"SELECT PRODUCT_ID from PRODUCTS where PRODUCT_ID = " + TextBox1.Text + " and DATE is null";
using(SqlCommand command = new SqlCommand(sql, connection))
{
using(SqlDataReader reader = command.ExecuteReader())
{
if(reader.HasRows)
{
string sql2 = #"UPDATE [products] SET date=#Value2 where PRODUCT_ID=#Value1";
using (SqlCommand command2 = new SqlCommand(sql2, connection))
command2.Parameters.AddWithValue("#Value1", TextBox1.Text);
command2.Parameters.AddWithValue("#Value2", DateTime.Now);
pageBody.Attributes.Add("bgcolor", "#9aff8e");
Label1.Text = "Item " + TextBox1.Text + " Recorded!";
TextBox1.Text = "";
}
else
{
reader.Close();
string sql3 = #"SELECT PRODUCT_ID from PRODUCTS where PRODUCT_ID = " + TextBox1.Text + "";
using(SqlCommand command3 = new SqlCommand(sql3, connection))
{
using(SqlDataReader reader2 = command3.ExecuteReader())
{
if (reader2.HasRows)
{
pageBody.Attributes.Add("bgcolor", "#fbff8e");
Label1.Text = "Item " + TextBox1.Text + " Already Shipped!";
TextBox1.Text = "";
}
else
{
pageBody.Attributes.Add("bgcolor", "#ff8e8e");
Label1.Text = "Item " + TextBox1.Text + " Not Found!";
TextBox1.Text = "";
}
}
}
}
}
}
}
finally
{
if(connection.State != ConnectionState.Closed)
{
connection.Close();
}
}
}
}
}
Put your parameters assignment inside a bracket and don't forget to call the execute method.
using (var command2 = new SqlCommand(sql2, connection))
{
command2.Parameters.AddWithValue("#Value1", TextBox1.Text);
command2.Parameters.AddWithValue("#Value2", DateTime.Now);
command2.ExecuteNonQuery();
}
using (SqlCommand command2 = new SqlCommand(sql2, connection)) {
command2.Parameters.AddWithValue("#Value1", TextBox1.Text);
command2.Parameters.AddWithValue("#Value2", DateTime.Now);
}
Forgot your brackets.

How do i add textbox values to Access database?

I want to add textbox values to relevant columns in access database, the connection has been established but when i click the submit button the values are not added.
here is the code i tried, any help is appreciated
protected void Button1_Click(object sender, EventArgs e)
{
string EmailAddress = TextBox1.Text;
string UserName = TextBox2.Text;
string Password = TextBox3.Text;
try
{
OleDbConnection con = new OleDbConnection(#"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = C:\Users\Bheki Ndhlovu\source\WebSites\WebSite8\App_Data\UserDatabase.accdb; Persist Security Info = False;");
OleDbCommand cmd = new OleDbCommand();
cmd = new OleDbCommand("INSERT INTO User(EmailAddress, UserName, Password) VALUES(#EmailAddress, #UserName, #Password)");
con.Open();
if (con.State == ConnectionState.Open)
{
TextBox1.Text = "sssss";
cmd.Parameters.Add("#EmailAddress", OleDbType.VarChar).Value = TextBox1.Text;
cmd.Parameters.Add("#UserName", OleDbType.VarChar).Value = TextBox2.Text;
cmd.Parameters.Add("#Password", OleDbType.VarChar).Value = TextBox3.Text;
cmd.ExecuteNonQuery();
con.Close();
}
}
catch (Exception error)
{
//Show error message as error.Message
}
}
Try adding connection string with OleDbCommand.
cmd = new OleDbCommand("INSERT INTO User(EmailAddress, UserName, Password) VALUES(#EmailAddress, #UserName, #Password)",con);
Here is an example were all data operations reside in a class. If the add new record is successful the new primary key is returned. On failure you can query the exception that raised the problem for failure.
using System;
using System.Windows.Forms;
using System.Data.OleDb;
using System.IO;
namespace MS_AccessAddNewRecord_cs
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void addRecordButton_Click(object sender, EventArgs e)
{
var ops = new Operations();
var newId = 0;
if (ops.AddNewRow(companyTextBox.Text, contactNameTextBox.Text, contactTitleTextBox.Text, ref newId))
{
newIdentifierTextBox.Text = $"{newId}";
}
else
{
MessageBox.Show($"{ops.Exception.Message}");
}
}
}
/// <summary>
/// This class should be in a separate class file, I placed it here for easy of learning
/// </summary>
public class Operations
{
private OleDbConnectionStringBuilder Builder = new OleDbConnectionStringBuilder
{
Provider = "Microsoft.ACE.OLEDB.12.0",
DataSource = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Database1.accdb")
};
private Exception mExceptiom;
public Exception Exception
{
get
{
return mExceptiom;
}
}
/// <summary>
/// Add a new record, upon success return the new primary key for the record in pIdentifier parameter
/// </summary>
/// <param name="pName"></param>
/// <param name="pContactName"></param>
/// <param name="pContactTitle"></param>
/// <param name="pIdentfier"></param>
/// <returns></returns>
public bool AddNewRow(string pName, string pContactName, string pContactTitle, ref int pIdentfier)
{
bool Success = true;
try
{
using (OleDbConnection cn = new OleDbConnection { ConnectionString = Builder.ConnectionString })
{
using (OleDbCommand cmd = new OleDbCommand { Connection = cn })
{
cmd.CommandText = "INSERT INTO Customers (CompanyName,ContactName, ContactTitle) " +
"Values(#CompanyName,#ContactName, #ContactTitle)";
cmd.Parameters.AddWithValue("#CompanyName", pName);
cmd.Parameters.AddWithValue("#ContactName", pContactName);
cmd.Parameters.AddWithValue("#ContactTitle", pContactTitle);
cn.Open();
int Affected = cmd.ExecuteNonQuery();
if (Affected == 1)
{
cmd.CommandText = "Select ##Identity";
pIdentfier = Convert.ToInt32(cmd.ExecuteScalar());
}
}
}
}
catch (Exception ex)
{
Success = false;
mExceptiom = ex;
}
return Success;
}
}
}
Perhaps in the Page_Load method you do not have a if(!isPostback) and so the value of the TextBoxes are getting reset on a postback before the Button1_Click method is executed.
If EmptyWaterHole's answer is not the problem, is it erroring out on the connection?
Be sure 'VarChar' is the correct data type for each of the fields.
Also, be sure the values do not exceed the size (ie: if you set the field to only allow up to 25 characters and your value is over 25 characters, the value will not be added).
In addition, if you are not allowing nulls and one of the values exceeds the limit, the whole record will not be added.
Mr. Hungry. Try it like this.
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:\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");
}
}
}
}
try this it will work if you are using access as your database
try
{
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "INSERT INTO REPORT (patientName,tel,hostel,id no,department,diagnose,gender) values(#patientName,#tel,#hostel,#id no,#department,#diagnose,#gender)";
connection.Open();
command.Parameters.AddWithValue("#patientName", textBox1.Text);
command.Parameters.AddWithValue("#tel", textBox2.Text);
command.Parameters.AddWithValue("#hostel", textBox3.Text);
command.Parameters.AddWithValue("#id no", textBox4.Text);
command.Parameters.AddWithValue("#department", textBox5.Text);
command.Parameters.AddWithValue("#diagnose", richTextBox1.Text);
command.Parameters.AddWithValue("#gender", textBox6.Text);
command.ExecuteNonQuery();
connection.Close();
MessageBox.Show("Patient record Have been save successfully....");
}
catch (Exception ex)
{
MessageBox.Show("error" + ex);
}

About the an unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll

I am writing a C# windows forms program. When I want to login in the windows form, I get an error that says:
A first chance exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: Invalid object name 'Login'.
If there is a handler for this exception, the program may be safely continued.
What should I do? Thanks.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsFormsApplication1
{
public partial class LOGIN : Form
{
public LOGIN()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\kenlui\Documents\LoginDate.mdf;Integrated Security=True;Connect Timeout=30;");
SqlDataAdapter sda = new SqlDataAdapter("Select Count(*) from Login where Username ='" + textBox1.Text + "' and Password = '" + textBox2.Text + "'", con);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows[0][0].ToString() == "1")
{
this.Hide();
main ss = new main();
ss.Show();
}
else
{
MessageBox.Show("Please Check Username and Password");
}
}
}
}
Either dbo.Login table does not exist OR it is associated with a different schema. When you create your tables and database objects you should prefix them with dbo. unless you know what schemas are and how to use them.
Some additional issues I find with your code:
You should never use string concatenation to create a sql statement. This leaves your code vulnerable to sql injection attacks and also syntax error (if the user name or password contained a ' for example.). Use parameterized sql instead.
Never store passwords in plain text. Use a hashing library and create a secure 1 way hash and persist that. When logging in create a hash from the presented password in the UI and compare that to the value in the database.
Your code never closes the database connection. To ensure it is always closed after you are done with it wrap it in a using block to ensure it is closed and disposed, this will help even if an exception is thrown.
Code with some corrections.
private void button1_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\kenlui\Documents\LoginDate.mdf;Integrated Security=True;Connect Timeout=30;"))
using (SqlDataAdapter sda = new SqlDataAdapter("Select Count(*) from Login where Username = #userName and Password = #password", con))
using (DataTable dt = new DataTable())
{
sda.SelectCommand.Parameters.Add(new SqlParameter("#userName", SqlDbType.VarChar) { Value = textBox1.Text });
// this should be a hash of the password, not the plain text value
sda.SelectCommand.Parameters.Add(new SqlParameter("#password", SqlDbType.VarChar) { Value = textBox2.Text });
sda.Fill(dt);
if (dt.Rows[0][0].ToString() == "1")
{
this.Hide();
main ss = new main();
ss.Show();
}
else
{
MessageBox.Show("Please Check Username and Password");
}
}
}
Finally instead of using a SqlDataAdapter consider using SqlCommand with ExecuteScalar instead.
private void button1_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\kenlui\Documents\LoginDate.mdf;Integrated Security=True;Connect Timeout=30;"))
using (SqlCommand sda = new SqlCommand("Select 1 from Login where Username = #userName and Password = #password", con))
{
sda.Parameters.Add(new SqlParameter("#userName", SqlDbType.VarChar) { Value = textBox1.Text });
// this should be a hash of the password, not the plain text value
sda.Parameters.Add(new SqlParameter("#password", SqlDbType.VarChar) { Value = textBox2.Text });
var result = sda.ExecuteScalar();
if (result != null && 1 == (int)result)
{
this.Hide();
main ss = new main();
ss.Show();
}
else
{
MessageBox.Show("Please Check Username and Password");
}
}
}

How to solve ASP.NET custom login page error?

In Login.aspx.cs file
The codes are following
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.Configuration;
namespace Leave_Management
{
public partial class Login : System.Web.UI.Page
{
//private string strcon = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(#"Data Source=TAUFIQ-PC\SQLEXPRESS;Initial Catalog=LM;Integrated Security=True");
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
conn.Open();
string checkuser = "select UserName from [User] where UserName='" + TextBoxUN + "'";
SqlCommand com = new SqlCommand(checkuser, conn);
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
if (temp == 1)
{
string checkpass = "select password from [User] where UserName='" + TextBoxUN + "'";
SqlCommand passcom = new SqlCommand(checkpass, conn);
string password = passcom.ExecuteScalar().ToString().Replace(" ", "");
conn.Close();
if (password == TextBoxPass.Text)
{
Response.Redirect("Registration.aspx");
}
}
}
}
}
An Error is showing as
"NullReferenceException was unhandled by user code"
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
Please help me to solve this.
You can just simplify your code by checking both username and password from the SQL statement:
protected void Button1_Click(object sender, EventArgs e)
{
conn.Open();
string SQL = "select UserID from [User] where UserName=#UserName AND Password=#Password";
SqlCommand com = new SqlCommand(SQL, conn);
com.Parameters.AddWithValue("#UserName", TextBoxUN.Text);
com.Parameters.AddWithValue("#Password", TextBoxPass.Text);
SqlDataReader data = com.ExecuteReader();
if (data.HasRows) // username and password match
{
conn.Close();
Response.Redirect("Registration.aspx");
}
else
{
conn.Close();
// display error here
}
}
I assume that UserID is the primary key of your Users table. You can use other column names if you want.
I also used parameters to avoid SQL injection. Cheers!
Too long for a comment, there are many things wrong with your code:
You are concatenating user-specified values into SQL queries. Don't do it, use parameters.
You are putting TextBoxUN into the SQL, you probably want TextBoxUN.Text. This is the reason you get null, since there is no user with that name.
You must take the value provided by ExecuteScalar() and check if it is null. Now it is, so you get a clear error about it.
Why get the username from the database with the username and then check for password? You can check for password and username with one query.
Do not store passwords in cleartext in the database! Use hash functions.
if temp comes up as null, then you will get the error. I would try:
...
int temp = 0;
try {
temp = Convert.ToInt32(com.ExecuteScalar().ToString());
} catch (exception) {}
...

Categories