NullReferenceException i am familiar with them, but cannot solve on this occasion - c#

im fairly new to ASP.net but i am familiar with Null reference exceptions however i cant solve this one. Im trying to collect data from a webform and pass it to my database through a connection string, this is when the exception occurs.
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;
public partial class Register : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (IsPostBack)
{
SqlConnection studConnA = new SqlConnection(ConfigurationManager.ConnectionStrings["StudConnection"].ConnectionString);
studConnA.Open();
string checkuser = "select count(*) from StudTable where Name='" + TextBoxName.Text + "'";
SqlCommand studComA = new SqlCommand(checkuser, studConnA);
int temp = Convert.ToInt32(studComA.ExecuteScalar().ToString());
if (temp == 1)
{
Response.Write("User already Exists");
}
studConnA.Close();
}
}
catch (Exception ex)
{
Response.Write("Error:" + ex.ToString());
}
}
protected void Button1_Click(object sender, System.EventArgs e)
{
try
{
SqlConnection studConn = new SqlConnection(ConfigurationManager.ConnectionStrings["StudConnectionString"].ConnectionString);
studConn.Open();
string insertQuery = "insert into StudTable (Name,Email,Age,Continent,School,Password) values (#name,#email,#age,#cont,#school,#pass)";
SqlCommand studCom = new SqlCommand(insertQuery, studConn);
studCom.Parameters.AddWithValue("#name", TextBoxName.Text);
studCom.Parameters.AddWithValue("#email", TextBoxEmail.Text);
studCom.Parameters.AddWithValue("#age", TextBoxAge.Text);
studCom.Parameters.AddWithValue("#cont",DropDownCont.SelectedItem.ToString());
studCom.Parameters.AddWithValue("#school", TextBoxSchool.Text);
studCom.Parameters.AddWithValue("#pas", TextBoxPass.Text);
studCom.ExecuteNonQuery();
Response.Redirect("Backend.aspx");
Response.Write("Your Registration is Sucessful");
studConn.Close();
}
catch (Exception ex)
{
Response.Write("Error:" +ex.ToString());
}
}
}
The null reference occurs at line 19
Line 17: if (IsPostBack)
Line 18: {
Line 19: SqlConnection studConnA = new SqlConnection(ConfigurationManager.ConnectionStrings["StudConnection"].ConnectionString);
Line 20: studConnA.Open();
Line 21: string checkuser = "select count(*) from StudTable where Name='" + TextBoxName.Text + "'";
I believe the issue is in the syntax of my connection string but im not sure,
Can anyone help me to solve this?

Check your configuration file for the following key:
<connectionStrings>
<add name="StudConnection" connectionString="YOUR DETAILS" />
</connectionStrings>
If it doesn't exist, add the right key and retry.
You can also check the issue with the following code:
if (IsPostBack)
{
// if this line fails, then you don't have the proper connection string
// element in the config file.
Debug.Assert(ConfigurationManager.ConnectionStrings["StudConnection"] != null);
SqlConnection studConnA = new SqlConnection(ConfigurationManager.ConnectionStrings["StudConnection"].ConnectionString);
studConnA.Open();
string checkuser = "select count(*) from StudTable where Name='" + TextBoxName.Text + "'";
SqlCommand studComA = new SqlCommand(checkuser, studConnA);
int temp = Convert.ToInt32(studComA.ExecuteScalar().ToString());
if (temp == 1)
{
Response.Write("User already Exists");
}
studConnA.Close();
}

It would appear that there is no connection string named StudConnection configured.

Related

Setting up a chart that displays the number of times a dataset record appears in C#

I am trying to create a chart that when, at the push of a button displays a chart that shows the user the number of times a record has appeared in the dataset/table that it is linked to. Please bare in mind that I have little experience with using Charts in Visual Studios/C#.
Currently I am getting this error: Error
This is all the code I have so far:
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 RRAS
{
public partial class formRRAS : Form
{
public OleDbConnection DataConnection = new OleDbConnection();
public formRRAS()
{
InitializeComponent();
}
private void formRRAS_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'database1DataSet.tblReject_test' table. You can move, or remove it, as needed.
this.tblReject_testTableAdapter.Fill(this.database1DataSet.tblReject_test);
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnSearch_Click(object sender, EventArgs e)
{
//This creates the String Publisher which grabs the information from the combo box on the form.
//Select and Dataconnection are also defined here.
string Select = "SELECT * FROM tblReject_test";
string DataConnection;
string Department = txtDepartment.Text;
string Start_Date = txtStart.Text;
string End_Date = txtEnd.Text;
string Anatomy = txtAnatomy.Text;
string RFR = cmbRFR.Text;
string Comment = txtComment.Text;
//Select defines what should be loaded on to the dataset.
if (Department != "")
{
Select = Select + " WHERE department_id =" + "'" + Department + "'";
if (Anatomy != "")
{
Select = Select + "AND body_part_examined =" + "'" + Anatomy + "'";
if (Start_Date != "")
{
Select = Select + " AND study_date =" + "'" + Start_Date + "'";
if (End_Date != "")
{
Select = Select + " AND study_date =" + "'" + End_Date + "'";
if (RFR != "")
{
Select = Select + " AND reject_category =" + "'" + RFR + "'";
if(Comment != "")
{
Select = Select + " AND reject_comment =" + "'" + Comment + "'";
}
}
}
}
}
}
else
{
Select = "SELECT * FROM tblReject_test";
}
//DataConnection connects to the database.
string connectiontring= "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\Database1.mdb";
DataConnection = new OleDbConnection(connectiontring);
//The DataAdapter is the code that ensures both the data in the Select and DataConnection strings match.
OleDbDataAdapter rdDataAdapter = new OleDbDataAdapter(Select, DataConnection);
try
{
//It then clears the datagridview and loads the data that has been selected from the DataAdapter.
database1DataSet.tblReject_test.Clear();
rdDataAdapter.Fill(this.database1DataSet.tblReject_test);
}
catch (OleDbException exc)
{
System.Windows.Forms.MessageBox.Show(exc.Message);
}
}
private void btnLoadChart_Click(object sender, EventArgs e)
{
try
{
int count = database1DataSet.Tables["tblReject_test"].Rows.Count;
DataConnection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = DataConnection;
string query = "SELECT * FROM tblReject_test";
command.CommandText = query;
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
charRejections.Series["RFR"].Points.AddXY(reader["reject_category"].ToString(), reader[count].ToString());
}
DataConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
}
}
Your code wouldn't compile as you are assigning a string to DataConnection (instance of OleDbConnection).
The correct usage should be as following.
string connectiontring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\Database1.mdb";
DataConnection = new OleDbConnection(connectiontring));
Also, your code doesn't close Database connection in case of exception.
It would be recommended to use the code as shown below. This is taken from MSDN
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
try
{
connection.Open();
Console.WriteLine("DataSource: {0} \nDatabase: {1}",
connection.DataSource, connection.Database);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
// The connection is automatically closed when the
// code exits the using block.
}

Execute scalar cannot pass password textbox, throws null exception

The code does connect to the database and actually check the username(number) and then exception runs when it has to get to verifying the password and a null reference is thrown
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;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnLogin_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Intellicell_CallCentreConnectionString"].ConnectionString);
conn.Open();
string checkuser = "SELECT COUNT(*) FROM Debtors WHERE MobilePhone='" + txtMobilePhone.Text + "'";
SqlCommand cmd = new SqlCommand(checkuser, conn);
int temp = Convert.ToInt32(cmd.ExecuteScalar().ToString());
conn.Close();
if (temp == 1)
{
conn.Open();
string CheckPasswordQuery = "SELECT IDNumber from Debtors WHERE MobilePhone='" + txtPassword.Text + "'";
SqlCommand passCmd = new SqlCommand(CheckPasswordQuery, conn);
string password = passCmd.ExecuteScalar().ToString().Replace(" ","");
conn.Close();
if (password == txtPassword.Text)
{
Session["New"] = txtMobilePhone.Text;
Response.Write("Password is correct!");
Response.Redirect("Home.aspx");
}
else
{
Response.Write("Password is not correct!");
}
}
else
{
Response.Write("Please Provide valid Login details!");
}
}
}
it is on line
string password = passCmd.ExecuteScalar().ToString().Replace(" ","");
that it breaks.
I suggest you if you want write sql adhoc, use string.format
It's clean
string checkuser = string.Format("SELECT COUNT(*) FROM Debtors WHERE MobilePhone={0},txtMobilePhone.Text);
Secondly, you can use using syntax , in order to clean your connection properly
I think, In the second sql you are using txtPassword.Text instead of txtMobilePhone.Text
The question is why are you getting the null execption, see this: https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar(v=vs.110).aspx
In summary ExecuteScaler returns a null (not a DBNull) if no rows are found, whence passCmd.ExecuteScalar().ToString().Replace(" ",""); null refences as its null.ToString()
You global logic looks flawed so hard to suggest exactly what to do, but passCmd.ExecuteScalar()?.ToString().Replace(" ","") will suppress the exeception.

Registration allows duplicate user name in Access

I do have a problem in checking username and password in my registration form. When I tend to register the same username and password that's is already in my database(Access), still it allows to register. I just wanna trap it however, I don't know how to that.
What I want to output is that, I want a trap that says "Account Exists, Try Again!" or "Username Exists!"
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; using System.Text.RegularExpressions;
namespace Login { public partial class Register : Form {
private OleDbConnection personalConn;
private OleDbCommand oleDbCmd = new OleDbCommand();
private String connParam = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\Majel\Tic Tac Toe\Database\data.accdb";
public Register()
{
personalConn = new OleDbConnection(connParam);
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
personalConn.Open();
oleDbCmd.Connection = personalConn;
if (textBox1.Text != "" && textBox2.Text != "")
{
int temp;
oleDbCmd.CommandText = "INSERT INTO data(Users,Pass) Values('" + this.textBox1.Text.ToString() + "','" + this.textBox2.Text + "');";
temp = oleDbCmd.ExecuteNonQuery();
if (temp > 0)
{
textBox1.Text = null;
textBox2.Text = null;
MessageBox.Show("Registration Success!");
this.Hide();
Form1 frm = new Form1();
frm.Show();
}
personalConn.Close();
}
}
catch (Exception)
{
MessageBox.Show("Invalid!, Duplicate Data.");
}
}
Notes: textBox1= username
textBox2= password Your attention is much highly appreciated. Thank you so much in advance.
Here is code which uses oledbcommand parameters using ? placeholder as mentioned in MSDN Reference. Also I have added using block which should Close opened connection implicitly.
using(OleDbConnection con = new OleDbConnection(connParam))
using(OleDbCommand cmd = new OleDbCommand("select count(*) from data where Users = ?"))
{
con.Open();
cmd.Connection = con;
cmd.Parameters.AddWithValue("#UserName", textBox1.Text);
object objRes = cmd.ExecuteScalar();
if (objRes == null || (int)objRes == 0)
{
cmd.Parameters.Clear();
cmd.CommandText = "INSERT INTO data (Users,Pass) values(?, ?);";
cmd.Parameters.AddWithValue("#Users", textBox1.Text);
cmd.Parameters.AddWithValue("#Pass", textBox2.Text);
int iRes = cmd.ExecuteNonQuery();
if(iRes > 0)
MessageBox.Show("Registration Success!");
}
else
errorProvider2.SetError(textBox1, "This username has been using by another user.");
}
You almost never use data (in this case, a username) as the primary key for a record in a database. Chance are, your access database is set up the same way.
This means that there is nothing at the DBMS layer that will stop this from occurring, short of making the username the primary key (not recommended).
The solution is to perform a SELECT query to get the count of records with that username, and only allow the insert if the count is 0. You might be able to write a trigger to do this for you, and make the DBMS "reject" the insert, but given your (apparent) level with databases, I wouldn't try that at this point.
To get the count:
SELECT Count(*) FROM Users WHERE userName=#userName
A paramaterized query here is crucial to protect against SQL injection.
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;
using System.Text.RegularExpressions;
namespace Login
{
public partial class Register : Form
{
public Register()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
if(text1Box1.Text == "" || textBox2.Text == "")
{
MessageBox.Show("Mandatory fields password or user is empty");
retrun; //I'm not sure if this return is need. Remove it if MessageBox "breaks" the execution of the code below.
}
OleDbCommand cmd = new OleDbCommand(#"Select * from Data where User=#User");
cmd.Parameters.AddWithValue("#User", textBox1.Text);
DataSet dst = SqlManager.GetDataSet(cmd, "Data");
if(dst.Tables[0].Rows > 0)
{
MessageBox.Show("User already exist");
return; //again i'm not sure that this return is needed.
}
Insert("Data", "User", textBox1.Text, "Pass", textBox2.Text);
textBox1.Text = null;
textBox2.Text = null;
MessageBox.Show("Registration Success!");
this.Hide();
Form1 frm = new Form1();
frm.Show();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
You need 1 class make it SqlManager.
public class SqlManager
{
private String connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\Majel\Tic Tac Toe\Database\data.accdb";
public static GetOleDbConnection(OleDbCommand cmd)
{
if(cmd.Connection == null)
{
OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();
cmd.Connection = conn;
return conn;
}
return cmd.Connection;
}
public static int ExecuteNonQuery(SqlCommand cmd)
{
OleDbConnection conn = GetSqlConnection(cmd);
try
{
return cmd.ExecuteNonQuery();
}
catch
{
throw;
}
finally
{
conn.Close();
}
}
public static DataSet GetDataSet(SqlCommand cmd)
{
return GetDataSet(cmd, "Table");
}
public static DataSet GetDataSet(SqlCommand cmd, string defaultTable)
{
OleDbConnection conn = GetSqlConnection(cmd);
try
{
DataSet resultDst = new DataSet();
using (OleDbDataAdapter adapter = new OleDbDataAdapter(cmd))
{
adapter.Fill(resultDst, defaultTable);
}
return resultDst;
}
catch
{
throw;
}
finally
{
conn.Close();
}
}
}
Here is another method you can put in the form class:
public virtual void Insert(string TableName, params object[] colValues)
{
if (colValues == null || colValues.Length % 2 != 0)
throw new ArgumentException("Invalid column values passed in. Expects pairs (ColumnName, ColumnValue).");
OleDbCommand cmd = new OleDbCommand("INSERT INTO " + TableName + " ( {0} ) VALUES ( {1} )");
string insertCols = string.Empty;
string insertParams = string.Empty;
for (int i = 0; i < colValues.Length; i += 2)
{
string separator = ", ";
if (i == colValues.Length - 2)
separator = "";
string param = "#P" + i;
insertCols += colValues[i] + separator;
insertParams += param + separator;
cmd.Parameters.AddWithValue(param, colValues[i + 1]);
}
cmd.CommandText = string.Format(cmd.CommandText, insertCols, insertParams);
DA.SqlManager.ExecuteNonQuery(cmd);
}
Like other guys tell you use parameters in this case you will avoid sql injection. Read in wikipedia about it. Also I add some structure for your program, it is not perfect but I should write a lot for more. It is possible to have some typos here, because I wrote the code here. How you make the check, you fetch the data from database for the user which you write in textbox1.Text. If the dataSet have rows that means at the moment there is existing user with this name. If you don't know what is data set read System.Data.
You should learn to write data access in other classes !
Try this with your Existing Code :
oleDbCmd.CommandText = "INSERT INTO data(Users,Pass) Values('" + this.textBox1.Text.ToString() + "','" + this.textBox2.Text + "') SELECT '" + this.textBox1.Text.ToString() + "','" + this.textBox2.Text + "' WHERE NOT EXISTS(SELECT Users,Pass FROM data WHERE Users='" + this.textBox1.Text.ToString() +"');";
temp = oleDbCmd.ExecuteNonQuery();
if (temp > 0)
{
textBox1.Text = null;
textBox2.Text = null;
MessageBox.Show("Registration Success!");
this.Hide();
Form1 frm = new Form1();
frm.Show();
}
else
{
MessageBox.Show("Username is already Present !!!");
}
It returns 0 if the username is already present in data.

How do I to insert data into an SQL table using C# as well as implement an upload function?

Below is the code I am working with to try to insert data into my 'ArticlesTBL' table. I also want to upload an image file to my computer.
I am getting an error reading: Incorrect syntax near 'UploadedUserFiles'.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;
public partial class _CopyOfSubmitArticle : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void uploadbutton_Click(object sender, EventArgs e)
{
string UpPath = Server.MapPath("~/UploadedUserFiles");
int imgSize = FileUpload1.PostedFile.ContentLength;
string imgName = FileUpload1.FileName;
string imgPath = "UploadedUserFiles/" + imgName;
if (FileUpload1.PostedFile.ContentLength > 1000000)
{
Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Alert", "alert('File is too big')", true);
}
else
{
FileUpload1.SaveAs(Server.MapPath(imgPath));
myinfo.Text = "file" + imgPath + "uploaded.";
}
String connectionString = WebConfigurationManager.ConnectionStrings["ConnectAntiFrack"].ConnectionString;
SqlConnection myConnection = new SqlConnection(connectionString);
myConnection.Open();
string ArticleImg = "UploadedUserFiles/" + FileUpload1.FileName;
string ArticleTitle = ArticleTitleTextBox.Text;
string ArticleContent = ArticleContentTextBox.Text;
string ArticleType = ArticleTypeDropdown.Text.ToString();
string ArticleAuthor = ArticleAuthorTextBox.Text.ToString();
string ArticleBrief = ArticleBriefTextBox.Text;
string ArticleDateTime = DateTime.Now.ToShortTimeString();
string query = "INSERT INTO ArticlesTBL (ArticleTitle, ArticleContent, ArticleType, ArticleImg, ArticleBrief, ArticleDateTime, ArticleAuthor, ArticlePublished, ArticleHomeDisplay, ArticleViews) VALUES (" + ArticleTitle +", " + ArticleContent +", "+ ArticleType +" " + ArticleImg +", "+ ArticleBrief +"," + ArticleDateTime + ", "+ ArticleAuthor +",'False', 'False', '0')";
SqlCommand myCommand = new SqlCommand(query, myConnection);
myCommand.ExecuteNonQuery();
// myinfo.Text = "connection to db is made";
myConnection.Close();
}
You should use parameters in your query to prevent attacks, like if someone entered '); drop table ArticlesTBL;--' as one of the values.
string query = "INSERT INTO ArticlesTBL (ArticleTitle, ArticleContent, ArticleType, ArticleImg, ArticleBrief, ArticleDateTime, ArticleAuthor, ArticlePublished, ArticleHomeDisplay, ArticleViews)";
query += " VALUES (#ArticleTitle, #ArticleContent, #ArticleType, #ArticleImg, #ArticleBrief, #ArticleDateTime, #ArticleAuthor, #ArticlePublished, #ArticleHomeDisplay, #ArticleViews)";
SqlCommand myCommand = new SqlCommand(query, myConnection);
myCommand.Parameters.AddWithValue("#ArticleTitle", ArticleTitleTextBox.Text);
myCommand.Parameters.AddWithValue("#ArticleContent", ArticleContentTextBox.Text);
// ... other parameters
myCommand.ExecuteNonQuery();
(xkcd)
using System;
using System.Data;
using System.Data.SqlClient;
namespace InsertingData
{
class sqlinsertdata
{
static void Main(string[] args)
{
try
{
SqlConnection conn = new SqlConnection("Data source=USER-PC; Database=Emp123;User Id=sa;Password=sa123");
conn.Open();
SqlCommand cmd = new SqlCommand("insert into <Table Name>values(1,'nagendra',10000);",conn);
cmd.ExecuteNonQuery();
Console.WriteLine("Inserting Data Successfully");
conn.Close();
}
catch(Exception e)
{
Console.WriteLine("Exception Occre while creating table:" + e.Message + "\t" + e.GetType());
}
Console.ReadKey();
}
}
}

Registration page error in .NET

i'm a newbie in .NET and C# field.
I'm creating a Registration page to a website im working on.
i keep getting an error when registering to a website i'm creating. When entering my details, it doesn't register me to the database.
I created the a table in the database(i created a connectionString), and yet i cannot register - i get an exception that says "error,please try registering again" (as i did).
Does someone know what am i doing wrong?! Thanks!
here's my code and images:
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;
public partial class Registration : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["RegisConnectionString"].ConnectionString);
con.Open();
string cmdStr = "Select count(*) from Table where Username='" + TextBox1Username.Text + "'";
SqlCommand userExist = new SqlCommand(cmdStr, con);
// int temp = Convert.ToInt32(userExist.ExecuteScalar().ToString());
con.Close();
/* if (temp == 1)
{
Response.Write("username already exists");
} */
}
}
protected void TextBox2_TextChanged(object sender, EventArgs e)
{
}
protected void Submit_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["RegisConnectionString"].ConnectionStr ing);
con.Open();
string insCmd = "Insert into Table (Username, Password, EmailAddress,Fullname, City) values (#Username, #Password, #EmailAddress, #Fullname, #City)";
SqlCommand insertUser = new SqlCommand(insCmd, con);
insertUser.Parameters.AddWithValue("#Username", TextBox1Username.Text);
insertUser.Parameters.AddWithValue("#Password", TextBox2Password.Text);
insertUser.Parameters.AddWithValue("#EmailAddress", TextBox4Email.Text);
insertUser.Parameters.AddWithValue("#Password", TextBox2Password.Text);
insertUser.Parameters.AddWithValue("#City", TextBox6City.Text);
try
{
insertUser.ExecuteNonQuery();
con.Close();
Response.Redirect("Login.aspx");
}
catch (Exception er)
{
Response.Write("error,please try registering again");
}
}
}
image:
[URL=http://imageshack.us/photo/my-images/4/os6b.jpg/][IMG=http://img4.imageshack.us/img4/2526/os6b.jpg][/IMG][/URL]
Uploaded with [URL=http://imageshack.us]ImageShack.us[/URL]
you are missing fullname in your parameter and you have password twice.fix that and run it again.
Also, in your catch block.. you should use exception message to debug or log somewhere where you can see the error clearly. the way you have it right now gives the error you typed. not actual message.
here is link where they are discussing about sqlexception. might be good idea to catch that.
SqlException catch and handling
You pass two times the password parameter in the insert query. The second one is in place of the #fullname parameter.
This will cause your insert command to fail because you don't provide the #fullname parameter expected by the query.
SqlCommand insertUser = new SqlCommand(insCmd, con);
insertUser.Parameters.AddWithValue("#Username", TextBox1Username.Text);
insertUser.Parameters.AddWithValue("#Password", TextBox2Password.Text);
insertUser.Parameters.AddWithValue("#EmailAddress", TextBox4Email.Text);
insertUser.Parameters.AddWithValue("#FullName", TextBox???????.Text); //<- Get from the correct textbox
insertUser.Parameters.AddWithValue("#City", TextBox6City.Text);
You could have found this problem yourself if, inside the catch, you had added the er.Message to your Response
try
{
insertUser.ExecuteNonQuery();
con.Close();
Response.Redirect("Login.aspx");
}
catch (Exception er)
{
Response.Write("error: " + er.Message + " ,please try registering again");
}

Categories

Resources