I have the codes up but when I try to update, it did not change anything. I am not sure where the problem went wrong
I have tried to change the index of email and others from 0-6 but when I use these index, everytime i tries to update, the email became UserID and so on.
Back End:
protected void gvAccount_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = (GridViewRow)gvAccount.Rows[e.RowIndex];
string UserID = gvAccount.DataKeys[e.RowIndex].Values["UserID"].ToString();
string Email = ((TextBox)row.Cells[1].Controls[0]).Text;
string FirstName = ((TextBox)row.Cells[2].Controls[0]).Text;
string LastName = ((TextBox)row.Cells[3].Controls[0]).Text;
string Password = ((TextBox)row.Cells[4].Controls[0]).Text;
string Point = ((TextBox)row.Cells[5].Controls[0]).Text;
string Role = ((TextBox)row.Cells[6].Controls[0]).Text;
SqlCommand cmd = new SqlCommand("UPDATE UserRegister set Email = '" + Email + "', FirstName = '" + FirstName + "', LastName = '" + LastName + "', Password = '" + Password + "',Point = '" + Point + "',Role = '" + Role + "' WHERE UserID =" + UserID, con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
gvAccount.EditIndex = -1;
FillGrid();
}
There is no error message, but it just did not update anything. I am not sure if is the WHERE UserID = UserID problem. UserID is my primary key
I think you've mistaken to take the value. For Excel I use like this:
string email= row[1].ToString();
string firstName = row[2].ToString();
string lastName = row[3].ToString();
string pass= row[4].ToString();
string point = row[5].ToString();
string role = row[6].ToString();
*Update
Something's wrong with your SQL, for the query try somethings like this:
string con = #"Data Source=myServerAddress;Initial Catalog=myDataBase Integrated Security=SSPI;
User ID=myDomain\myUsername;Password=myPassword;";
string comm = #"Update... SET... WHERE...";
SqlCommand cmd = new SqlCommand(comm, con);
Gridview.Databind();
Related
I also don't know how to add the values of comboboxes and gender radio buttons to the database. This is basically for a registration form to insert its values into a database. I also need to display the values of the database on the form from selecting the combobox value.
private void Btn_register_Click(object sender, EventArgs e)
{
//int regNo = Cbox_regNo.Text; //i need to get the values from the combobox
string fName = Tbox_fName.Text;
string lName = Tbox_lName.Text;
string dob = dtp_dob.Text;
string address = Tbox_address.Text;
string email = Tbox_email.Text;
string mPhone = Tbox_mPhone.Text;
string hPhone = Tbox_hPhone.Text;
string pName = Tbox_parentName.Text;
string nic = Tbox_nic.Text;
string cNumber = Tbox_cntctNumber.Text;
string connString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=\"C:\\Users\\abhin\\Desktop\\Final Project\\Visual Studio\\Final Project\\Final Project\\Student.mdf\";Integrated Security=True";
string Query = "insert into Registrations (regNo, firstName, lastName, dateOfBirth, gender, address, email, mobilePhone, homePhone, parentName, nic, contactNo) values('"+this.Cbox_regNo.Text+"','" + this.Tbox_fName.Text + "','" + this.Tbox_lName.Text + "','" + this.dtp_dob.Value + "','" + this.Tbox_address.Text + "','" + this.Tbox_email.Text + "','" + this.Tbox_mPhone.Text + "','" + this.Tbox_hPhone.Text + "','" + this.Tbox_parentName.Text + "','" + this.Tbox_nic.Text + "','" + this.Tbox_cntctNumber.Text + "') ;";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmdDB = new SqlCommand(Query, conn);
SqlDataReader myReader;
try
{
conn.Open();
myReader=cmdDB.ExecuteReader();
MessageBox.Show("Record Added Succesfully", "Register Student", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
while (myReader.Read())
{
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
conn.Close();
}
}
On declaring your “Query” variable you are using 12 column (regNo, firstName…) and 11 value. You need one more value
I have 2 textboxes and 2 labels.
label: UserID & ACCType.
textbox: Email & Password.
I want to find data from the textboxes and then insert data from the database into the 2 labels.
so, in other words, I would like to collect the email and password in the textboxes. from this information, i want to then insert the ID and AccountType in the labels. what am I doing wrong?
protected void Login_Click(object sender, EventArgs e)
{
string UID = UserID.Text;
string AType = AccType.Text;
string Email = Email.Text;
string Password = Password.Text;
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=sql2016.fse.network;Initial Catalog=db_1518393_fse_rec; User ID=user_db_1518393_fse_rec; Password=P#55word;";
Int32 verify;
string query1 = "Select * from Accounts where Email='" + Email.Text + "' and Password='" + Password.Text + "' ";
SqlCommand cmd1 = new SqlCommand(query1, con);
con.Open();
verify = Convert.ToInt32(cmd1.ExecuteScalar());
con.Close();
if (verify > 0)
{
//successful
ErrorMessage.Text += "Logging in...";
//Response.Redirect("succesful.aspx");
//display User ID & Account Type
string query2 = "INSERT * from Accounts where Email='" + Email.Text + "' and Password='" + Password.Text + "' + ID + AccountType";
//string query2 = "Select Email, Password, ID, AccountType from Accounts(Email, Password, ID, AccountType) " + "Values('" + Email + "', '" + Password + "', '" + UID + "', '" + AType + "')";
}
else
{
//unsuccessful
//Response.Redirect("unsuccesful.aspx", true);
ErrorMessage.Text += "Email or Password incorrect! Please try again.";
}
}
this is wrong
string query2 = "INSERT * from Accounts where Email='" + Email.Text + "' and Password='" + Password.Text + "' + ID + AccountType";
should be like this
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
as showing in W3Schools here
Few things to consider here...
First, as many people noticed (and always will here on SO), NEVER concatenate strings for commnand text. Instead, user parameters, like this:
string query1 = "Select * from Accounts where Email=#Email and Password=#Password ";
cmd.Parameters.Add("#Email", SqlDbType.VarChar).Value = Email.Text;
cmd.Parameters.Add("#Password", SqlDbType.VarChar).Value = Password.Text;
Second, you are using ExecuteScalar which only return number of affected rows. Instead, you should read data with DataReader. Something like this:
SqlDataReader reader = cmd1.ExecuteReader();
verify = reader.HasRows;
if (verify)
{
ErrorMessage.Text += "Logging in...";
reader.Read();
this.lblUserId.Text = reader["ID"].ToString();
//read other data into other labels
}
con.Close();
third, you INSERT syntax is wrong and should be like this:
string query2 = #"
INSERT INTO Accounts
(Email, Password, ID, AccountType)
VALUES
(#Email, #Password, #ID, #AccountType)
";
cmd.Parameters.Add("#Email", SqlDbType.VarChar).Value = Email.Text;
cmd.Parameters.Add("#Password", SqlDbType.VarChar).Value = Password.Text;
cmd.Parameters.Add("#ID", SqlDbType.Int).Value = /* some ID textbox or what ever */;
cmd.Parameters.Add("#AccountType", SqlDbType.Int).Value = /* some value for acc type */;
... and fourth:
why do you enter account data into table after user successfully logged in?
You said you want to update the labels after collecting email and password from the textboxes which i guess can be achieved using the 'query1', if the Account table of yours contain the field 'UserId' and 'AccountType'. You should use DataReader instead of ExecuteScalar for verification and reading of data from db and update the labels with UserId and AccountType. Following can be the hypothetical answer of yours:-
SqlDataReader dr = cmd1.ExecuteReader();
if(dr.HasRows)
{
//if email and password is okay
while(dr.Read())
{
//successful
ErrorMessage.Text += "Logging in...";
//Response.Redirect("succesful.aspx");
//display User ID & Account Type
UserId.Text = (string)dr["userid"];
AccType.Text = (string)dr["accounttype"];
}
}
else{
//unsuccessful
//Response.Redirect("unsuccesful.aspx", true);
ErrorMessage.Text += "Email or Password incorrect! Please try again.";
}
And Finally, I have no idea on why you trying to insert any data to the Account table after logging in. I mean you should update some field on your table instead of inserting a new row into the table.
I have two queries.. what I want to do is if the login control finds the username and password in 1st query table redirect it to seller page.. If it finds the un and pw in 2nd query table then redirect it to the dealer page. How can I do that? Coz it only checks the first query.
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
var conString = ConfigurationManager.ConnectionStrings["CONSTRING"].ConnectionString;
SqlConnection con = new SqlConnection(conString);
string user = Login1.UserName;
string pass = Login1.Password;
con.Open();
SqlCommand cmd1 = new SqlCommand("select username, password, status from login where username = '" + user + "' and password = '" + pass + "' and status = 1", con);
string CurrentName;
CurrentName = (string)cmd1.ExecuteScalar();
if (CurrentName != null)
{
Session.Timeout = 1;
Session["un"] = Login1.UserName;
Response.Redirect("sellerlogin.aspx?un=" + Login1.UserName);
}
SqlCommand cmd2 = new SqlCommand("select username, password, status from dealer where username = '" + user + "' and password = '" + pass + "' ", con);
string CurrentNam;
CurrentNam = (string)cmd2.ExecuteScalar();
if (CurrentNam != null)
{
Session.Timeout = 1;
Response.Redirect("dealerlogin.aspx?un="+ Login1.UserName);
}
Try using:
Response.End();
return;
With your code:
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
var conString = ConfigurationManager.ConnectionStrings["CONSTRING"].ConnectionString;
SqlConnection con = new SqlConnection(conString);
string user = Login1.UserName;
string pass = Login1.Password;
con.Open();
SqlCommand cmd1 = new SqlCommand("select username, password, status from login where username = '" + user + "' and password = '" + pass + "' and status = 1", con);
string CurrentName;
CurrentName = (string)cmd1.ExecuteScalar();
if (CurrentName != null)
{
Session.Timeout = 1;
Session["un"] = Login1.UserName;
Response.Redirect("sellerlogin.aspx?un=" + Login1.UserName);
Response.End();
return;
}
SqlCommand cmd2 = new SqlCommand("select username, password, status from dealer where username = '" + user + "' and password = '" + pass + "' ", con);
string CurrentNam;
CurrentNam = (string)cmd2.ExecuteScalar();
if (CurrentNam != null)
{
Session.Timeout = 1;
Response.Redirect("dealerlogin.aspx?un="+ Login1.UserName);
Response.End();
return;
}
i was trying to update two tables at once, but i got some syntax error on update code could u give me some idea? the insert code works perfect and i tried to copy the insert code and edit on update button clicked
here is my code
private void button2_Click(object sender, EventArgs e)
{
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;" +
#"Data source= C:\Users\user\Documents\Visual Studio 2010\Projects\WindowsFormsApplication1\WindowsFormsApplication1\crt_db.accdb";
try
{
conn.Open();
String Name = txtName.Text.ToString();
String AR = txtAr.Text.ToString();
String Wereda = txtWereda.Text.ToString();
String Kebele = txtKebele.Text.ToString();
String House_No = txtHouse.Text.ToString();
String P_O_BOX = txtPobox.Text.ToString();
String Tel = txtTel.Text.ToString();
String Fax = txtFax.Text.ToString();
String Email = txtEmail.Text.ToString();
String Item = txtItem.Text.ToString();
String Dep = txtDep.Text.ToString();
String k = "not renwed";
String Remark = txtRemark.Text.ToString();
String Type = txtType.Text.ToString();
String Brand = txtBrand.Text.ToString();
String License_No = txtlicense.Text.ToString();
String Date_issued = txtDate.Text.ToString();
String my_querry = "update crtPro set Name='" + Name + "',AR='" + AR + "',Wereda='" + Wereda + "',Kebele='" + Kebele + "',House_No='" + House_No + "',P_O_BOX='" + P_O_BOX + "',Tel='" + Tel + "',Fax='" + Fax + "',Email='" + Email + "',Item='" + Item + "',Dep='" + Dep + "','" + k + "',Remark='" + Remark + "' where Name='" + Name + "' ";
OleDbCommand cmd = new OleDbCommand(my_querry, conn);
cmd.ExecuteNonQuery();
String my_querry1 = "SELECT max(PID) FROM crtPro";
OleDbCommand cmd1 = new OleDbCommand(my_querry1, conn);
string var = cmd1.ExecuteScalar().ToString();
String ki = txtStatus.Text.ToString();
String my_querry2 = "update crtItemLicense set PID=" + var + ",Type='" + Type + "',Brand='" + Brand + "',License_No='" + License_No + "',Date_issued='" + Date_issued + "' where PID=" + var + "";
OleDbCommand cmd2 = new OleDbCommand(my_querry2, conn);
cmd2.ExecuteNonQuery();
MessageBox.Show("Message added succesfully");
}
catch (Exception ex)
{
MessageBox.Show("Failed due to" + ex.Message);
}
finally
{
conn.Close();
}
The most likely problem based on the little information given (what database are you using for example - SQL Server 2012?), is that the datatype you are providing in the concatenated dynamic sql does not match the datatype of the column in the database. You've surrounded each value with quotes - which means it will be interpreted as a varchar. If you've got a date value in the wrong format (ie if Date_Issued is a date column) or if it is a number column, then it will error.
The solution is to replace your dynamic SQL with a parameterized query eg:
String my_querry = "update crtPro set Name=#name, AR=#ar, Wereda=#Wereda, etc ...";
OleDbCommand cmd = new OleDbCommand(my_querry, conn);
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#name", Name);
cmd.Parameters.AddWithValue("#myParam", Convert.ToDateTime(txtDate.Text.Trim()));
...
cmd.ExecuteNonQuery();
You can read about it further here
PS Make sure your parameters are in the same order as they are used in the SQL, because oledbcommand doesn't actually care what you call them. see here
i have a code like this:
public int updateFriend(long id, string Firstname, string Lastname, string Nickname, DateTime Birthdate, int Age, string Gender)
{
OleDbConnection con = new OleDbConnection(conString());
string query = "UPDATE FriendList SET Firstname ='" + Firstname + "', Lastname ='" + Lastname + "',Nickname ='" + Nickname + "',Birthday ='" + Birthdate + "',Age ='" + Age + "', Gender ='" + Gender + "' WHERE ID = " + id;
OleDbCommand cmd = new OleDbCommand(query, con);
con.Open();
int rowsAffected = cmd.ExecuteNonQuery();
con.Close();
return (rowsAffected);
}
now the problem is when i click the update button it calls the method updateFriend, then an error appears on the Line "int rowsAffected = cmd.ExecuteNonQuery();" saying
"No value given for one or more required parameters."
Can somebody help me with this?
string query = "UPDATE FriendList SET Firstname ='" + Firstname + "', Lastname ='" + Lastname + "',Nickname ='" + Nickname + "',Birthday ='" + Birthdate + "',Age ='" + Age + "', Gender ='" + Gender + "' WHERE ID = " + id;
You are passing all parameters as string where some of them are int and one is DateTime. As suggested you should use Parameters.AddWithValue()
string query = "UPDATE FriendList SET Firstname = #Firstname, Lastname = #Lastname , Nickname = #Nickname, Birthday = #Birthdate, Age = #Age, Gender = #Gender WHERE ID = #id";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#Firstname", FirstName);
//add rest parameters the same way as above
cmd.Parameters.AddWithValue("#id", id);
Talking about on your error message;
"No value given for one or more required parameters."
This message will appears probably one of your parameters is null or zero-length string. Or the reason can be misspelling of your parameters.
Check your query in your database first and look which column gives you an error.
And please, never add your parameters in your sql command. That may cause SQL Injection attack. Always use parameterized query on your queries.
Check out SqlParameterCollection.AddWithValue() method from MSDN.