When I fill out the form and click registration, it shows an error:
Object reference not set to an instance of an object.
The error is here:
int temp=Convert.ToInt32(com.ExecuteScalar().ToString());
Which object must be added to refrence?
Here is the code of the web page:
public partial class register : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Page.DataBind();
if(IsPostBack)
{
SqlConnection conn = new
SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionS
tring"].ConnectionString);
conn.Open();
string checkuser = "SELECT * FROM [Table] where user_name ='" +
Text_username + "'";
SqlCommand com = new SqlCommand (checkuser , conn);
int temp=Convert.ToInt32(com.ExecuteScalar().ToString());
if (temp == 1){
Response.Write("User already exists");
}
conn.Close();
}
}
protected void Button2_Click(object sender, EventArgs e)
{
Text_fname.Text = "";
Text_lname.Text = "";
Text_email.Text = "";
Text_password.Text = "";
Text_password_again.Text = "";
Text_username.Text = "";
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new
SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionS
tring"].ConnectionString);
conn.Open();
string insert = "insert into Table
(user_fname,user_lname,user_email,user_password,user_name) values (#firstName
,#lastName ,#Email ,#passWord ,#userName)";
SqlCommand com = new SqlCommand (insert , conn);
com.Parameters.AddWithValue("#firstName", Text_fname.Text);
com.Parameters.AddWithValue("#lastName", Text_lname.Text);
com.Parameters.AddWithValue("#Email", Text_email.Text);
com.Parameters.AddWithValue("#passWord", Text_password.Text);
com.Parameters.AddWithValue("#userName", Text_username.Text);
com.ExecuteNonQuery();
Response.Write("Registration is successful");
Response.Redirect("Default.aspx");
conn.Close();
}
catch (Exception ex)
{
Response.Write("Error: " + ex.ToString());
}
}
}
From the error message you have posted, it is clear that the com.ExecuteScalar() is null. Hence, when you call the ToString method on it you get a null reference exception. Since the com.ExecuteScalar() can be null, I suggest you do a check for this.
int temp;
var result = com.ExecuteScalar();
if(result != null)
{
temp = Convert.ToInt32(result.ToString());
}
if (temp == 1)
{
Response.Write("User already exists");
}
Related
So I used the Response.Redirect control to move to a page called "Equipment.aspx" and it was working fine but after a while it started to get redirected to the page "OpeningPage.aspx".
I tried creating those pages again and changed the name of the page from "OpeningPage.aspx" to "Opening_Page.aspx" and when i tried running it showed http:404 file not found error and RequestedURL:/OpeningPage.aspx
SqlConnection sqlcon = new SqlConnection(con);
sqlcon.Open();
string checkuser = "SELECT count(*) FROM UserAccounts WHERE UserName = '" + username.Text + "'";
SqlCommand cmd = new SqlCommand(checkuser, sqlcon);
int temp = Convert.ToInt32(cmd.ExecuteScalar().ToString());
sqlcon.Close();
if (temp == 1)
{
sqlcon.Open();
string checkpassword = "SELECT Password FROM UserAccounts WHERE UserName = '" + username.Text + "'";
SqlCommand cmdt = new SqlCommand(checkpassword, sqlcon);
string tem = cmdt.ExecuteScalar().ToString();
if (tem == password.Text)
{
Session["usersession"] = username.Text;
Response.Redirect("Equipment.aspx");
}
else
{
Response.Write("incorrect password");
}
}
else
{
Response.Write("incorrect username");
}
the following is the code for the "Equipment.aspx.cs" page:
protected void Page_Load(object sender, EventArgs e)
{
if(Session["usersession"] != null )
{
usernam.Text = Session["usersession"].ToString();
}
else
{
Response.Redirect("Login.aspx");
}
}
protected void logout_Click(object sender, EventArgs e)
{
Session.RemoveAll();
Response.Redirect("~/Opening_Page.aspx");
}
i want to check if the username already exists in the database and if yes, error message will prompt that says "username already exist". now i have this code but its not working. program still accepts the username even if it is duplicated from the database. can someone help me out pls? here is my whole registration code:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string checkuser = "select count(*) from UserData where Username = '" + txtUser.Text + "'";
SqlCommand scm = new SqlCommand(checkuser, conn);
int temp = Convert.ToInt32(scm.ExecuteScalar().ToString());
if (temp == 1) // check if user already exist.
{
Response.Write("User already existing");
}
conn.Close();
}
}
protected void btn_Registration_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string insertQuery = "insert into UserData(Username,Firstname,Lastname,Email,Password,CustomerType,DeliveryAddress,Zip,ContactNumber)values(#Username,#Firstname,#Lastname,#Email,#Password,#CustomerType,#DeliveryAddress,#Zip,#ContactNumber)";
SqlCommand scm = new SqlCommand(insertQuery, conn);
scm.Parameters.AddWithValue("#Username", txtUser.Text);
scm.Parameters.AddWithValue("#Firstname", txtFN.Text);
scm.Parameters.AddWithValue("#Lastname", txtLN.Text);
scm.Parameters.AddWithValue("#Email", txtEmail.Text);
scm.Parameters.AddWithValue("#Password", BusinessLayer.ShoppingCart.CreateSHAHash(txtPW.Text));
scm.Parameters.AddWithValue("#CustomerType", RadioButtonList1.SelectedItem.ToString());
scm.Parameters.AddWithValue("#DeliveryAddress", txtAddress.Text);
scm.Parameters.AddWithValue("#Zip", txtZip.Text);
scm.Parameters.AddWithValue("#ContactNumber", txtContact.Text);
scm.ExecuteNonQuery();
Session["Contact"]= txtContact.Text;
Session["Email"] = txtEmail.Text;
Session["DeliveryAddress"] = txtAddress.Text;
label_register_success.Text = ("Registration Successful!");
//Response.Redirect("Home.aspx");
conn.Close();
}
catch (Exception ex)
{
Response.Write("Error:" + ex.ToString());
}
}
You validate data on Page_Load? I think, you can choose to these solusions
You have to do it in btn_Registration_Click before you insert the
data, or
Maybe, you can modify it to do in sp and throw message through it if data is
duplicated and do the checking there.
It should be like this (according to solution 1)
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
}
}
protected void btn_Registration_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string checkuser = "select count(*) from UserData where Username = '" + txtUser.Text + "'";
SqlCommand scm = new SqlCommand(checkuser, conn);
int temp = Convert.ToInt32(scm.ExecuteScalar().ToString());
if (temp > 0) // check if user already exist.
{
Response.Write("User already existing");
}
else
{
string insertQuery = "insert into UserData(Username,Firstname,Lastname,Email,Password,CustomerType,DeliveryAddress,Zip,ContactNumber)values(#Username,#Firstname,#Lastname,#Email,#Password,#CustomerType,#DeliveryAddress,#Zip,#ContactNumber)";
scm = new SqlCommand(insertQuery, conn);
scm.Parameters.AddWithValue("#Username", txtUser.Text);
scm.Parameters.AddWithValue("#Firstname", txtFN.Text);
scm.Parameters.AddWithValue("#Lastname", txtLN.Text);
scm.Parameters.AddWithValue("#Email", txtEmail.Text);
scm.Parameters.AddWithValue("#Password", BusinessLayer.ShoppingCart.CreateSHAHash(txtPW.Text));
scm.Parameters.AddWithValue("#CustomerType", RadioButtonList1.SelectedItem.ToString());
scm.Parameters.AddWithValue("#DeliveryAddress", txtAddress.Text);
scm.Parameters.AddWithValue("#Zip", txtZip.Text);
scm.Parameters.AddWithValue("#ContactNumber", txtContact.Text);
scm.ExecuteNonQuery();
Session["Contact"]= txtContact.Text;
Session["Email"] = txtEmail.Text;
Session["DeliveryAddress"] = txtAddress.Text;
label_register_success.Text = ("Registration Successful!");
//Response.Redirect("Home.aspx");
}
conn.Close();
}
catch (Exception ex)
{
Response.Write("Error:" + ex.ToString());
}
}
i have an error as which is on the button click event, as its shows me an error message on this line:
com.EndExecuteNonQuery();
message text: Error 2 No overload for method 'EndExecuteNonQuery' takes 0 arguments
Thank you for your support
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["usradmadslistview"].ConnectionString);
conn.Open();
string cmdStr = "Select count(*) from UserInfo where UID = '" + UsrNme.Text + "'";
SqlCommand com = new SqlCommand(cmdStr, conn);
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
if (temp == 1)
{
chkusrnamlbl.Visible = true;
}
conn.Close();
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["usradmadslistview"].ConnectionString);
conn.Open();
string insertquery = "insert into UserInfo (UID,FN,LN,Password,Email,CountID,State,City) Values (#username,#firstn,#lastn,#passbox,#email1,#country,#state,#city)";
SqlCommand com = new SqlCommand(insertquery, conn);
com.Parameters.AddWithValue("#username", UsrNme.Text);
com.Parameters.AddWithValue("#firstn", fnbox.Text);
com.Parameters.AddWithValue("#lastn", lnamebox.Text);
com.Parameters.AddWithValue("#passbox", passtxtbx1.Text);
com.Parameters.AddWithValue("#email1", emailbox.Text);
com.Parameters.AddWithValue("#country", DrDncoundrlst.SelectedItem.ToString());
com.Parameters.AddWithValue("#state", DropDownListSwestate.SelectedItem.ToString());
com.Parameters.AddWithValue("#city", citytxtbox.Text);
com.EndExecuteNonQuery();
Response.Redirect("User panel.aspx");
conn.Close();
}
catch(Exception ex) {
Response.Write("Error:" + ex.ToString());
}
EndExecuteNonQuery requires an IAsyncResult parameter as mentioned here in MSDN.
Also, is this just a code snippet? Because I think you would want to use com.ExecuteNonQuery() instead. EndExecuteNonQuery is the end pair for asynchronously executing SQL statements.
I want to get next record from table to show as Question. With below code I am not able to get next Question from table.
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false)
{
Quiz_Load();
}
}
private void Quiz_Load()
{
try
{
if (Session["UserQuizID"] != null)
{
string mayank = "mm.bhagat";
string UserQuiz_ID = Session["UserQuizID"].ToString();
SqlConnection con = new SqlConnection(c);
SqlCommand cmd = new SqlCommand("select top 0.1 percent QuestionID, Title, Answer1,Answer2,Answer3,Answer4,UserAnswer from [Table_UserAnswer] WHERE UserQuizID = '" + UserQuiz_ID.ToString() + "' AND UserName = '" + mayank.ToString() + "' order by newid()", con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
Session["QuestionID"] = dr[0].ToString();
Lbl_QuestionTitle.Text = dr[1].ToString();
RadBut_Answer.Items.Add(dr[2].ToString());
RadBut_Answer.Items.Add(dr[3].ToString());
RadBut_Answer.Items.Add(dr[4].ToString());
RadBut_Answer.Items.Add(dr[5].ToString());
Session["UserAnswer"] = dr[6].ToString();
}
else
{
}
con.Close();
}
else
{
Response.Redirect("Start.aspx");
}
}
catch
{
}
}
protected void RadBut_Answer_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
int getvalue;
getvalue = Convert.ToInt32(RadBut_Answer.SelectedIndex + 1);
Lbl_SelectedAnsMsg.Text = MessageFormatter.GetFormattedAlertsMessage("Your Selected Answer is : " + getvalue.ToString());
Session["UserAnswer"] = getvalue.ToString();
}
catch
{
}
}
protected void But_Next_Click(object sender, EventArgs e)
{
UpdateUserAns();
if (Session["UserAnswer"] == null)
{
Response.Redirect("Result.aspx");
}
else
{
}
}
private void UpdateUserAns()
{
try
{
string mayank = "mm.bhagat";
string UserQuiz_ID = Session["UserQuizID"].ToString();
string Question_ID = Session["QuestionID"].ToString();
string User_Answer = Session["UserAnswer"].ToString();
SqlConnection con = new SqlConnection(c);
SqlCommand cmd = new SqlCommand("UPDATE Table_UserAnswer SET UserAnswer='" + User_Answer.ToString() + "' WHERE UserQuizID = '"+ UserQuiz_ID.ToString() +"' AND QuestionID = '"+Question_ID.ToString()+"' AND UserName = '"+mayank.ToString()+"'", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
cmd.Cancel();
}
catch
{
}
}
hi check this post client here
here you can find solution of your question
I can add, edit, delete database using listbox. But I want to do it using DatagridView I already bind it to my database.
How do I add,edit,delete update my database in datagridview using codes?
These are my codes:
namespace Icabales.Homer
{
public partial class Form1 : Form
{
SqlConnection cn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=c:\users\homer\documents\visual studio 2010\Projects\Icabales.Homer\Icabales.Homer\Database1.mdf;Integrated Security=True;User Instance=True");
SqlCommand cmd = new SqlCommand();
SqlDataReader dr;
SqlDataAdapter da;
DataTable dt = new DataTable();
public Form1()
{
InitializeComponent();
}
private void bindgrid()
{
string command = "select * from info";
da = new SqlDataAdapter(command, cn);
da.Fill(dt);
dataGridView1.DataSource = dt;
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'database1DataSet.info' table. You can move, or remove it, as needed.
this.infoTableAdapter.Fill(this.database1DataSet.info);
cmd.Connection = cn;
loadlist();
bindgrid();
}
private void button1_Click(object sender, EventArgs e)
{
if (txtid.Text != "" & txtname.Text != "")
{
cn.Open();
cmd.CommandText = "insert into info (id,name) values ('" + txtid.Text + "' , '" + txtname.Text + "')";
cmd.ExecuteNonQuery();
cmd.Clone();
MessageBox.Show("Record Inserted");
cn.Close();
txtid.Text = "";
txtname.Text = "";
loadlist();
}
}
private void loadlist()
{
listBox1.Items.Clear();
listBox2.Items.Clear();
cn.Open();
cmd.CommandText = "select * from info";
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
listBox1.Items.Add(dr[0].ToString());
listBox2.Items.Add(dr[1].ToString());
}
}
cn.Close();
}
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
ListBox l = sender as ListBox;
if (l.SelectedIndex != -1)
{
listBox1.SelectedIndex = l.SelectedIndex;
listBox2.SelectedIndex = l.SelectedIndex;
txtid.Text = listBox1.SelectedItem.ToString();
txtname.Text = listBox2.SelectedItem.ToString();
}
}
private void button2_Click(object sender, EventArgs e)
{
if (txtid.Text != "" & txtname.Text != "")
{
cn.Open();
cmd.CommandText = "delete from info where id = '"+txtid.Text+"'and name = '"+txtname.Text+"'";
cmd.ExecuteNonQuery();
cn.Close();
MessageBox.Show("Record Deleted");
loadlist();
txtid.Text = "";
txtname.Text = "";
}
}
private void button3_Click(object sender, EventArgs e)
{
if (txtid.Text != "" & txtname.Text != "" & listBox1.SelectedIndex != -1)
{
cn.Open();
cmd.CommandText = "update info set id='"+txtid.Text+"',name='"+txtname.Text+"'where id='"+listBox1.SelectedItem.ToString()+"' and name='"+listBox2.SelectedItem.ToString()+"'";
cmd.ExecuteNonQuery();
cn.Close();
MessageBox.Show("Record Updated");
loadlist();
txtid.Text = "";
txtname.Text = "";
}
}
}
}
I have a dataGridView and a button on a form. When I do any editing, insertion or deletion in the dataGridView1, the code below does the magic
public partial class EditPermit : Form
{
OleDbCommand command;
OleDbDataAdapter da;
private BindingSource bindingSource = null;
private OleDbCommandBuilder oleCommandBuilder = null;
DataTable dataTable = new DataTable();
public EditPermit()
{
InitializeComponent();
}
private void EditPermitPermit_Load(object sender, EventArgs e)
{
DataBind();
}
private void btnSv_Click(object sender, EventArgs e)
{
dataGridView1.EndEdit(); //very important step
da.Update(dataTable);
MessageBox.Show("Updated");
DataBind();
}
private void DataBind()
{
dataGridView1.DataSource = null;
dataTable.Clear();
String connectionString = MainWindow.GetConnectionString(); //use your connection string please
String queryString1 = "SELECT * FROM TblPermitType"; // Use your table please
OleDbConnection connection = new OleDbConnection(connectionString);
connection.Open();
OleDbCommand command = connection.CreateCommand();
command.CommandText = queryString1;
try
{
da = new OleDbDataAdapter(queryString1, connection);
oleCommandBuilder = new OleDbCommandBuilder(da);
da.Fill(dataTable);
bindingSource = new BindingSource { DataSource = dataTable };
dataGridView1.DataSource = bindingSource;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
I have implemented a solution that inserts/updates/deletes data in MS SQL database directly from DataGridView.
To accomplish this I have used the following events: RowValidating and UserDeletingRow.
It is supposed that you have
SqlConnection _conn;
declared and initialized.
Here is the code:
private void dgv_RowValidating( object sender, DataGridViewCellCancelEventArgs e )
{
try
{
if (!dgv.IsCurrentRowDirty)
return;
string query = GetInsertOrUpdateSql(e);
if (_conn.State != ConnectionState.Open)
_conn.Open();
var cmd = new SqlCommand( query, _conn );
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show( ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning );
}
}
public string GetInsertOrUpdateSql( DataGridViewCellCancelEventArgs e )
{
DataGridViewRow row = dgv.Rows[e.RowIndex];
int id = 0;
int.TryParse( row.Cells["Id"].Value.ToString(), out id );
DateTime dob;
DateTime.TryParse( row.Cells["Dob"].Value.ToString(), out dob );
string email = row.Cells["Email"].Value.ToString();
string phone = row.Cells["Phone"].Value.ToString();
string fio = row.Cells["Fio"].Value.ToString();
if (id == 0)
return string.Format( "insert into {0} Values ('{1}','{2}','{3}','{4}')", "dbo.People", fio, dob.ToString( "dd-MM-yyyy" ), email, phone );
else
return string.Format( "update {0} set Fio='{1}', Dob='{2}', Email='{3}', Phone='{4}' WHERE Id={5}", "dbo.People", fio, dob.ToString( "dd-MM-yyyy" ), email, phone, id );
}
private void dgv_UserDeletingRow( object sender, DataGridViewRowCancelEventArgs e )
{
try
{
int id = 0;
int.TryParse( e.Row.Cells["Id"].Value.ToString(), out id );
string query = string.Format( "DELETE FROM {0} WHERE Id = {1}", "dbo.People", id );
var cmd = new SqlCommand( query, _conn );
if (_conn.State != ConnectionState.Open)
_conn.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show( ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning );
}
}
Hope this helps.
I have the same kind of project at home, I do not have the source code with me but if needed I can check somewhere this weekend to see what exactly I have done, but I believe it's some of the following:
Since you are using a dataset and a dataadapter this can be achieved very easily.
As long as your DataGridView1 has the properties enabled for users to add/delete/edit rows you could use the following code.
DataAdapter.Update(DataTable);
//in your code this would be:
da.Update(dt);
The DataAdapter.Update() Method will auto generate any insert/update/delete commands needed to update the results of your fill query compared with the current data in your datagridview.
You can set those commands (properties) as well in case you prefer to modify them, though this is not necessary.
This only works ofcourse after a user has made changes to the DataGridView. Add this code to a simple button and see if you have any luck. It definitly was something this simple :)