Database Updating - sql-server

I have a web app, where when a page loads, the address details are extracted from the database and displayed in the corresponding text-fields. However when I try to update and save the data, the data doesn't get updated.
However the same works fine when the extraction of data happens through the click of a button.
here's the code :
public partial class Address : System.Web.UI.Page
{
string global;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
global = Session["ID"].ToString();
System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection("Server = INLD50045747A\\SQLEXPRESS; Database = MyDatabase;User ID = sa; Password = Welcome1; Trusted_Connection = False;");
//SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS; AttachDbFilename=|DataDirectory|\\MyDatabase.mdf;Integrated Security=True;User Instance=True");
con.Open();
SqlCommand cmd = new SqlCommand("SELECT PermanentAdd,PermanentAdd2, HomePlace, HomeState, HomePin FROM EMPLOYEE_FULLADDRESS_TABLE WHERE EmployeeID = '" + global + "'", con);
SqlDataReader x = cmd.ExecuteReader();
while (x.Read())
{
TextBox1.Text = (string)x["PermanentAdd"];
TextBox1.Enabled = false;
TextBox5.Text = (string)x["PermanentAdd2"];
TextBox5.Enabled = false;
TextBox2.Text = (string)x["HomePlace"];
TextBox2.Enabled = false;
TextBox3.Text = (string)x["HomeState"];
TextBox3.Enabled = false;
State.Items.FindByText(State.SelectedItem.Text).Selected = false;
State.Items.FindByText(TextBox3.Text).Selected = true;
State.Enabled = false;
TextBox4.Text = (string)x["HomePin"];
TextBox4.Enabled = false;
}
x.Close();
con.Close();
}
}
protected void UpdateButton_Click(object sender, EventArgs e)
{
try
{
System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection("Server = INLD50045747A\\SQLEXPRESS; Database = MyDatabase;User ID = sa; Password = Welcome1; Trusted_Connection = False;");
//System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection("Data Source=.\\SQLEXPRESS; AttachDbFilename=|DataDirectory|\\MyDatabase.mdf;Integrated Security=True;User Instance=True");
con.Open();
// global = Session["ID"].ToString();
//string insert = "UPDATE EMPLOYEE_FULLADDRESS_TABLE SET PermanentAdd = #PermanentAdd, PermanentAdd2 = #PermanentAdd2, HomePlace = #HomePlace, HomeState= #HomeState, HomePin= #HomePin where EmployeeID = '" + global + "'";
SqlCommand cmd1 = new SqlCommand("UPDATE EMPLOYEE_FULLADDRESS_TABLE SET PermanentAdd = #PermanentAdd, PermanentAdd2 = #PermanentAdd2, HomePlace = #HomePlace, HomeState= #HomeState, HomePin= #HomePin where EmployeeID = '" + global + "'", con);
cmd1.Parameters.AddWithValue("#PermanentAdd", TextBox1.Text);
cmd1.Parameters.AddWithValue("#PermanentAdd2", TextBox5.Text);
cmd1.Parameters.AddWithValue("#HomePlace", TextBox2.Text);
if (State.SelectedItem.Text == "--Select--")
{
State.SelectedItem.Text = TextBox3.Text;
}
cmd1.Parameters.AddWithValue("#HomeState", State.SelectedItem.Text);
cmd1.Parameters.AddWithValue("#HomePin", TextBox4.Text);
cmd1.ExecuteNonQuery();
con.Close();
lblmsg.Text = "DATA Updated Successfully";
lblmsg.ForeColor = System.Drawing.Color.Green;
}
catch (Exception exp)
{
lblmsg.Text = exp.Message;
lblmsg.ForeColor = System.Drawing.Color.Red;
}
}
// static int count = 0;
protected void EditButton_Click(object sender, EventArgs e)
{
TextBox1.Enabled = true;
TextBox2.Enabled = true;
//TextBox3.Enabled = true;
TextBox4.Enabled = true;
TextBox5.Enabled = true;
State.Enabled = true;
}
please help.

I think you have commented out your global / employeeid assignment?
// global = Session["ID"].ToString();
You should also change this to a parameter in your SQL.

Related

Wrong Format of the initialization string in ADO.NET

