Asp.net adding database from textbox and dropdownlist - c#

net to adding database. I am trying to do texts on two textbox and one selected value in dropdownlist to add my table.
Here is my code
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;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string connectionString = #" Data Source=.\SQLEXPRESS;AttachDbFilename=C:\USERS\CEM\DOCUMENTS\VISUAL STUDIO 2010\WEBSITES\EKLEMEDENE\APP_DATA\DATABASE.MDF;Integrated Security=True;User Instance=True";
string queryString = "INSERT INTO ekle(flight, name, food) VALUES ('" + TextBox1.Text + " ' , '" + TextBox2.Text + " ' , '" + DropDownList1.SelectedValue + " ' )";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand(queryString, con);
con.Open();
command.ExecuteNonQuery();
con.Close();
}
}
After I execute I will have error
Database 'C:\Users\Cem\Documents\Visual Studio 2010\WebSites\eklemedene\App_Data\Database.mdf' already exists. Choose a different database name.
An attempt to attach an auto-named database for file C:\USERS\CEM\DOCUMENTS\VISUAL STUDIO 2010\WEBSITES\EKLEMEDENE\APP_DATA\DATABASE.MDF failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.

You're wide open for SQL-Injection. Avoid passing parameters directly from controls. Instead use Parameters.
Use using-statement for anything implementing IDisposable like Connections or Commands:
There's something wrong with your ConnectionString, you could try to use SqlConnectionStringBuilder class:
//Build the connection
SqlConnectionStringBuilder bldr = new SqlConnectionStringBuilder();
//Put your server or server\instance name here. Likely YourComputerName\SQLExpress
bldr.DataSource = ".\\SQLEXPRESS";
//Attach DB Filename
bldr.AttachDBFilename = #"C:\USERS\CEM\DOCUMENTS\VISUAL STUDIO 2010\WEBSITES\EKLEMEDENE\APP_DATA\DATABASE.MDF";
//User Instance
bldr.UserInstance = true;
//Whether or not a password is required.
bldr.IntegratedSecurity = true;
using(var connection = new SqlConnection(bldr.ConnectionString))
{
var sql = "INSERT INTO ekle(flight, name, food) VALUES (#flight, #name , #food)";
using(var command = new SqlCommand(sql, connection))
{
command.Parameters.AddWithValue("#flight", TextBox1.Text);
command.Parameters.AddWithValue("#name", TextBox2.Text);
command.Parameters.AddWithValue("#food", DropDownList1.SelectedValue);
connection.Open();
command.ExecuteNonQuery();
}
} // closes the connection implicitely

Related

How to update data in access 2010 using c# in visual Studio 2019

Sir,
I wrote a program for update data in my MS-Access database. but It show error message box. What is my fault? How can I fix it.
I am using MS-Access 2010. Database formet (.accdb). Other Information:
Table Name: user_info.
Table's Fields are: a) Name b) Designation c) User_Name d) Password.
Visual Studio 2019
C#
My Trying Code is:
using System.Data;
using System.Windows.Forms;
using System.Data.OleDb;
namespace Shahid_Abdul_Hamid_Hall_1._1
{
public partial class ChangePassword : Form
{
OleDbConnection conn = new OleDbConnection();
public ChangePassword(String User)
{
InitializeComponent();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\SAHHDB1.accdb;Persist Security Info=False;";
lvl_user.Text = User;
}
private void ChangePassword_Load(object sender, EventArgs e)
{
}
private void btn_cancel_Click(object sender, EventArgs e)
{
this.Hide();
}
private void btn_change_Click(object sender, EventArgs e)
{
if (txt_new_pass.Text == txt_cnew_pass.Text)
{
try
{
conn.Open();
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "update user_info set Password = '"+ txt_new_pass.Text + "' where User_Name = '"+ lvl_user.Text + "'";
cmd.ExecuteNonQuery();
conn.Close();
}
catch (Exception ew)
{
MessageBox.Show("Error" + " " + ew);
}
}
else
{
MessageBox.Show("'Confirm New Password' dosen't Match 'New Password'. Try Again.");
}
}
}
}
You may be best-off trying something like LINQ Connect Express, and letting VS auto-generate the code.
Otherwise, your provider does not appear to be up-to-date and you changed the path so I can't see if you did that right either. If LINQ Connect Express doesn't work, start with the snippit below.
string connectionString = # "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Your\Full\Path\Database.accdb";
// Create a connection
using(OleDbConnection connection = new OleDbConnection(connectionString)) {
// your code here
}

Why does ExecuteNonQuery give back "Input is not valid in this context" (ASP.NET | Ole Db)?

