Trying to run the following code below so when a user selects ID from Combobox then whatever field has that ID in my database it will fill in the labels in my form.
This error in the screenshot keeps on appearing. I'm new to c# programming so, some friendly assistance would be great :)
Error
private void button1_Click_1(object sender, EventArgs e)
{
try
{
con.Open();
OleDbCommand
command = new OleDbCommand("SELECT * FROM tbl_newsurvey WHERE ID= '" + comboBoxID.Text + "'");
command.Connection = con;
cmd.Parameters.AddWithValue("ID", comboBoxID.SelectedIndex.ToString());
OleDbDataReader selectreader = command.ExecuteReader();
while (selectreader.Read() == true)
{
string name = selectreader["txtname"].ToString();
lblname.Text = Name;
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
Can you convert your ID field to varchar in your database and check if the following line is the one throwing the error?
cmd.Parameters.AddWithValue("ID", comboBoxID.SelectedIndex.ToString());
Refer to this documentation.
private void btnLogin_Click(object sender, EventArgs e)
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "select * from Cafelist where Username = '" + txtUsn.Text + "' and Password = '" + txtPass.Text + "'";
OleDbDataReader reader = command.ExecuteReader();
int count = 0;
while (reader.Read())
{
count = count + 1;
}
if(count ==1)
{
MessageBox.Show("Username and password is correct");
}
else if (count > 1)
{
MessageBox.Show("Duplicate Found");
}
else
{
MessageBox.Show("Username/Password Incorrect");
}
connection.Close();
}
trying to use this code to pull usn and pass for login, and get this error, tried looking around for a solution but haven't found any similar to my issue, i understand this is probably something really basic but please go easy as i've only been playing around with c# a couple weeks and this is my first attempt at using databases.
not trying to do any security features just trying to work out why when i enter text and click login this error appears, i have been following a youtube video try and self teach (as much as you can with this subject) however he doesn't hit this error and i have googled myself into oblivion.
thanks in advance, anymore information required let me know as this is my first time posting.
You need to insert the parameters to be replaced on your query for your actual values, query and parameters are separated on the OleDbCommand, try replacing your cmd.CommandText like this
command.CommandText = "select * from Cafelist where Username = #UserName and Password = #UserPass";
Then you need to give the parameters to the cmd like this:
cmd.Parameters.AddRange(new OleDbParameter[]
{
new OleDbParameter("#UserName", txtUsn.Text),
new OleDbParameter("#UserPass", txtPass.Text),
...
});
what am basically trying to do here is to scrap user opinion and put each user opinion one by one in each row. Code seems to be alright. But everytime I try to run it gives me syntax error. enter image description here
And this is my code:
foreach (var item in HeaderNames)
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "INSERT INTO Review (Rev,Url) values('" + item.InnerText + "','" + txtURL.Text + "')";
MessageBox.Show("this is test");
command.ExecuteNonQuery();
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I am new to ASP.NET, I am facing some difficulty in updating records inside database in ASP.NET. My code is showing no errors, but still the records are not being updated. I am using SQL Server 2012.
Code behind is as follows:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["user"] != null)
{
con.Open();
string query = "Select * from Customers where UserName ='" + Session["user"] + "'";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
txt_name.Text = reader["CustName"].ToString();
txt_phonenumber.Text = reader["Contact"].ToString();
txt_address.Text = reader["CustAddress"].ToString();
txt_cardnum.Text = reader["CustAccountNo"].ToString();
txt_city.Text = reader["CustCity"].ToString();
txt_emailaddress.Text = reader["Email"].ToString();
txt_postalcode.Text = reader["CustPOBox"].ToString();
Cnic.Text = reader["CustCNIC"].ToString();
}
con.Close();
}
else
{
Response.Redirect("Login.aspx");
}
}
protected void BtnSubmit_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd2 = con.CreateCommand();
SqlCommand cmd1 = con.CreateCommand();
cmd1.CommandType = CommandType.Text;
cmd1.CommandText = "Select CustID from Customers where UserName = '" + Session["user"] + "'";
int id = Convert.ToInt32(cmd1.ExecuteScalar());
cmd2.CommandType = CommandType.Text;
cmd2.CommandText = "update Customers set CustName='" + txt_name.Text + "',CustCNIC='" + Cnic.Text + "',Email='" + txt_emailaddress.Text + "',CustAccountNo='" + txt_cardnum.Text + "',CustAddress='" + txt_address.Text + "',CustPOBox='" + txt_postalcode.Text + "' where CustID='" + id + "'";
cmd2.ExecuteNonQuery();
con.Close();
}
Help will be much appreciated. THANKS!
After debugging the result i am getting is this
cmd2.CommandText "update Customers set CustName='Umer Farooq',CustCNIC='42101555555555',Email='adada#gmail.com',CustAccountNo='0',CustAddress='',CustPOBox='0' where CustID='6'" string
Here Account Number And POBOX is 0 and address is going as empty string. But i have filled the text fields
First thing to do to fix this is to use good ADO techniques, using SqlParameters for the passed in values; and not the risky SQL Injection method of concatenating strings together.
This first portion does just that. I have added in the int sqlRA variable to read the results of the non-query, which will return Rows Affected by the query. This is wrapped in a simple try...catch routine to set the value to negative 1 on any error. Other error handling is up to you. That makes your code look something like this:
cmd1.Parameters.AddWithValue("#SessionUser", Session["User"]);
int id = Convert.ToInt32(cmd1.ExecuteScalar());
cmd2.CommandType = CommandType.Text;
cmd2.CommandText = "UPDATE Customers SET CustName = #CustName, CustCNIC = #CustCNIC, Email = #Email, CustAccountNo = #CustAccountNo, CustAddress = #CustAddress, CustPOBox = #CustPOBox WHERE (CustID = #CustID)";
cmd2.Parameters.AddWithValue("#CustName", txt_name.Text);
cmd2.Parameters.AddWithValue("#CustCNIC", Cnic.Text);
cmd2.Parameters.AddWithValue("#Email", txt_emailaddress.Text);
cmd2.Parameters.AddWithValue("#CustAccountNo", txt_cardnum.Text);
cmd2.Parameters.AddWithValue("#CustAddress", txt_address.Text);
cmd2.Parameters.AddWithValue("#CustPOBox", txt_postalcode.Text);
cmd2.Parameters.AddWithValue("#CustID", id);
int sqlRA
try { sqlRA = cmd2.ExecuteNonQuery(); }
catch (Exception ex) {
sqlRA = -1;
// your error handling
}
/* sqlRA values explained
-1 : Error occurred
0 : Record not found
1 : 1 Record updated
>1 :Multiple records updated
*/
Now reading through your code, all we are doing with the first query is mapping the Session["User"] to id, and then using that id in the second query to do the update, and that Username is not updated in the second. Waste of a query most likely, as we could use the Session["User"] to do the update. That will bring you down to this query, and still bring back that Rows Affected value back:
cmd0.CommandType = CommandType.Text;
cmd0.CommandText = "UPDATE Customers SET CustName = #CustName, CustCNIC = #CustCNIC, Email = #Email, CustAccountNo = #CustAccountNo, CustAddress = #CustAddress, CustPOBox = #CustPOBox WHERE (UserName = #SessionUser)";
cmd0.Parameters.AddWithValue("#CustName", txt_name.Text);
cmd0.Parameters.AddWithValue("#CustCNIC", Cnic.Text);
cmd0.Parameters.AddWithValue("#Email", txt_emailaddress.Text);
cmd0.Parameters.AddWithValue("#CustAccountNo", txt_cardnum.Text);
cmd0.Parameters.AddWithValue("#CustAddress", txt_address.Text);
cmd0.Parameters.AddWithValue("#CustPOBox", txt_postalcode.Text);
cmd0.Parameters.AddWithValue("#SessionUser", Session["User"]);
int sqlRA
try { sqlRA = cmd0.ExecuteNonQuery(); }
catch (Exception ex) {
sqlRA = -1;
// your error handling
}
/* sqlRA values explained
-1 : Error occurred
0 : Record not found
1 : 1 Record updated
>1 :Multiple records updated
*/
When BtnSubmit fires the event, the code in the Page_Load runs before the codes in BtnSubmit, replacing the values placed in the TextBox with the values from the Database before the Update takes place.
OleDbConnection cn = new OleDbConnection();
cn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\`Hp\Desktop\PROGRAM1\notificationSystem\notificationSystem\Database.accdb";
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = cn;
//reg();
cn.Open();
cmd.CommandText = "select article from news where npublished = '" + metroDateTime1.Text + "' AND ntime = '" + label4.Text + "'";
//AND ntime = '" + label4.Text + "'
//Scalar executes the fetching of data
var a = cmd.ExecuteScalar();
//this statement gets the process of getting the data from the database to label
if (a != null)
{
label1.Text = "" + a.ToString();
//while in this statement is displaying the data inside the textbox
metroTextBox2.Text = label1.Text;
}
else if (metroTextBox2.Text != null)
{
//SEND SMS PROCESS
}
else if (metroTextBox2.Text == null)
{
//REPEAT FETCH
}
cn.Close();
So the code above works but I use a button, and I have to press the button everytime to fetch information. Does anyone have any advice on what should I do to automatically fetch information from database using datagridview and display it on textbox?
I want to put the code on form load, so everytime I will run the program it will automatically fetch and do its job. But I don't know how to do it and I tried but it won't work.
Any help is gradly appreciated.