I just have a simply method show below:
private void Button_Click_1(object sender, RoutedEventArgs e)
{
string sqlcmdString = string.Format("UPDATE Bills SET Name = '#name', Time = '#time', Product = '#pro', Price = #money WHERE Name = '#value';");
using (SqlConnection con = new SqlConnection(sqlcmdString))
using (SqlCommand cmd = new SqlCommand("dbo.Bills", con))
{
// tell ADO.NET it's a stored procedure (not inline SQL statements)
cmd.CommandType = CommandType.StoredProcedure;
// define parameters
cmd.Parameters.Add("#name", SqlDbType.NVarChar, 100).Value = tb_TenKH.Text;
cmd.Parameters.Add("#time", SqlDbType.DateTime).Value = cb_Thoigian.Text;
cmd.Parameters.Add("#pro", SqlDbType.NVarChar, 100).Value = tb_SanPham.Text;
cmd.Parameters.Add("#money", SqlDbType.Money).Value = tb_ThanhTien.Text;
cmd.Parameters.Add("#value", SqlDbType.NVarChar, 100).Value = cellvalue;
// open connection, execute stored procedure, close connection again
con.Open();
if (cmd.ExecuteNonQuery() > 0)
{
//dosomething
}
else
{
MessageBox.Show("Failed!!!");
}
con.Close();
}
}
This lines could not be run. When i debug it, it shows error:
System.ArgumentException: 'Format of the initialization string does
not conform to specification starting at index 0.'
I aware that something went wrong in my sqlcmdString maybe about syntax, but I couldn't determine it. Please give me a help.
I'm wrong in syntax: I should use like below:
string sqlcmdString = string.Format("UPDATE Bills SET Name = '#name', Time = '#time', Product = '#pro', Price = #money WHERE Name = '#value';");
using (SqlConnection con = new SqlConnection(connString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand(sqlcmdString, con))
{
cmd.CommandType = CommandType.Text;
// define parameters
cmd.Parameters.Add("#name", SqlDbType.NVarChar, 100).Value = tb_TenKH.Text;
cmd.Parameters.Add("#time", SqlDbType.DateTime).Value = cb_Thoigian.Text;
cmd.Parameters.Add("#pro", SqlDbType.NVarChar, 100).Value = tb_SanPham.Text;
cmd.Parameters.Add("#money", SqlDbType.Money).Value = tb_ThanhTien.Text;
cmd.Parameters.Add("#value", SqlDbType.NVarChar, 100).Value = cellvalue;
if (cmd.ExecuteNonQuery() > 0)
{
MessageBox.Show("Thành Công!!!");
if (passrow != null)
{
string[] result_back = { tb_TenKH.Text, cb_Thoigian.Text, tb_SanPham.Text, tb_ThanhTien.Text };
passrow(result_back);
{
this.Hide();
}
}
}
else
{
MessageBox.Show("Thất Bại!!!");
}
con.Close();
}
}

Login for users of different positions