I want to change a user's name. The current name and the new one are textbox inputs. On debugging, I get the exception that f.e. "JOHN" is not valid in this context. Why does this happen? It should expect a string and receives it. Where is the mistake?
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.OleDb;
namespace WebApplication1
{
public partial class Index : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection();
con.ConnectionString = "...";
OleDbCommand changeFirstName = new OleDbCommand("UPDATE Usertable SET Name =" + #NewFN + " WHERE Name = " + #FN + "", con);
changeFirstName.Parameters.Add("#NewFN", OleDbType.VarChar).Value = getNewFirstName.Text;
changeFirstName.Parameters.Add("#FN", OleDbType.VarChar).Value = getFirstName.Text;
con.Open();
try
{
int i = changeFirstName.ExecuteNonQuery();
}
catch(Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex);
}
con.Close();
}
}
}
The parameter tokens are part of the SQL and live inside it:
OleDbCommand changeFirstName = new OleDbCommand(
"UPDATE Usertable SET Name = #NewFN WHERE Name = #FN", con);
Side notes:
the connection and command are both IDisposable and should use using
when possible, prefer the provider-specific provider over OleDB - for example, if you're connecting to SQL-Server, use SqlConnection / SqlCommand
you may find tools like "Dapper" save you a lot of work here
Example of all 3 combined:
using(var con = new SqlConnection("..."))
{
con.Execute("UPDATE Usertable SET Name = #NewFN WHERE Name = #FN",
new {
NewFN = getNewFirstName.Text,
FN = getFirstName.Text,
});
}
I got it now. Because it is OleDb I can not use # in the Command string. Instead of #NewFN and #FN I have to use ?. On Parameter.Add I have to use #Name to give them a value. Here is an example:
OleDbCommand changeFirstName = new OleDbCommand (”UPDATE Usertable SET Name = ? WHERE Name = ?“);
changeFirstName.Parameters.Add(”#Name“, OleDbType.VarChar).Value = getNewFirstName.Text;

Load data from SQL Server database to C#

I get this error:
System.Data.SqlClient.SqlException: 'Incorrect syntax near the keyword 'Table'.
when I run the program; it said the error near to table!
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;
namespace WindowsFormsApp3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string SOURCE = #"Data Source=DESKTOP-K39PU4T\SQLEXPRESS;Initial Catalog=Mohamed;Integrated Security=True";
SqlConnection CON = new SqlConnection(SOURCE);
CON.Open();
MessageBox.Show("DB Connected");
string SqlSelectQuery = " Select*From Table Where ID ="+ int.Parse(textBox1.Text);
SqlCommand cmd = new SqlCommand(SqlSelectQuery, CON);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
textBox2.Text = (dr["Name"].ToString());
textBox3.Text = (dr["Surname"].ToString());
textBox4.Text = (dr["Lastname"].ToString());
}
else
{
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
MessageBox.Show("No Record Found Please Enter Correct Id");
}
CON.Close();
}
}
}
I want to load the data from SQL Server to ASP.NET in Visual Studio
Table is key word, if you have table named "Table" you may need to use [Table] for escape keyword in the SQL string, otherwise give the correct table name instead of Table. also you better use parameters instead of concatenating string as sql statement.
string SqlSelectQuery = "Select * From [Table] Where ID =#ID";
SqlCommand cmd = new SqlCommand(SqlSelectQuery, CON);
cmd.Parameters.AddWithValue("#ID", int.Parse(textBox1.Text));
What is the table name from which you want to get data?
if its name is Table then replace " Select*From Table Where ID =" with " Select * From \"Table\" Where ID ="
otherwise replace Table with actual table name

How to solve ASP.NET custom login page error?

In Login.aspx.cs file
The codes are following
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.Configuration;
namespace Leave_Management
{
public partial class Login : System.Web.UI.Page
{
//private string strcon = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(#"Data Source=TAUFIQ-PC\SQLEXPRESS;Initial Catalog=LM;Integrated Security=True");
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
conn.Open();
string checkuser = "select UserName from [User] where UserName='" + TextBoxUN + "'";
SqlCommand com = new SqlCommand(checkuser, conn);
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
if (temp == 1)
{
string checkpass = "select password from [User] where UserName='" + TextBoxUN + "'";
SqlCommand passcom = new SqlCommand(checkpass, conn);
string password = passcom.ExecuteScalar().ToString().Replace(" ", "");
conn.Close();
if (password == TextBoxPass.Text)
{
Response.Redirect("Registration.aspx");
}
}
}
}
}
An Error is showing as
"NullReferenceException was unhandled by user code"
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
Please help me to solve this.
You can just simplify your code by checking both username and password from the SQL statement:
protected void Button1_Click(object sender, EventArgs e)
{
conn.Open();
string SQL = "select UserID from [User] where UserName=#UserName AND Password=#Password";
SqlCommand com = new SqlCommand(SQL, conn);
com.Parameters.AddWithValue("#UserName", TextBoxUN.Text);
com.Parameters.AddWithValue("#Password", TextBoxPass.Text);
SqlDataReader data = com.ExecuteReader();
if (data.HasRows) // username and password match
{
conn.Close();
Response.Redirect("Registration.aspx");
}
else
{
conn.Close();
// display error here
}
}
I assume that UserID is the primary key of your Users table. You can use other column names if you want.
I also used parameters to avoid SQL injection. Cheers!
Too long for a comment, there are many things wrong with your code:
You are concatenating user-specified values into SQL queries. Don't do it, use parameters.
You are putting TextBoxUN into the SQL, you probably want TextBoxUN.Text. This is the reason you get null, since there is no user with that name.
You must take the value provided by ExecuteScalar() and check if it is null. Now it is, so you get a clear error about it.
Why get the username from the database with the username and then check for password? You can check for password and username with one query.
Do not store passwords in cleartext in the database! Use hash functions.
if temp comes up as null, then you will get the error. I would try:
...
int temp = 0;
try {
temp = Convert.ToInt32(com.ExecuteScalar().ToString());
} catch (exception) {}
...

