I want to add textbox values to relevant columns in access database, the connection has been established but when i click the submit button the values are not added.
here is the code i tried, any help is appreciated
protected void Button1_Click(object sender, EventArgs e)
{
string EmailAddress = TextBox1.Text;
string UserName = TextBox2.Text;
string Password = TextBox3.Text;
try
{
OleDbConnection con = new OleDbConnection(#"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = C:\Users\Bheki Ndhlovu\source\WebSites\WebSite8\App_Data\UserDatabase.accdb; Persist Security Info = False;");
OleDbCommand cmd = new OleDbCommand();
cmd = new OleDbCommand("INSERT INTO User(EmailAddress, UserName, Password) VALUES(#EmailAddress, #UserName, #Password)");
con.Open();
if (con.State == ConnectionState.Open)
{
TextBox1.Text = "sssss";
cmd.Parameters.Add("#EmailAddress", OleDbType.VarChar).Value = TextBox1.Text;
cmd.Parameters.Add("#UserName", OleDbType.VarChar).Value = TextBox2.Text;
cmd.Parameters.Add("#Password", OleDbType.VarChar).Value = TextBox3.Text;
cmd.ExecuteNonQuery();
con.Close();
}
}
catch (Exception error)
{
//Show error message as error.Message
}
}
Try adding connection string with OleDbCommand.
cmd = new OleDbCommand("INSERT INTO User(EmailAddress, UserName, Password) VALUES(#EmailAddress, #UserName, #Password)",con);
Here is an example were all data operations reside in a class. If the add new record is successful the new primary key is returned. On failure you can query the exception that raised the problem for failure.
using System;
using System.Windows.Forms;
using System.Data.OleDb;
using System.IO;
namespace MS_AccessAddNewRecord_cs
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void addRecordButton_Click(object sender, EventArgs e)
{
var ops = new Operations();
var newId = 0;
if (ops.AddNewRow(companyTextBox.Text, contactNameTextBox.Text, contactTitleTextBox.Text, ref newId))
{
newIdentifierTextBox.Text = $"{newId}";
}
else
{
MessageBox.Show($"{ops.Exception.Message}");
}
}
}
/// <summary>
/// This class should be in a separate class file, I placed it here for easy of learning
/// </summary>
public class Operations
{
private OleDbConnectionStringBuilder Builder = new OleDbConnectionStringBuilder
{
Provider = "Microsoft.ACE.OLEDB.12.0",
DataSource = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Database1.accdb")
};
private Exception mExceptiom;
public Exception Exception
{
get
{
return mExceptiom;
}
}
/// <summary>
/// Add a new record, upon success return the new primary key for the record in pIdentifier parameter
/// </summary>
/// <param name="pName"></param>
/// <param name="pContactName"></param>
/// <param name="pContactTitle"></param>
/// <param name="pIdentfier"></param>
/// <returns></returns>
public bool AddNewRow(string pName, string pContactName, string pContactTitle, ref int pIdentfier)
{
bool Success = true;
try
{
using (OleDbConnection cn = new OleDbConnection { ConnectionString = Builder.ConnectionString })
{
using (OleDbCommand cmd = new OleDbCommand { Connection = cn })
{
cmd.CommandText = "INSERT INTO Customers (CompanyName,ContactName, ContactTitle) " +
"Values(#CompanyName,#ContactName, #ContactTitle)";
cmd.Parameters.AddWithValue("#CompanyName", pName);
cmd.Parameters.AddWithValue("#ContactName", pContactName);
cmd.Parameters.AddWithValue("#ContactTitle", pContactTitle);
cn.Open();
int Affected = cmd.ExecuteNonQuery();
if (Affected == 1)
{
cmd.CommandText = "Select ##Identity";
pIdentfier = Convert.ToInt32(cmd.ExecuteScalar());
}
}
}
}
catch (Exception ex)
{
Success = false;
mExceptiom = ex;
}
return Success;
}
}
}
Perhaps in the Page_Load method you do not have a if(!isPostback) and so the value of the TextBoxes are getting reset on a postback before the Button1_Click method is executed.
If EmptyWaterHole's answer is not the problem, is it erroring out on the connection?
Be sure 'VarChar' is the correct data type for each of the fields.
Also, be sure the values do not exceed the size (ie: if you set the field to only allow up to 25 characters and your value is over 25 characters, the value will not be added).
In addition, if you are not allowing nulls and one of the values exceeds the limit, the whole record will not be added.
Mr. Hungry. Try it like this.
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;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OleDbConnection conn;
conn = new OleDbConnection(#"Provider=Microsoft.Jet.OleDb.4.0;Data Source=C:\your_path_here\Northwind.mdb");
conn.Open();
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandText = #"INSERT INTO MyExcelTable([Fname], [Lname], [Address])VALUES('" + textBox1.Text + "', '" + textBox2.Text + "','" + textBox3.Text + "')";
cmd.ExecuteNonQuery();
conn.Close();
}
public OleDbConnection myCon { get; set; }
private void button2_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Ryan\Desktop\Coding\Microsoft Access\Northwind.mdb";
string fstName = textBox1.Text.Trim();
string lstName = textBox2.Text.Trim();
string adres = textBox3.Text.Trim();
OleDbCommand cmd = new OleDbCommand(#"INSERT INTO MyExcelTable (FName, LName, Address) VALUES (#FName, #LName, #Address)")
{
Connection = conn
};
conn.Open();
if (conn.State == ConnectionState.Open)
{
// you should always use parameterized queries to avoid SQL Injection
cmd.Parameters.Add("#FName", OleDbType.VarChar).Value = fstName;
cmd.Parameters.Add("#LName", OleDbType.VarChar).Value = lstName;
cmd.Parameters.Add("#Address", OleDbType.VarChar).Value = adres;
try
{
cmd.ExecuteNonQuery();
MessageBox.Show(#"Data Added");
conn.Close();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Source + "\n" + ex.Message);
conn.Close();
}
}
else
{
MessageBox.Show(#"Connection Failed");
}
}
}
}
try this it will work if you are using access as your database
try
{
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "INSERT INTO REPORT (patientName,tel,hostel,id no,department,diagnose,gender) values(#patientName,#tel,#hostel,#id no,#department,#diagnose,#gender)";
connection.Open();
command.Parameters.AddWithValue("#patientName", textBox1.Text);
command.Parameters.AddWithValue("#tel", textBox2.Text);
command.Parameters.AddWithValue("#hostel", textBox3.Text);
command.Parameters.AddWithValue("#id no", textBox4.Text);
command.Parameters.AddWithValue("#department", textBox5.Text);
command.Parameters.AddWithValue("#diagnose", richTextBox1.Text);
command.Parameters.AddWithValue("#gender", textBox6.Text);
command.ExecuteNonQuery();
connection.Close();
MessageBox.Show("Patient record Have been save successfully....");
}
catch (Exception ex)
{
MessageBox.Show("error" + ex);
}
Related
I wrote a code for my pleasure.
i have access data file "mdb" and i show him on gridview from gridview i select row and shown on text box.
i edit the textbox and try to press on Save button and show me error msg.
what i do wrong?
save button didnt save and show me error msg.
add pictures and my code:
Error msg
gridview+textbox
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 Center image description hereDHW
{
public partial class Form2 : Form
{
private OleDbConnection connection = new OleDbConnection();
public Form2()
{
InitializeComponent();
connection.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source = C:\Users\RBA\Desktop\123\users1.mdb;
Persist Security Info=False;";
}
private void button9_Click(object sender, EventArgs e)
{
this.Close();
Form1 f1 = new Form1();
f1.Show();
}
private void btn_save_Click(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "insert into GRL1 (NoBoard,Site,Group,Kind,Unit) values ('" + txt_noboard.Text + "','" + txt_site.Text + "','" + txt_group.Text + "','" + txt_kind.Text + "','" + txt_unit.Text + "',)";
command.ExecuteNonQuery();
MessageBox.Show("Data Saved");
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
private void Form2_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'users1DataSet.GRL1' table. You can move, or remove it, as needed.
this.gRL1TableAdapter.Fill(this.users1DataSet.GRL1);
}
private void btn_loadGR_Click(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query = "select * from GRL1";
command.CommandText = query;
OleDbDataAdapter da = new OleDbDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
private void button3_Click(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query = "select * from GRS1";
command.CommandText = query;
OleDbDataAdapter da = new OleDbDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0)
{
DataGridViewRow row = this.dataGridView1.Rows[e.RowIndex];
txt_noboard.Text = row.Cells[0].Value.ToString();
txt_site.Text = row.Cells[1].Value.ToString();
txt_group.Text = row.Cells[2].Value.ToString();
txt_kind.Text = row.Cells[3].Value.ToString();
txt_unit.Text = row.Cells[4].Value.ToString();
txt_com.Text = row.Cells[5].Value.ToString();
}
}
}
}
You have a typo in your sql text. There is a comma before the close brace. But there is also an error caused by the usage of a reserved keyword in MS-Access (Group). You need to put square brackets around that name.
Finally, do not use string concatenation to build sql commands but always use parameters.
This avoid sql injection hacks and remove problem with parsing your inputs (for example if there is a single quote in your input text the whole query will fail again with a syntax error)
private void btn_save_Click(object sender, EventArgs e)
{
try
{
using(OleDbConnection connection = new OleDbConnection(....con string...))
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
// Notice how Group field is between square brackets.
// If you can I suggest to change the name of this field
string cmdText = #"insert into GRL1 (NoBoard,Site,[Group],Kind,Unit)
values (#nob, #sit, #grp, #knd, #uni)";
command.CommandText = cmdText;
// Is NoBoard an integer? If yes you should pass an integer not a string
command.Parameters.Add("#nob", OleDbType.Integer).Value = Convert.ToInt32(txt_noboard.Text);
command.Parameters.Add("#sit", OleDbType.VarWChar).Value = txt_site.Text;
command.Parameters.Add("#grp", OleDbType.VarWChar).Value = txt_group.Text;
command.Parameters.Add("#knd", OleDbType.VarWChar).Value = txt_kind.Text;
command.Parameters.Add("#uni", OleDbType.VarWChar).Value = txt_unit.Text;
command.ExecuteNonQuery();
MessageBox.Show("Data Saved");
}
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
The parameters collection is filled with the values required by your query text. Notice that I don't know exactly the datatype of your columns in the database. The parameter OleDbType should exactly match the types expected to avoid Type Mismatch exceptions
Last tip. Connections should be created, opened and closed when needed. Do not keep a global connection object. You don't get much gain in performance because ADO.NET employs a technique called Connection Pooling
I am new on c# and i am facing problem. i made two buttons, one for case another for credit card. when i click on button, my data is not inserting into ms access file.why is it not showing any error and how can i fix it ?
private void CashButton_Click(object sender, EventArgs e)
{
SaveOrder((int)PaymentTypes.Cash);
}
private void CreditCardButton_Click(object sender, EventArgs e)
{
SaveOrder((int)PaymentTypes.CreditCard);
}
private void SaveOrder(int paymentType)
{
try
{
string connstring = ConfigurationManager.ConnectionStrings["dbx"].ConnectionString;
using (OleDbConnection conn = new OleDbConnection(connstring))
{
conn.Open();
using (OleDbCommand cmd = new OleDbCommand("INSERT INTO [Orders](OrderNummber,TransactionDate,ClientName,TotalAmount,PaymentType) VALUES(#OrderNummber,#TransactionDate,#ClientName,#TotalAmount,#PaymentType)",conn))
{
cmd.Parameters.AddWithValue("#OrderNummber",OrderNumberTextBox.Text);
cmd.Parameters.AddWithValue("#TransactionDate",TransactionDateDateTimePicker.Value.Date);
cmd.Parameters.AddWithValue("#ClientName",ClientNameTextBox.Text);
cmd.Parameters.AddWithValue("#TotalAmount",Convert.ToDecimal(TotalAmountTextBox.Text));
cmd.Parameters.AddWithValue("#PaymentType", paymentType);
cmd.ExecuteNonQuery();
}
foreach (DataGridViewRow row in CartDataGridView.Rows)
{
using (OleDbCommand cmd = new OleDbCommand("INSERT INTO [OrdersItems](OrderNumber,Quantity,UnitPrice,TotalPrice) VALUES(#OrderNumber,#Quantity,#UnitPrice,#TotalPrice)", conn))
{
cmd.Parameters.AddWithValue("#OrderNumber", OrderNumberTextBox.Text);
cmd.Parameters.AddWithValue("#Quantity", Convert.ToInt16(row.Cells["Quantity"].Value));
cmd.Parameters.AddWithValue("#UnitPrice",Convert.ToDecimal(row.Cells["UnitPrice"].Value));
cmd.Parameters.AddWithValue("#TotalPrice", Convert.ToDecimal(row.Cells["TotalPrice"].Value));
cmd.ExecuteNonQuery();
}
}
MessageBox.Show("Order is processed successfully!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
}
}
Do it like this.
using System;
using System.Data;
using System.Windows.Forms;
using System.Data.OleDb;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Ryan\Desktop\Coding\Microsoft Access\Northwind.mdb";
string fstName = textBox1.Text.Trim();
string lstName = textBox2.Text.Trim();
string adres = textBox3.Text.Trim();
OleDbCommand cmd = new OleDbCommand(#"INSERT INTO MyExcelTable (FName, LName, Address) VALUES (#FName, #LName, #Address)")
{
Connection = conn
};
conn.Open();
if (conn.State == ConnectionState.Open)
{
// you should always use parameterized queries to avoid SQL Injection
cmd.Parameters.Add("#FName", OleDbType.VarChar).Value = fstName;
cmd.Parameters.Add("#LName", OleDbType.VarChar).Value = lstName;
cmd.Parameters.Add("#Address", OleDbType.VarChar).Value = adres;
try
{
cmd.ExecuteNonQuery();
MessageBox.Show(#"Data Added");
conn.Close();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Source + "\n" + ex.Message);
conn.Close();
}
}
else
{
MessageBox.Show(#"Connection Failed");
}
}
}
}
This will definitely work. Just change the connection string and the variables to suit your needs.
For a program I'm making, I want to add the countrycode, the zipcode of the city and the name of the city in a table. If this information is already in the table, nothing needs to happen.
However, new records won't insert in my table.
For example: with only 'BE, '3580', 'Beringen' in my table. I start my program.
First I insert the values that are already in my table and nothing happends.
Second I try to add a new value (for example: ('BE' '3500', 'Hasselt')). I get the messagebox with: "Data added succesfully!".
After that, I try to add the same value as before ('BE' '3500', 'Hasselt'). My program does nothing.
But when I open Access, to take a look in the table. No new data was added.
What did I do wrong?
connection.ConnectionString = #"Provider = Microsoft.Jet.OLEDB.4.0; Data Source = DeJongDatabase.mdb; Persist Security Info = True";
This is the rest of my code
static class Zipcodes
{
public static void checkAndSavePostCode(String country, String zipcode, string city)
{
Globals.connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = Globals.connection;
command.CommandText = string.Format("SELECT * FROM Zipcodes WHERE CountryCode = #countryCode AND City= #city AND Zipcode= #zipcode");
command.Parameters.AddWithValue("#countyCode", country);
command.Parameters.AddWithValue("#city", city);
command.Parameters.AddWithValue("#zipcode", zipcode);
OleDbDataReader postcodeReader = command.ExecuteReader();
bool exists = false;
while (postcodeReader.Read())
{
exists = true;
}
postcodeReader.Close();
command.Dispose();
Globals.connection.Close();
OleDbCommand writeCommand = new OleDbCommand();
writeCommand.Connection = Globals.connection;
try
{
Globals.connection.Open();
if (!exists)
{
if (Globals.connection.State == System.Data.ConnectionState.Open)
{
/*writeCommand.CommandText = "INSERT INTO Zipcodes(CountryCode, ZipCode, City) VALUES(#countryCode, #zipcode, #city)";
writeCommand.Parameters.AddWithValue("#countyCode", country);
writeCommand.Parameters.AddWithValue("#city", city);
writeCommand.Parameters.AddWithValue("#zipcode", zipcode); */
writeCommand.CommandText = "INSERT INTO Zipcodes(CountryCode, ZipCode, City) VALUES(?, ?, ?)";
writeCommand.Parameters.Add(new OleDbParameter("#countryCode", OleDbType.VarChar)).Value = country;
writeCommand.Parameters.Add(new OleDbParameter("#zipcode", OleDbType.VarChar)).Value = zipcode;
writeCommand.Parameters.Add(new OleDbParameter("#city", OleDbType.VarChar)).Value = city;
if (writeCommand.ExecuteNonQuery() > 0)
{
MessageBox.Show("Data saved successfuly...!");
}
}
else
{
MessageBox.Show("FAILED");
}
}
}
catch(OleDbException ex)
{
MessageBox.Show(ex.Source);
MessageBox.Show(ex.ToString());
}
finally
{
Globals.connection.Close();
}
This works fine for me.
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;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OleDbConnection conn;
conn = new OleDbConnection(#"Provider=Microsoft.Jet.OleDb.4.0;Data Source=C:\Users\your_path_here\Northwind.mdb");
conn.Open();
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandText = #"INSERT INTO MyExcelTable([Fname], [Lname], [Address])VALUES('" + textBox1.Text + "', '" + textBox2.Text + "','" + textBox3.Text + "')";
cmd.ExecuteNonQuery();
conn.Close();
}
public OleDbConnection myCon { get; set; }
private void button2_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Ryan\Desktop\Coding\Microsoft Access\Northwind.mdb";
string fstName = textBox1.Text.Trim();
string lstName = textBox2.Text.Trim();
string adres = textBox3.Text.Trim();
OleDbCommand cmd = new OleDbCommand(#"INSERT INTO MyExcelTable (FName, LName, Address) VALUES (#FName, #LName, #Address)")
{
Connection = conn
};
conn.Open();
if (conn.State == ConnectionState.Open)
{
// you should always use parameterized queries to avoid SQL Injection
cmd.Parameters.Add("#FName", OleDbType.VarChar).Value = fstName;
cmd.Parameters.Add("#LName", OleDbType.VarChar).Value = lstName;
cmd.Parameters.Add("#Address", OleDbType.VarChar).Value = adres;
try
{
cmd.ExecuteNonQuery();
MessageBox.Show(#"Data Added");
conn.Close();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Source + "\n" + ex.Message);
conn.Close();
}
}
else
{
MessageBox.Show(#"Connection Failed");
}
}
}
}
Hello Friends i am trying to develop a shout box in asp.net but it ends with an error The connection was not closed. The connection's current state is open. Can you please help me out what is the problem in my code .
Shout.aspx.cs
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace finalWork
{
public partial class Shout : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
PopulateTextBox();
}
}
private void PopulateTextBox()
{
SqlConnection con = ConnectionManager.GetDatabaseConnection();
DataTable dt = new DataTable();
string name = string.Empty, message = string.Empty;
StringBuilder sb = new StringBuilder(string.Empty);
try
{
con.Open();
string sqlStatement = "SELECT * FROM Message";
SqlCommand cmd = new SqlCommand(sqlStatement, con);
SqlDataAdapter sqlDa = new SqlDataAdapter(cmd);
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
//get the data stored from the DataTable
name = dt.Rows[i]["Username"].ToString();// where Name is the FieldName from database
message = dt.Rows[i]["Message"].ToString();
sb.AppendFormat("Name:{0}Date Posted:{1}{2}", name + Environment.NewLine
, DateTime.Now.ToShortDateString() + Environment.NewLine
, message + Environment.NewLine);
}
// get the concated and formatted values from string builder and display the result in TextBoxPrintMessage
TextBoxPrintMessage.Text = sb.ToString();
}
con.Close();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Fetch Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
con.Close();
}
}
private void AddNewPost(string name, string message)
{
SqlConnection con = ConnectionManager.GetDatabaseConnection();
string sqlStatement = string.Empty;
sqlStatement = "INSERT INTO Message" +
"(Username,Message)" +
"VALUES (#Username,#Message)";
try
{
con.Open();
SqlCommand cmd = new SqlCommand(sqlStatement, con);
cmd.Parameters.AddWithValue("#Username", name);
cmd.Parameters.AddWithValue("#Message", message);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
con.Close();
}
}
protected void ButtonPost_Click(object sender, EventArgs e)
{
// Check for empty values fieds before inserting the record
if (TextBoxName.Text != string.Empty && TextBoxMessage.Text != string.Empty)
{
//insert new post to database
AddNewPost(TextBoxName.Text.Trim(), TextBoxMessage.Text.Trim());
//Populate the TextBox to reflect changes made
PopulateTextBox();
}
else
{
//display message if the field was not supplied
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "Script",
"alert('Please supply the required fields!');", true);
}
}
}
}
I just manually add it and it works :)
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
SqlConnection con = new SqlConnection(constr);
Add comment to following code its already called in finally block of PopulateTextBox() function.
//con.Close();
Remove con.Close(); inside Try block as you have used it in finally block.
Try This way. It will help you.
SqlConnection connection = new SqlConnection(youCconnectionString);
connection.Close();
connection.Open();
SqlCommand command = new SqlCommand("YourQuery", connection);
command.CommandType = CommandType.Text;
command.ExecuteNonQuery();
connection.Close();
command.Dispose();
I have three textbox in the web form, which is username, password and IC number that the user have to enter to register. if the IC number the person entered, matches the IC value of any record in the database, it will update the username and password that the person have typed into the username field and password field of that record that have the matching IC. The updating part is fine but What I would want to do is if the record in the database for username and password of the nric entered is filled up, I would like to have a error in a label saying that this NRIC already have a username and password. Help
Etc, If I entered S9583728F in the NRIC box, and want to register a account, but since in my table S9583728F already have a username and password which is settsser and ddddd, I want it to give me, this NRIC already have a username and password.
Error
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;
using System.Data;
using System.Web.Security;
using System.Globalization;
using System.Text;
using System.Threading;
public partial class register : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnCreate_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["sacpConnectionString"].ConnectionString))
{
try
{
SqlCommand cmd = new SqlCommand();
Guid guid;
guid = Guid.NewGuid();
string sql = #"UPDATE patient
SET
pUserName = #pUserName,
pPassword = #pPassword
WHERE pIC = #pIC";
cmd.Parameters.AddWithValue("#pIC", txtIC.Value);
cmd.Parameters.AddWithValue("#pUsername", txtUsername.Value);
cmd.Parameters.AddWithValue("#pPassword", txtPassword.Value);
cmd.Connection = con;
cmd.CommandText = sql;
con.Open();
cmd.ExecuteNonQuery();
cmd.CommandText = "SELECT patientID, pUsername, pPassword FROM patient WHERE pIC = #pIC;";
int id = (cmd.ExecuteScalar() != null) ? Convert.ToInt32(cmd.ExecuteScalar()) : 0;
if (id > 0)
{
Session.Add("ID", id);
Session.Add("Username", txtUsername.Value);
Session.Add("Password", txtPassword.Value);
FormsAuthentication.SetAuthCookie(txtUsername.Value, true);
Response.Redirect("registered.aspx");
}
else
{
lblErrorMessage.Text = "IC does not exist";
}
}
/*
catch (Exception)
{
lblErrorMessage.Text = "IC does not exist";
}
*/
finally
{
con.Close();
}
}
}
}
}
Just change your UPDATE Query as below:
string sql = #"UPDATE patient
SET
pUserName = #pUserName,
pPassword = #pPassword
WHERE pIC = #pIC and pUserName='' and pPassword =''";
Solution 2: write a seperate function and continue with UPDATE if it returns false else display warning message.
boolean IsIDExist()
{
SqlCommand cmd = new SqlCommand();
string sql = #"SELECT count(*) from patient
WHERE pIC = #pIC" and pUserName!='' and pPassword !=''";
cmd.Parameters.AddWithValue("#pIC", txtIC.Value);
cmd.Connection = con;
cmd.CommandText = sql;
con.Open();
if(Convert.ToInte32(cmd.ExecuteScalar())>0)
return true;
return false;
}
Complete Code:
boolean IsIDExist()
{
SqlCommand cmd = new SqlCommand();
string sql = #"SELECT count(*) from patient
WHERE pIC = #pIC" and pUserName!='' and pPassword !=''";
cmd.Parameters.AddWithValue("#pIC", txtIC.Value);
cmd.Connection = con;
cmd.CommandText = sql;
con.Open();
if(Convert.ToInte32(cmd.ExecuteScalar())>0)
return true;
return false;
}
if (Page.IsValid)
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["sacpConnectionString"].ConnectionString))
{
try
{
SqlCommand cmd = new SqlCommand();
Guid guid;
guid = Guid.NewGuid();
string sql = #"UPDATE patient
SET
pUserName = #pUserName,
pPassword = #pPassword
WHERE pIC = #pIC and pUserName='' and pPassword=''";
cmd.Parameters.AddWithValue("#pIC", txtIC.Value);
cmd.Parameters.AddWithValue("#pUsername", txtUsername.Value);
cmd.Parameters.AddWithValue("#pPassword", txtPassword.Value);
cmd.Connection = con;
cmd.CommandText = sql;
con.Open();
cmd.ExecuteNonQuery();
if (!IsIDExist())
{
Session.Add("ID", id);
Session.Add("Username", txtUsername.Value);
Session.Add("Password", txtPassword.Value);
FormsAuthentication.SetAuthCookie(txtUsername.Value, true);
Response.Redirect("registered.aspx");
}
else
{
lblErrorMessage.Text = "IC Already Exist";
}
}
/*
catch (Exception)
{
lblErrorMessage.Text = "IC does not exist";
}
*/
finally
{
con.Close();
}
}
}