I am sort of new to login feature for projects and am trying to do logins for my group, which consists of 3 users, namely Nurse, Patient and Pharmacist. I think I am about to complete the loin process but I have a problem with one of my methods, getPosition() in my LoginDAO.cs. So far, I have not done any login codes for patient and pharmacist as i will need my group mates' parts for it to work, but shown below is what I have done. Somehow, login(string nric, string pw) works, but not getPosition(string nric). This is the error that i get from my error log:
Exception: Must declare the scalar variable "#paraNRIC". Source: LoginDAO.getPosition
Thanks in advance :D
protected void btnLogin_Click(object sender, EventArgs e)
{
login login = new login();
login.nric = tbLoginID.Text;
login.pw = tbPassword.Text;
if (login.userLogin(login.nric, login.pw))
{
if (login.getPosition(login.nric) == "Nurse")
{
Response.Redirect("Nurse.aspx");
}
else if (login.getPosition(login.nric) == "Patient")
{
Response.Redirect("Patient.aspx");
}
else if (login.getPosition(login.nric) == "Pharmacist")
{
Response.Redirect("PharmacistDisplay.aspx");
}
}
else
{
lblErr.Text = "Invalid account.";
}
}
public bool login(string nric, string pw)
{
bool flag = false;
SqlCommand cmd = new SqlCommand();
StringBuilder sqlStr = new StringBuilder();
sqlStr.AppendLine("SELECT Password from Position");
sqlStr.AppendLine("Where NRIC = #paraNRIC");
try
{
SqlConnection myconn = new SqlConnection(DBConnect);
cmd = new SqlCommand(sqlStr.ToString(), myconn);
cmd.Parameters.AddWithValue("#paraNRIC", nric);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
if (dt == null)
{
flag = false;
}
else
{
string dbhashedpw = dt.Rows[0]["Password"].ToString();
flag = Helper.VerifyHash(pw, "SHA512", dbhashedpw);
}
}
catch (Exception exc)
{
logManager log = new logManager();
log.addLog("NurseDAO.login", sqlStr.ToString(), exc);
}
return flag;
}
public string getPosition(string nric)
{
string dbPosition = "";
int result = 0;
SqlCommand cmd = new SqlCommand();
StringBuilder sqlStr = new StringBuilder();
sqlStr.AppendLine("SELECT Position from Position ");
sqlStr.AppendLine("where NRIC = #paraNRIC");
cmd.Parameters.AddWithValue("#paraNRIC", nric);
try
{
SqlConnection myconn = new SqlConnection(DBConnect);
cmd = new SqlCommand(sqlStr.ToString(), myconn);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
myconn.Open();
result = cmd.ExecuteNonQuery();
dbPosition = dt.Rows[0]["Position"].ToString();
myconn.Close();
}
catch (Exception exc)
{
logManager log = new logManager();
log.addLog("LoginDAO.getPosition", sqlStr.ToString(), exc);
}
return dbPosition;
`}
Your error is here:
SqlCommand cmd = new SqlCommand();
// lines omitted
cmd.Parameters.AddWithValue("#paraNRIC", nric);
try
{
SqlConnection myconn = new SqlConnection(DBConnect);
cmd = new SqlCommand(sqlStr.ToString(), myconn);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
Note that you are instantiating cmd twice. The code adds the parameters to the first SqlCommand instance, but executes the second instance.
To resolve, ensure you declare the parameters on the instance of SqlCommand you invoke:
public string getPosition(string nric)
{
string dbPosition = "";
int result = 0;
// remove this line: SqlCommand cmd = new SqlCommand();
StringBuilder sqlStr = new StringBuilder();
sqlStr.AppendLine("SELECT Position from Position ");
sqlStr.AppendLine("where NRIC = #paraNRIC");
// move parameter declaration until after you declare cmd
try
{
SqlConnection myconn = new SqlConnection(DBConnect);
SqlCommand cmd = new SqlCommand(sqlStr.ToString(), myconn);
// add the parameters here:
cmd.Parameters.AddWithValue("#paraNRIC", nric);
// code continues
You could change this line
sqlStr.AppendLine("where NRIC = #paraNRIC");
To This
sqlStr.AppendLine("where NRIC = '" + nric + "'");
and avoid parameters altogether.

How to bind gridview from database?

using System.Data.SqlClient;
namespace EHR
{
public partial class imagery : Form
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\wittyse\Desktop\database_EHR\EHR.mdf;Integrated Security=True;Connect Timeout=30");
SqlCommand cmd;
DataTable dt2 = new DataTable();
public imagery()
{
InitializeComponent();
}
public void readdatagrid1()
{
//con.Open();
SqlDataAdapter dpeo = new SqlDataAdapter("Select Img_ID,PEOPLE_INFO.people_ID,PEOPLE_INFO.Name,Imgs,Result from PEOPLE_INFO,IMAGERY_DIAGNOSTIC,MG_NAM where IMAGERY_DIAGNOSTIC.Img_ID=MG_NAM.Mg_nm_ID and PEOPLE_INFO.people_ID=IMAGERY_DIAGNOSTIC.People_ID", con);
DataSet dpep = new DataSet();
dpeo.Fill(dpep, "IMAGERY_DIAGNOSTIC");
dataGridView1.DataSource = dpep.Tables["IMAGERY_DIAGNOSTIC"];
con.Close();
}
private void imagery_Load(object sender, EventArgs e)
{
//dataGridView1.DataSource = null;
readdatagrid1();
SqlDataAdapter dz = new SqlDataAdapter("Select * from MG_NAM order by Mg_nm_ID", con);
DataSet dzo = new DataSet();
dz.Fill(dzo, "MG_NAM");
comboBox1.DataSource = dzo.Tables["MG_NAM"];
comboBox1.DisplayMember = "Imgs";
SqlDataAdapter da = new SqlDataAdapter("Select Name from PEOPLE_INFO order by people_ID", con);
DataSet ds = new DataSet();
da.Fill(ds, "PEOPLE_INFO");
comboBox2.DataSource = ds.Tables["PEOPLE_INFO"];
comboBox2.DisplayMember = "Name";
con.Close();
}
public int comck=0;
public int idx;
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
con.Close();
string Query = "Select Mg_nm_ID,Imgs from MG_NAM where Imgs='" + comboBox1.Text + "'";
con.Open();
SqlCommand createCommand = new SqlCommand(Query, con);
SqlDataReader dr = createCommand.ExecuteReader();
while (dr.Read())
{
textBox4.Text = dr.GetInt32(0).ToString();
//textBox1.Text = dr.GetInt32(1).ToString();
idx = Convert.ToInt32(textBox4.Text);
}
dr.Close();
comck = 1;
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(id+" index is "+comboBox1.SelectedIndex,"info");
}
public int comck2 = 0;
public int id;
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
con.Close();
string Query = "Select people_ID,Name from PEOPLE_INFO where Name='" + comboBox2.Text + "'";
con.Open();
SqlCommand createCommand = new SqlCommand(Query, con);
SqlDataReader dr = createCommand.ExecuteReader();
while (dr.Read())
{
textBox2.Text = dr.GetInt32(0).ToString();
//textBox1.Text = dr.GetInt32(1).ToString();
id = Convert.ToInt32(textBox2.Text);
}
dr.Close();
comck2 = 1;
}
private void button2_Click(object sender, EventArgs e)
{
if (comck == 0 & comck2 == 0 || textBox3.Text == "")
{
MessageBox.Show("you must select or inter data","info");
}
else
{
con.Close();
cmd = new SqlCommand("Insert into IMAGERY_DIAGNOSTIC(People_ID,Mg_Nam,Result) values ('" + id + "','" + idx + "','" + textBox3.Text + "')", con);
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Added new IMAGERY DIAGNOSTIC ", "ADD", MessageBoxButtons.OK, MessageBoxIcon.Information);
dataGridView1.DataSource = null;
con.Close();
readdatagrid1();
}
// MessageBox.Show("info save"+comboBox1.SelectedIndex," info ");
}
private void button3_Click(object sender, EventArgs e)
{
if (selectgrid == 0)
{ MessageBox.Show("you must select record to delet it","Info",MessageBoxButtons.OK,MessageBoxIcon.Information); }
else
{
cmd = new SqlCommand("Delete From IMAGERY_DIAGNOSTIC Where Img_ID='" + bindex + "'", con);
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("You delete recored successfully", "delete", MessageBoxButtons.OK, MessageBoxIcon.Information);
dataGridView1.DataSource = null;
con.Close();
readdatagrid1();
}
}
public int bindex;
public int selectgrid = 0;
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0)
{
DataGridViewRow row = this.dataGridView1.Rows[e.RowIndex];
textBox1.Text = row.Cells["People_ID"].Value.ToString(); //roll type to update
comboBox2.Text = row.Cells["Name"].Value.ToString();
textBox3.Text = row.Cells["Result"].Value.ToString();
string dex = row.Cells["Img_ID"].Value.ToString();
bindex = Convert.ToInt32(dex); //Bld_ID in integer format | for Query
selectgrid = 1;
}
}
}
}
replace the following code dataGridView1.DataSource = dpep.Tables["IMAGERY_DIAGNOSTIC"];
with
dataGridView1.DataSource = new BindingSource { DataSource =dpep.Tables["IMAGERY_DIAGNOSTIC"] };

fill textbox on second combobox selection changed in cascading combobox in windows form using c#

I have 2 cascading combo-box in windows form application. I have textbox for price and unit. when I select first combobox, second combobox gets populated. I want textbox for price and unit to be filled only on second combobox selection.
My problem is when the form is loaded both textboxes are filled with values from table and not on combobox selection changed.
my code is:
private void Purchase_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'supplierDataSet.Supplier' table. You can move, or remove it, as needed.
this.supplierTableAdapter.Fill(this.supplierDataSet.Supplier);
fillName();
comboBoxName.SelectedIndex = -1;
}
private void fillName()
{
string str = "Select distinct Item_Name from Item";
using (SqlConnection con = new SqlConnection(#"Data Source=ashish-pc\;Initial Catalog=HMS;Integrated Security=True"))
{
using (SqlCommand cmd = new SqlCommand(str, con))
{
using (SqlDataAdapter adp = new SqlDataAdapter(cmd))
{
DataTable dtItem = new DataTable();
adp.Fill(dtItem);
comboBoxName.DataSource = dtItem;
comboBoxName.DisplayMember = "Item_Name";
comboBoxName.ValueMember = "Item_Name";
}
}
}
}
private void fillMake()
{
string str = "Select Item_Make from Item Where Item_Name=#Item_Name";
using (SqlConnection con = new SqlConnection(#"Data Source=ashish-pc\;Initial Catalog=HMS;Integrated Security=True"))
{
using (SqlCommand cmd = new SqlCommand(str, con))
{
cmd.Parameters.AddWithValue("#Item_Name", comboBoxName.Text);
using (SqlDataAdapter adp = new SqlDataAdapter(cmd))
{
DataTable dtItem = new DataTable();
adp.Fill(dtItem);
comboBoxMake.DataSource = dtItem;
comboBoxMake.ValueMember = "Item_Make";
comboBoxMake.DisplayMember = "Item_Make";
}
}
}
}
private void comboBoxName_SelectedIndexChanged_1(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(comboBoxName.Text))
{
comboBoxMake.Enabled = true;
fillMake();
comboBoxMake.SelectedIndex = -1;
}
}
private void comboBoxMake_SelectedIndexChanged_1(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(comboBoxMake.Text))
{
textBoxPrice.Enabled = true;
textBoxUoM.Enabled = true;
}
SqlConnection con = new SqlConnection(#"Data Source=ashish-pc\;Initial Catalog=HMS;Integrated Security=True");
SqlCommand cmd = new SqlCommand("Select * from Item Where Item_Make='" + comboBoxMake.Text + "' AND Item_Name='" + comboBoxName.Text + "'", con);
SqlDataReader reader;
try
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
reader = cmd.ExecuteReader();
while (reader.Read())
{
textBoxPrice.Text = Convert.ToString(reader["Price"]);
textBoxUoM.Text = Convert.ToString(reader["Unit"]);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
}
}
I am stuck here. please help.
Try changing SelectedIndex = -1 to SelectedItem = -1 in Purchase_Load and ComboBox1_SelectedIndexChanged.

Error in Win Form Login

private void Button1Click(object sender, EventArgs e)
{
var dt = new DataTable();
const string Connectionstring = "Data Source=GARETH-PC1;Initial Catalog=Genres;Integrated Security=True";
using (var con = new SqlConnection(Connectionstring))
{
con.Open();
var query = "Select Username From Login Where Username ='" + ComboBox1.SelectedText + "' Password ='" + textBox2.Text + "'";
using (var sda = new SqlDataAdapter(query, con))
{
sda.Fill(dt);
}
}
if (dt.Rows[0].ItemArray.GetValue(0).ToString() == "1")
{
Hide();
var ss = new Main();
ss.Show();
}
else
{
MessageBox.Show("Invalid Username or Password");
}
}
The if (dt.Rows[0].ItemArray.GetValue(0).ToString() == "1") - Returns an error saying there's nothing in the table... But there is ..any suggestions?
Maybe you can try like this:
dt.Rows[0]["ColumnName"].ToString()
This is working for me.
I would change your code in this way.
First, change to a parameterized query instead of a string concatenation (Sql Injection and parsing)
Second, use the count property to check if you have found a record or not
private void Button1Click(object sender, EventArgs e)
{
var dt = new DataTable();
const string Connectionstring = "Data Source=GARETH-PC1;Initial Catalog=Genres;Integrated Security=True";
var query = "Select Username From Login Where Username =#uname AND Password=#pwd";
using (var con = new SqlConnection(Connectionstring))
using (var cmd = new SqlCommand(query, con)
{
con.Open();
cmd.Parameters.AddWithValue("#uname", ComboBox1.SelectedText);
cmd.Parameters.AddWithValue("#pwd", textBox2.Text);
using (var sda = new SqlDataAdapter(cmd))
{
sda.Fill(dt);
}
}
if (dt.Rows.Count > 0)
{
Hide();
var ss = new Main();
ss.Show();
}
else
{
MessageBox.Show("Invalid Username or Password");
}
}
As a side note, it is a very bad idea to store passwords in plain text inside a database. You should consider to use an HASH and store it instead of the plain password.

Resources