SqlCommand connection string for localhost database

I am trying to create a simple website in VS Express for Web 2013 which can interact with a database "Parts." My database is stored in the app_data folder. I am able to view the connection in the Server Explorer, which implies the connection string is saved. However, the following code throws 2 errors:
Error 13 The best overloaded method match for 'System.Data.SqlClient.SqlCommand.SqlCommand(string, System.Data.SqlClient.SqlConnection)' has some invalid arguments
Error 14 Argument 2: cannot convert from 'string' to 'System.Data.SqlClient.SqlConnection'
I don't know how to remedy this. Here is my c# code:
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void insertButton_Click(object sender, EventArgs e)
{
string connstring = System.Configuration.ConfigurationManager.ConnectionStrings["connect"].ConnectionString;
SqlCommand cmd = new SqlCommand("INSERT INTO PARTS VALUES('" + nameBox.Text + "', '" + descriptionBox.Text + "', '" + quantityBox.Text + "', '" + categoryList.SelectedValue + "')", connstring);
cmd.ExecuteNonQuery();
}
}
I'm completely new to c#, so please keep that in mind. Thanks for your help.
UPDATE: The following code throws two errors, both of which are:
Error 15 The name 'conn' does not exist in the current context
I'm new to c#, but it doesn't look like there's anything wrong with the code. The name "conn" is clearly defined right above.
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void insertButton_Click(object sender, EventArgs e)
{
using (var conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["connect"].ConnectionString))
using (var cmd = new SqlCommand(
"INSERT INTO PARTS VALUES(#name, #description, #quantity, #category)", conn))
{
cmd.Parameters.AddWithValue("name", nameBox.Text);
cmd.Parameters.AddWithValue("description", descriptionBox.Text);
cmd.Parameters.AddWithValue("quantity", quantityBox.Text);
cmd.Parameters.AddWithValue("category", categoryList.SelectedValue);
conn.Open();
cmd.ExecuteNonQuery();
}
}
}
using(var conn = new SqlConnection(connectionString))
{
conn.Open();
// use conn to create the command
}
But important: YOUR SQL IS REALLY REALLY DANGEROUS. That is open to SQL injection, a HUGE and trivially easy attack surface. Please please parameterize that.
For example:
using(var conn = new SqlConnection(connectionString))
using(var cmd = new SqlCommand(
"INSERT INTO PARTS VALUES(#name, #description, ...)", conn))
{
cmd.Parameters.AddWithValue("name", nameBox.Text);
cmd.Parameters.AddWithValue("description", descriptionBox.Text);
//...
conn.Open();
cmd.ExecuteNonQuery();
}
(note you need to add a few yourself; I have left it incomplete, just name and description used for example)
What is connect value from your config?
Can you try
SqlConnection conn = new SqlConnection(connstring);
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
and now issue the query.
You need to create a SqlConnection first:
string connstring = System.Configuration.ConfigurationManager.ConnectionStrings["connect"].ConnectionString;
SqlConnection conn = new SqlConnection(connstring);
SqlCommand cmd = new SqlCommand("INSERT INTO PARTS VALUES('" + nameBox.Text + "', '" + descriptionBox.Text + "', '" + quantityBox.Text + "', '" + categoryList.SelectedValue + "')"
, conn);
cmd.ExecuteNonQuery();
Some early habits to get into:
Do not concatenate SQL strings. This is for several reasons, not the least of which is the vulnerability to SQL Injection attacks.
wrap your connection and command in using statements. That ensures that the connections are closed properly if there is an exception.
The end result will look something like:
string connstring = ConfigurationManager.ConnectionStrings["connect"].ConnectionString;
using(SqlConnection conn = new SqlConnection(connstring))
{
string sql = "INSERT INTO PARTS VALUES(#name, #description, #quantity, #categoryList)"
using(SqlCommand cmd = new SqlCommand(sql , conn))
{
cmd.Parameters.AddWithValue("#name", nameBox.Text);
... etc.
cmd.ExecuteNonQuery();
}
}

Categories