I am trying to update my database table ExpenseManagement. But it is not Updated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
public partial class UserProfile : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
txtUserId.Text = Request.Cookies["txtUserName"].Value;
string con_string = #"data Source= 10.10.10.5; initial catalog= test; user= xx; password= xxxxxxxxx;";
SqlConnection con = new SqlConnection(con_string);
SqlCommand cmd = new SqlCommand("select FirstName, LastName, Password, EmailId, MobileNumber from ExpenseManagement where UserId ='"+txtUserId.Text+"'", con);
cmd.Parameters.AddWithValue("#UserId", txtUserId.Text);
con.Open();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
txtFirstName.Text = dt.Rows[0]["FirstName"].ToString();
txtLastName.Text = dt.Rows[0]["LastName"].ToString();
txtPassword.Text= dt.Rows[0]["Password"].ToString();
txtEmailId.Text = dt.Rows[0]["EmailId"].ToString();
txtMobileNumber.Text = dt.Rows[0]["MobileNumber"].ToString();
con.Close();
txtUserId.Enabled = false;
txtFirstName.Enabled=false;
txtLastName.Enabled=false;
txtPassword.Enabled = false;
txtEmailId.Enabled = false;
txtMobileNumber.Enabled = false;
btnUpdate.Visible = false;
}
protected void Button1_Click1(object sender, EventArgs e)
{
txtUserId.Enabled = true;
txtUserId.ReadOnly = true;
txtFirstName.Enabled = true;
txtLastName.Enabled = true;
txtPassword.Enabled = true;
txtMobileNumber.Enabled = true;
txtEmailId.Enabled = true;
btnUpdate.Visible = true;
btnEdit.Visible = false;
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
string con_string = #"data Source= 10.10.10.5; initial catalog= test; user= xx; password= xxxxxxxxx;";
SqlConnection con = new SqlConnection(con_string);
string qryUpdate = "Update ExpenseManagement set FirstName= #FirstName, LastName=#LastName, Password=#Password, EmailId=#EmailId,MobileNumber=#MobileNumber where UserId= #UserId";
SqlCommand cmd = new SqlCommand(qryUpdate, con);
cmd.Parameters.AddWithValue("#UserId", txtUserId.Text);
cmd.Parameters.AddWithValue("#FirstName", txtFirstName.Text);
cmd.Parameters.AddWithValue("#LastName", txtLastName.Text);
cmd.Parameters.AddWithValue("#Password", txtPassword.Text);
cmd.Parameters.AddWithValue("#EmailId", txtEmailId.Text);
cmd.Parameters.AddWithValue("#MobileNumber", txtMobileNumber.Text);
con.Open();
if (Page.IsValid)
{
cmd.ExecuteNonQuery();
btnEdit.Visible = true;
}
con.Close();
}
}
I have next database fields:
UserId, FirstName, LastName, Password, EmailId, MobileNumber.
Missing the Page.IsPostBack check on the Page_Load event.
In ASP.NET, when you raise an event on a server side control, the Page_Load event is always executed before the code in the control event.
In your case, your user changes the textboxes, then presses the Update button. This raises the Page_Load event followed by the btnUpdate_Click event. Without a check on the property IsPostBack, the Page_Load event reloads the textboxes from the database with the original values effectively destroying the data typed by the user, then the button event code is called. But at this point the values in the textboxes are the original ones, so your code runs correctly, but doesn't change anything.
Change the Page_Load event adding
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
txtUserId.Text = Request.Cookies["txtUserName"].Value;
string con_string = #"data Source= 10.10.10.5; initial catalog= test; user= xx; password= xxxxxxxxx;";
SqlConnection con = new SqlConnection(con_string);
SqlCommand cmd = new SqlCommand(#"select FirstName, LastName, Password,
EmailId, MobileNumber
from ExpenseManagement
where UserId =#usedId", con);
cmd.Parameters.AddWithValue("#UserId", txtUserId.Text);
con.Open();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
......
btnUpdate.Visible = false;
}
}
I could recommend for the command to be more readable to user # instead of concatenating strings with "+" sign as below:
protected void btnUpdate_Click(object sender, EventArgs e)
{
string con_string = #"data Source= 10.10.10.5;initial catalog= test; user= xx; password= xxxxxxxxx;";
SqlConnection con = new SqlConnection(con_string);
string qryUpdate = #"Update ExpenseManagement
set FirstName= #FirstName,
LastName=#LastName,
Password=#Password,
EmailId=#EmailId,
MobileNumber=#MobileNumber
where UserId= #UserId";
SqlCommand cmd = new SqlCommand(qryUpdate, con);
cmd.Parameters.AddWithValue("#UserId", Convert.ToInt32(txtUserId.Text));
cmd.Parameters.AddWithValue("#FirstName", txtFirstName.Text);
cmd.Parameters.AddWithValue("#LastName", txtLastName.Text);
cmd.Parameters.AddWithValue("#Password", txtPassword.Text);
cmd.Parameters.AddWithValue("#EmailId", txtEmailId.Text);
cmd.Parameters.AddWithValue("#MobileNumber", txtMobileNumber.Text);
con.Open();
if (Page.IsValid)
{
cmd.ExecuteNonQuery();
btnEdit.Visible = true;
}
con.Close();
}
Also I agree with RezaRahmati to convert the userId and other parameters to correct types you have defined in your database, table columns.
I think the problem is using cmd.Parameters.AddWithValue("#UserId", txtUserId.Text); because it add a parameter of type string (because txtUserId.Text is string) instead of int or long, so change it to cmd.Parameters.AddWithValue("#UserId", int.parse(txtUserId.Text)); or use cmd.Parameters.Add() which takes type as argument.
Related
This is my code behind for data update. But it is not updating in my database. Don't know why. Any suggestion pls.
I've check the database connection and it is working fine. I didn't declare the connection string using {..}.
Actually I didn't get any error message for the insert. I got an record update message. But in my database, it is not updating.
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;
using System.Configuration;
namespace StudentDataDisplay2
{
public partial class Form1 : Form
{
SqlConnection conn = new SqlConnection(#"Data Source=localhost;Initial Catalog=TestData;Integrated Security=True");
public Form1()
{
InitializeComponent();
this.Text = "Student Data Display Form";
}
private void Form1_Load(object sender, EventArgs e)
{
}
public void display_data()
{
conn.Open();//establish connection
SqlCommand cmd = conn.CreateCommand();
//cmd.CommandType = CommandType.Text();
cmd.CommandText = "SELECT * from StudentDetails";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
dataGridView1.DataSource = dt;
conn.Close();
}
private void btnInsert_Click(object sender, EventArgs e)
{
conn.Open();//establish connection
SqlCommand cmd = conn.CreateCommand();
//cmd.CommandType = CommandType.Text();
cmd.CommandText = "INSERT INTO StudentDetails VALUES (#Name,#Subject)";
cmd.Parameters.Add("#Name", SqlDbType.NVarChar).Value = textBox1.Text; //add values in textbox1 and store in db
cmd.Parameters.Add("#Subject", SqlDbType.NVarChar).Value = textBox2.Text; //add values in textbox2 and store in db
cmd.ExecuteNonQuery();
conn.Close();
display_data();
MessageBox.Show("Record added");
}
private void btnDisplay_Click(object sender, EventArgs e)
{
display_data();
}
private void btnDelete_Click(object sender, EventArgs e)
{
conn.Open();//establish connection
SqlCommand cmd = conn.CreateCommand();
//cmd.CommandType = CommandType.Text();
cmd.CommandText = "DELETE FROM StudentDetails WHERE Name= #Name";
cmd.Parameters.Add("#Name", SqlDbType.NVarChar).Value = textBox1.Text; //add values in textbox1 and store in db
cmd.ExecuteNonQuery();
conn.Close();
display_data();
MessageBox.Show("Record deleted");
}
private void btnUpdate_Click(object sender, EventArgs e)
{
//conn.Open();//establish connection
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "UPDATE StudentDetails SET Name = #Name WHERE Subject = #Subject";
cmd.Parameters.AddWithValue("#Name", textBox1.Text);
cmd.Parameters.AddWithValue("#Subject", textBox2.Text);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
display_data();
MessageBox.Show("Record updated!");
}
private void buttonSearch_Click(object sender, EventArgs e)
{
conn.Open();//establish connection
SqlCommand cmd = conn.CreateCommand();
//cmd.CommandType = CommandType.Text();
cmd.CommandText = "DELETE FROM StudentDetails WHERE Name= #Name";
cmd.Parameters.Add("#Name", SqlDbType.NVarChar).Value = textBox1.Text; //add values in textbox1 and store in db
cmd.ExecuteNonQuery();
conn.Close();
display_data();
MessageBox.Show("Search completed!");
}
}
}
i have made a credit request page wherein users can request a value/amount. I have implemented that it should be activated first via email activation before putting the data to the admin page for viewing and approval.
i have made an "Activated" field where it is null until the user has clicked the link on his/her email address and it becomes "1" when user clicks it.
here is the code:
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
string constr = "Data Source = 'PAULO'; Initial Catalog=ShoppingCartDB;Integrated Security =True";
string activationCode = !string.IsNullOrEmpty(Request.QueryString["ActivationCode"]) ? Request.QueryString["ActivationCode"] : Guid.Empty.ToString();
using (SqlConnection con = new SqlConnection(constr))
{
SqlCommand Activate = new SqlCommand("SELECT UserId FROM CRActivation WHERE ActivationCode = #ActivationCode");
Activate.Parameters.AddWithValue("#ActivationCode", activationCode);
Activate.Connection = con;
con.Open();
string storedUserId = Activate.ExecuteScalar().ToString();
con.Close();
using (SqlCommand cmd = new SqlCommand("DELETE FROM CRActivation WHERE ActivationCode = #ActivationCode"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#ActivationCode", activationCode);
cmd.Connection = con;
con.Open();
int rowsAffected = cmd.ExecuteNonQuery();
con.Close();
if (rowsAffected == 1)
{
SqlCommand userCmd = new SqlCommand("UPDATE CreditRequests SET Activated = 1 WHERE ID = " + storedUserId);
userCmd.Connection = con;
con.Open();
userCmd.ExecuteNonQuery();
con.Close();
ltMessage.Text = "Credit Request Submitted.";
}
else
{
ltMessage.Text = "Invalid Activation code.";
}
}
}
}
}
what i want to happen is to carry over the "Activated" field and make an if statement that if it is 1, it will be shown in my gridview.
here is the gridview code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["IslandGasAdminFM"] != null)
{
bindgrid();
Label1.Text = "- Finance Manager";
}
else
{
Response.Write("<script>alert('Finance Manager credentials needed'); window.location.href='LogIn.aspx';</script>");
}
}
something like this:
if(Activated==1)
{
bindgrid();
}
any help or tricks will be of great help.
I have a gridview does not update on pageload. If you insert a value into the table, the page posts back and the gridview remains the same. All tho the record is inserted into the database. I'm fairly new to ADO.NET, any suggestions would be much appreciated.
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.Data;
using System.Configuration;
public partial class Equip_DB : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataBind();
}
string cs = ConfigurationManager.ConnectionStrings["NIC"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand showAll = new SqlCommand("SELECT * FROM Equiptment", con);
SqlDataReader reads = showAll.ExecuteReader();
GridView1.DataSource = reads;
GridView1.DataBind();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
string cs = ConfigurationManager.ConnectionStrings["NIC"].ConnectionString;
SqlConnection con = new SqlConnection(cs);
//INSERT INTO Equiptment VALUES ('2', 'Hammers', '24')
string query = "INSERT INTO Equiptment VALUES ('"+
equipAmount.Text +"', '"+
equipType.Text + "', '" +
DropDownList1.SelectedValue +"')";
AddContract.Visible = true;
SqlCommand cmd = new SqlCommand(query, con);
try
{
con.Open();
cmd.ExecuteNonQuery();
}
catch {
con.Close();
}
}
}
You are not binding gridview with updated content.
protected void Button1_Click(object sender, EventArgs e)
{
string cs = ConfigurationManager.ConnectionStrings["NIC"].ConnectionString;
SqlConnection con = new SqlConnection(cs);
//INSERT INTO Equiptment VALUES ('2', 'Hammers', '24')
string query = "INSERT INTO Equiptment VALUES ('"+
equipAmount.Text +"', '"+
equipType.Text + "', '" +
DropDownList1.SelectedValue +"')";
AddContract.Visible = true;
SqlCommand cmd = new SqlCommand(query, con);
try
{
con.Open();
cmd.ExecuteNonQuery();
con.Close();
//GRID LOAD CODE GOES HERE
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand showAll = new SqlCommand("SELECT * FROM Equiptment", con);
SqlDataReader reads = showAll.ExecuteReader();
GridView1.DataSource = reads;
GridView1.DataBind();
}
///////////////////////
}
catch {
con.Close();
}
}
}
On Registration page I have the error
"C# .net ExecuteNonQuery: CommandText property has not been initialized"
But If I give comments to "cmd.ExecuteNonQuery" on Registration page the this error goes to login page. I am unable to register and login on this.
Login Page:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Security;
using System.Web.Security;
public partial class Login : System.Web.UI.Page
{
//SqlConnection con = new SqlConnection("Data Source=LENOVO;Initial Catalog=Onl9Shopping;Persist Security Info=True;User ID=sa;Password=123");
SqlConnection con = new SqlConnection("Data Source=localhost;Initial Catalog=Onl9Shopping;Trusted_Connection=Yes;;Pooling=False");
protected void Page_Load(object sender, EventArgs e)
{
}
protected void ImageButton4_Click(object sender, ImageClickEventArgs e)
{
SqlCommand cmd = new SqlCommand();
cmd.CommandText="checksecurity ";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
con.Open();
cmd.Parameters.AddWithValue("#username", Txtusername.Text);
cmd.Parameters.AddWithValue("#password", Txtpassword.Text);
SqlParameter p1 = new SqlParameter("#ret", SqlDbType.Int);
p1.Direction = ParameterDirection.ReturnValue;
cmd.Parameters.Add(p1);
SqlParameter p2 = new SqlParameter("#status", SqlDbType.VarChar, 50);
p2.Direction = ParameterDirection.Output;
cmd.Parameters.Add(p2);
SqlParameter p3 = new SqlParameter("#name", SqlDbType.VarChar, 50);
p3.Direction = ParameterDirection.Output;
cmd.Parameters.Add(p3);
cmd.ExecuteNonQuery();
int r = Convert.ToInt16(cmd.Parameters["#ret"].Value);
string status = cmd.Parameters["#status"].Value.ToString();
string loggedname = cmd.Parameters["#name"].Value.ToString();
if (r == -1)
{
Label1.Text = "Wrong Username";
}
else if (r == -2)
{
Label1.Text = "wrong Password";
}
else
{
Session["name"] = loggedname;
FormsAuthenticationTicket tk = new FormsAuthenticationTicket(1, Txtusername.Text, DateTime.Now, DateTime.Now.AddHours(2), false, status);
string s = FormsAuthentication.Encrypt(tk);
HttpCookie ck = new HttpCookie(FormsAuthentication.FormsCookieName,s);
Response.Cookies.Add(ck);
Response.Redirect("Welcome.aspx");
}
Label1.Visible = true;
}
}
Registration Page:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class Registartion : System.Web.UI.Page
{
SqlConnection con = new SqlConnection("Data Source=localhost;Initial Catalog=Onl9Shopping;Trusted_Connection=Yes");
protected void Page_Load(object sender, EventArgs e)
{
}
private void getregno()
{
string query = "select max (registrationno) from register";
SqlDataAdapter adp = new SqlDataAdapter(query, con);
DataSet ds = new DataSet();
adp.Fill(ds);
Txtreg.Text = (Convert.ToInt16(ds.Tables[0].Rows[0][0]) + Convert.ToInt16(1)).ToString();
}
protected void btncheck_Click(object sender, EventArgs e)
{
string query = "select username from register";
SqlDataAdapter adp = new SqlDataAdapter(query, con);
DataSet ds = new DataSet();
adp.Fill(ds);
int b = 0;
int c = 0;
int a = 0;
a = ds.Tables[0].Rows.Count;
while (a > b)
{
if (ds.Tables[0].Rows[b][0].ToString().Equals(TxtUserName.Text))
{
c = 1;
}
b++;
}
if (c == 1)
{
Label1.Text = "Name already exist !!..";
}
else
{
Label1.Text = "Name available";
}
Label1.Visible=true;
}
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
string query = "select username from register";
SqlDataAdapter adp = new SqlDataAdapter(query, con);
DataSet ds = new DataSet();
adp.Fill(ds);
int b = 0;
int c = 0;
int a = 0;
a = ds.Tables[0].Rows.Count;
while (a > b)
{
if (ds.Tables[0].Rows[b][0].ToString().Equals(TxtUserName.Text))
{
c = 1;
}
b++;
}
if (c == 1)
{
Label1.Text = "Name already exist !!..";
}
else
{
SqlCommand cmd = new SqlCommand();
string query1 = "Insert into register(Name,FatherName,Gender,Address,Country,State,City,Pin,Phn,Email,Username,Password,SecurityQuestion,Hint)values(#Name,#Fathername,#Gender,#Address,#Country,#State,#City,#Pin,#Phn,#Email,#Username,#Password,#SecurityQuestion,#Hint)";
cmd.CommandText = query1;
cmd.Connection = con;
con.Open();
cmd.Parameters.AddWithValue("#Name", Txtname.Text);
cmd.Parameters.AddWithValue("#FatherName", Txtfname.Text);
cmd.Parameters.AddWithValue("#Gender", DropDownList1.Text);
cmd.Parameters.AddWithValue("#Address", Txtaddress.Text);
cmd.Parameters.AddWithValue("#Country", Txtcountry.Text);
cmd.Parameters.AddWithValue("#State", Txtstate.Text);
cmd.Parameters.AddWithValue("#City", Txtcity.Text);
cmd.Parameters.AddWithValue("#Pin", Txtpin.Text);
cmd.Parameters.AddWithValue("#Phn", Txtphn.Text);
cmd.Parameters.AddWithValue("#Email", Txtemail.Text);
cmd.Parameters.AddWithValue("#Username", TxtUserName.Text);
cmd.Parameters.AddWithValue("#Password", Txtpassword.Text);
cmd.Parameters.AddWithValue("#SecurityQuestion", DropDownList2.Text);
cmd.Parameters.AddWithValue("#Hint", Txthint.Text);
cmd.ExecuteNonQuery();
cmd.Dispose();
con.Close();
Txtname.Text = string.Empty;
Txtfname.Text = string.Empty;
Txtaddress.Text = string.Empty;
Txtcountry.Text = string.Empty;
Txtstate.Text = string.Empty;
Txtcity.Text = string.Empty;
Txtpin.Text = string.Empty;
Txtphn.Text = string.Empty;
Txtemail.Text = string.Empty;
TxtUserName.Text = string.Empty;
Txtpassword.Text = string.Empty;
Txtaddress.Text = string.Empty;
Txthint.Text = string.Empty;
Label2.Text = "Data sumitted ";
Label2.Visible = true;
}
}
}
There no commandtype for the click event for ImageButton1:
SqlCommand cmd = new SqlCommand();
string query1 = "Insert intoregister(Name,FatherName,Gender,Address,Country,State,City,Pin,Phn,Email,Username,Password,SecurityQuestion,Hint)values(#Name,#Fathername,#Gender,#Address,#Country,#State,#City,#Pin,#Phn,#Email,#Username,#Password,#SecurityQuestion,#Hint)";
cmd.CommandText = query1;
cmd.CommandType=CommandType.Text;
cmd.Connection = con;
con.Open();
Had the same issue today. You get this exception when the user you are using doesn't have the permissions to use the database. For testing it, you can login with the user using MS SQL Management Studio, and try to execute the query.
Check which groups the user is assigned to, make it a db_owner f.e., and check that it does not belong to db_denydatareader or db_denydatawriter
I have a table in my sql database called "usertype". My website has a registration form where the user will choose which type of user s/he is. So, what I want is that, when the user type of the person who logs in is User add, edit and delete buttons would be disable in the List of Faculty page of the website.
Click the link to see how my usertype table looks like:
http://i44.tinypic.com/2j34cau.jpg
And this is my code for Register.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class Register : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(Helper.GetConnection());
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetUserType();
}
}
void GetUserType()
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT ID, userType FROM type";
SqlDataReader dr = cmd.ExecuteReader();
ddlType.DataSource = dr;
ddlType.DataTextField = "userType";
ddlType.DataValueField = "ID";
ddlType.DataBind();
con.Close();
}
bool IsExisting(string email)
{
bool existing = true; //initial Value
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT userEmail FROM users WHERE userEmail = #userEmail";
cmd.Parameters.Add("userEmail", SqlDbType.VarChar).Value = email;
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows) // record (email Address) is existing
existing = true;
else //record is not existing
existing = false;
con.Close();
return existing;
}
protected void btnRegister_Click(object sender, EventArgs e)
{
if (!IsExisting(txtEmail.Text)) //if email not existing
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "INSERT INTO users VALUES (#TypeID, #userFN, #userLN, #userEmail, #userPassword, #userAddress, #userContact, #userCourse, #userSection, #userSchool)";
cmd.Parameters.Add("#TypeID", SqlDbType.Int).Value = ddlType.SelectedValue;
cmd.Parameters.Add("#userFN", SqlDbType.VarChar).Value = txtFN.Text;
cmd.Parameters.Add("#userLN", SqlDbType.VarChar).Value = txtLN.Text;
cmd.Parameters.Add("#userEmail", SqlDbType.VarChar).Value = txtEmail.Text;
cmd.Parameters.Add("#userPassword", SqlDbType.VarChar).Value = Helper.CreateSHAHash(txtPassword.Text);
cmd.Parameters.Add("#userAddress", SqlDbType.VarChar).Value = "";
cmd.Parameters.Add("#userContact", SqlDbType.VarChar).Value = "";
cmd.Parameters.Add("#userCourse", SqlDbType.VarChar).Value = "";
cmd.Parameters.Add("#userSection", SqlDbType.VarChar).Value = "";
cmd.Parameters.Add("#userSchool", SqlDbType.VarChar).Value = "";
cmd.ExecuteNonQuery();
con.Close();
string message = "Hello, " + txtFN.Text + " " + txtLN.Text + "! <br />"
+ "<br />You have successfully registered in our website. <br />" + "<br /> Click <a href = 'http://localhost:7773/PROJECT%20%5BWB-DEV1%5D/Login.aspx'>" + "here</a> to login <br /> <br />" + "Regards, <br /> " + "The Administrator";
Helper.SendEmail(txtEmail.Text, "Registered Successfully", message);
Response.Redirect("Login.aspx");
}
else //error existing
{
error.Visible = true;
}
}
}
This is the Faculty.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class Faculty : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(Helper.GetConnection());
protected void Page_Load(object sender, EventArgs e)
{
GetProfessor();
}
void GetProfessor()
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT ProfNo, SchoolID, LastName, FirstName, MI, " +
"Address, ContactNo, EmailAddress FROM Professor";
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "Professor");
gvProfessor.DataSource = ds;
gvProfessor.DataBind();
con.Close();
}
protected void gvProfessor_SelectedIndexChanged(object sender, EventArgs e)
{
btnEdit.Visible = true;
btnDelete.Visible = true;
btnAdd.Visible = true;
}
protected void btnDelete_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "DELETE FROM Professor WHERE ProfNo=#ProfNo";
cmd.Parameters.Add("#ProfNo", SqlDbType.Int).Value =
gvProfessor.SelectedRow.Cells[0].Text;
cmd.ExecuteNonQuery();
con.Close();
GetProfessor();
}
protected void btnEdit_Click(object sender, EventArgs e)
{
Session["ID"] = gvProfessor.SelectedRow.Cells[0].Text;
Response.Redirect("EditFaculty.aspx");
}
protected void btnAdd_Click(object sender, EventArgs e)
{
Response.Redirect("AddFaculty.aspx");
}
}
The btnAdd, btnEdit, btnDelete should be disable when its a User, and should be enabled when its an Admin.
I'm new to this and I hope you can help me. Thanks!
Since you didn't provide any code, all I can give you is pseudo-code:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
// If the user type doesn't equal user, they're enabled
btnAdd.Enabled = user.Type != "User";
btnEdit.Enabled = user.Type != "User";
btnDelete.Enabled = user.Type != "User";
}
}
If your user types are stored in the database as IDs, the best way to handle this is to create an enum whose values match the IDs in your database. The enum would look like this.
public enum UserType
{
Unknown = 0,
Admin = 1,
User = 2
}
Then, your code would look similar to this.
protected void Page_Load(object sender, EventArgs e)
{
SetButtonsEnabledDisabled(IsAdmin(userType));
}
private bool IsAdmin(int userTypeId)
{
return userTypeId == (int)UserType.Admin;
}
private void SetButtonsEnabledDisabled(bool isEnabled)
{
ButtonAdd.Enabled = isEnabled;
ButtonEdit.Enabled = isEnabled;
ButtonDelete.Enabled = isEnabled;
}
It's a good idea to store your IDs in an enum, if for no other reason than to increase the readability of your code. In Faculty.aspx.cs, you need to do a check on your currently logged in user. Whether you're passing some value through a query string, or doing an extra database call, I'm not going to architect it for you. But once you have that context, you can apply that to enable or disable your buttons.
Another thing to note is it's always a BAD idea to put data layer code in your code behind. Have a look at this SO answer for reasons why. https://stackoverflow.com/a/5318242/1717855