must declare the scalar variable #TextBox1 asp.net - c#

this is the part of the code that i am sharing for the solution of my new application.
when i execute this code,it throws exception "Must declare the scalar variable #textBox1"
public partial class About : Page
{
SqlCommand cmd = new SqlCommand();
SqlConnection con = new SqlConnection();
protected void Page_Load(object sender, EventArgs e)
{
con.ConnectionString = "Data Source=.;Initial Catalog=carpro;Integrated Security=True";
con.Open();
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("Insert into Driver_Registration(Driver_Name,Driver_DOB,Driver_Address,License_Number,National_Insurance_Number,"+
"Email_Address,UK_History,Contact,Occupation,License_Details,Taxi_License_Number,"+
"Deposit_Details,Weekly_Rent) Values (#TextBox1,#TextBox2,#TextBox3,#TextBox4,#TextBox5," +
"#TextBox6,#TextBox7,#TextBox8,#TextBox9,#TextBox10,#TextBox11,#TextBox12,#TextBox13)",con);
cmd.Parameters.AddWithValue("#Driver_Name",TextBox1.Text);
cmd.Parameters.AddWithValue("#Driver_DOB", TextBox2.Text);
cmd.Parameters.AddWithValue("#Driver_Address", TextBox3.Text);
cmd.Parameters.AddWithValue("#License_Number", TextBox4.Text);
cmd.Parameters.AddWithValue("#National_Insurance_Number", TextBox5.Text);
cmd.Parameters.AddWithValue("#Email_Address", TextBox6.Text);
cmd.Parameters.AddWithValue("#UK_History", TextBox7.Text);
cmd.Parameters.AddWithValue("#Contact", TextBox8.Text);
cmd.Parameters.AddWithValue("#Occupation", TextBox9.Text);
cmd.Parameters.AddWithValue("#License_Details", TextBox10.Text);
cmd.Parameters.AddWithValue("#Taxi_License_Number", TextBox11.Text);
cmd.Parameters.AddWithValue("#Deposit_Details", TextBox12.Text);
cmd.Parameters.AddWithValue("#Weekly_Rent", TextBox13.Text);
cmd.ExecuteNonQuery();
Label1.Text = "Registration Successfull";
con.Close();
}
}

The parameters you are using in your INSERT statement are not the same parameters you are creating in your cmd.Parameters.AddWithValue(..). Replace the INSERT parameters to the ones you actually created like #Driver_Name.
Also, you should move your
con.ConnectionString = "Data Source=.;Initial Catalog=carpro;Integrated Security=True";
con.Open();
down to your button. Essentially you are only opening your connection once, then closing it on button click. Currently, there is no way to re-open the connection without re-starting the application.
Or better yet segment it off into its own class/function.
Or even better, setup the connection string in the web.config and call it from there utilizing dependency injection.

in your query you specify the parameters:
(#TextBox1,#TextBox2,#TextBox3,#TextBox4,#TextBox5," +
"#TextBox6,#TextBox7,#TextBox8,#TextBox9,#TextBox10,#TextBox11,#TextBox12,#TextBox13)
you have 2 options
1 you can change your query to :
VALUES(#Driver_Name,......
2 you can change you AddWithValue to:
cmd.Parameters.AddWithValue("#TextBox1",TextBox1.Text);
...

Related

Application freeze at connection.open()

I created a Firebird database and successfully connected to it via Visual Studio Server Explorer. Now I want to test it through code, so I made a simple form that - on a button press - changes a label text to a value from the database. Here is the code
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("data source=localhost;initial catalog=D:\\poslovanje\\POSLOVANJE.FDB;user id=SYSDBA");
SqlCommand cmd = new SqlCommand("SELECT ID FROM USERS", con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while(dr.Read())
{
label3.Text = dr[0].ToString();
}
con.Close();
}
Problem is my application just freezes when it comes to con.Open();
I have also tried this connection string:
User=SYSDBA;Password=masterkey;Database=D:\\poslovanje\\poslovanje.fdb;Data Source=localhost;
It's basic beginners mistake, i need to use FbConnection and FbCommand, not Sql

Display DateTime iin C# and WPF

I have a DateTime variable selected in a 1st window and I'm trying to display in in a 2nd window. It connects to the DB as it should be,but it appears a random data from the DB,not the selected one.
Here is the code:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Are you sure?");
Window1 win1 = new Window1();
win1.Show();
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
{
string connectionString = null;
SqlConnection cnn;
connectionString =
#"Data Source=IBWS05\MSSQLSERVER2012;Initial Catalog=Interview;Integrated Security=True";
try
{
SqlConnection con =
new SqlConnection(
#"Data Source=IBWS05\MSSQLSERVER2012;Initial Catalog=Interview;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
con.Open();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText =
"insert into [Event] (Description,StartData,EndData,Type) values (#description,#startdata,#endata,#type)";
cmd.Parameters.AddWithValue("description", descriptionTxt.Text);
cmd.Parameters.AddWithValue("startData", StartDate.Value);
cmd.Parameters.AddWithValue("endata", EndDate.Value);
cmd.Parameters.AddWithValue("type", typeTxt.Text);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data Saved");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
////Window2 win = new Window2(id);
//Window2 win3 = new Window2();
//this.Close();
//win3.Show();
SqlConnection conn =
new SqlConnection(
#"Data Source=IBWS05\MSSQLSERVER2012;Initial Catalog=Interview;Integrated Security=True");
SqlCommand comm = new SqlCommand();
comm.Connection = conn;
comm.CommandType = CommandType.Text;
int query= Convert.ToInt32(comm.CommandText = "select MAX(StartData) from [Events]");
Window2 win = new Window2(query);
win.Show();
}
The error is input string was not in a correct format. How can I convert it?
There are a few things you need to look at/consider in your code, first is your issue.
This line of code:
int query= Convert.ToDateTime(comm.CommandText = "select MAX(DateTime) from [Events]");
Won't achieve what you are after as you aren't executing the code. You are actually trying to convert your command object to a Date Time.
Earlier in your method you are writing to the database and part of that you call the following:
cmd.ExecuteNonQuery();
There are various other methods that you have on the command object that all work in different ways. To read about them visit this MSDN page, but essentially you probably want to use the ExectuteScalar method for what you are trying to do.
Next, I would consider moving your connection string to the app.config file and accessing it from there rather than typing it out multiple times.
And finally, I would use a using statement for each of your Connection's so that you ensure they are being disposed of correctly.
Just some extra food for thought.

Insert into database button code not working unsure how to fix it

I have tried to fix it but it wont take the three words i try to insert. it says error
"Format of the initialization string does not conform to specification
starting at index 0."
here is the button code
private void button5_Click(object sender, RoutedEventArgs e)
{
SqlConnection con = new SqlConnection("ConnectionOne");
con.Open();
MySqlCommand cmd = new MySqlCommand("INSERT INTO test.lifestyle(animal_food,animal_hobbies,animal_sport) values('" + this.food_txt.Text + "','" + this.hobby_txt.Text + "','" + sport_txt.Text + "');");
cmd.ExecuteNonQuery();
con.Close();
}
The ConnectionOne is the name of the connection i have made with the data base
I strongly suspect you have a variable as ConnectionOne and this saves your string.
In such a case, you need to use it as;
SqlConnection con = new SqlConnection(ConnectionOne);
But more important, you should always use paramterized queries. This kind of string concateanations are open for SQL Injection attacks.
Also use using statement to dispose your SqlConnection and SqlCommand instead of calling .Close() method manually.
private void button5_Click(object sender, RoutedEventArgs e)
{
using(var con = new SqlConnection(ConnectionOne))
using(var cmd = con.CreateCommand())
{
cmd.CommandText = #"INSERT INTO test.lifestyle(animal_food,animal_hobbies,animal_sport)
values(#food, #hobbies, #sport)";
cmd.Parameters.AddWithValue("#food", this.food_txt.Text);
cmd.Parameters.AddWithValue("#hobbies", this.hobby_txt.Text);
cmd.Parameters.AddWithValue("#sport", sport_txt.Text);
con.Open();
cmd.ExecuteNonQuery();
}
}

exception thrown while connecting to database: connection property has not been initialized

I am trying basic database insert and this code is waht I am running in visual studio 2010:-
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString="Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\Administrator\\Documents\\Visual Studio 2010\\WebSites\\WebSite3\\App_Data\\name.mdf;Integrated Security=True;User Instance=True";
SqlCommand cmd = new SqlCommand("insert into names values('" + TextBox1.Text + "')");
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
where am I wrong?
You created a connection and opened it, but you did not associate it with the SqlCommand. You can do this a couple of ways, either in the constructor of the SqlCommand or through the Connection property of the SqlCommand.
Additionally, you should use parameterized queries to prevent SQL Injection attacks. I'd also recommend putting the SqlConnection in a using block to ensure it is closed and properly disposed of. Putting all of that together gives you something like this:
protected void Button1_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\Administrator\\Documents\\Visual Studio 2010\\WebSites\\WebSite3\\App_Data\\name.mdf;Integrated Security=True;User Instance=True"))
{
conn.Open();
SqlCommand cmd = new SqlCommand("insert into names values(#name)", conn);
// Alternatively, you could do cmd.Connection = conn if you didn't pass
// the connection object into the SqlCommand constructor
cmd.Parameters.AddWithValue("#name", TextBox1.Text);
cmd.ExecuteNonQuery();
}
}
You did not assign the connection to the command object. try:
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString="Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\Administrator\\Documents\\Visual Studio 2010\\WebSites\\WebSite3\\App_Data\\name.mdf;Integrated Security=True;User Instance=True";
SqlCommand cmd = new SqlCommand("insert into names values('" + TextBox1.Text + "')");
cmd.Connection = conn; // <- this is the missing line
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}

About connecting sql server to c# (with ADO.NET)

I Have a problem in connecting my database to c# in connection string section
this is my code but when i run it , i get an error about this :
"Format of the initialization string does not conform to specification
starting at index 84"
My Code:
private void button2_Click(object sender, EventArgs e)
{
SqlConnection Cn = new SqlConnection(#" Server=TheAddress ; Database=MyDataBase.mdf ; integrated security='True' #");
Cn.Open();
SqlCommand Cm = new SqlCommand("", Cn);
Cm.CommandText = "INSERT INTO Table1(ID_Food, Name_Food , TypeOfService_Food , Price_Food , Type_Food) VALUES (#ID_Food , #Name_Food , #TypeOfService_Food , #Price_Food , #Type_Food)";
Cm.Parameters.AddWithValue("#ID_Food", textBox1.Text);
Cm.Parameters.AddWithValue("#Name_Food", textBox2.Text);
Cm.Parameters.AddWithValue("#TypeOfService_Food", textBox3.Text);
Cm.Parameters.AddWithValue("#Price_Food", textBox4.Text);
Cm.Parameters.AddWithValue("#Type_Food", textBox5.Text);
Cm.ExecuteNonQuery();
Cn.Close();
}
I Cant Even Open My Connection (Error Happen in declaring SqlConnection)
I know its an Amature Question ... but its made me angry (i cant set it correctly)(with visual studio 2012 & sqlserver management studio 2012)
Looks like you have a "#" at the end you should remove from the connection string. You also might consider using the using statements when creating the SqlConnection and SqlCommand objects so they are properly disposed.
using (var Cn = new SqlConnection(#"Server=TheAddress;Database=MyDataBase.mdf;integrated security=True"))
{
Cn.Open();
using (var Cm = new SqlCommand("", Cn))
{
Cm.CommandText = "INSERT INTO Table1(ID_Food, Name_Food , TypeOfService_Food , Price_Food , Type_Food) VALUES (#ID_Food , #Name_Food , #TypeOfService_Food , #Price_Food , #Type_Food)";
Cm.Parameters.AddWithValue("#ID_Food", textBox1.Text);
Cm.Parameters.AddWithValue("#Name_Food", textBox2.Text);
Cm.Parameters.AddWithValue("#TypeOfService_Food", textBox3.Text);
Cm.Parameters.AddWithValue("#Price_Food", textBox4.Text);
Cm.Parameters.AddWithValue("#Type_Food", textBox5.Text);
Cm.ExecuteNonQuery();
Cn.Close();
}
}
you need to provide valid connection string .
Try This :
SqlConnection Cn = new SqlConnection(#"Data Source=TheAddress;Initial Catalog=MyDataBase.mdf;Integrated Security=True");
EDIT : from comments : as you are getting runtime excpetion please check wether you are able to communicate with the server or not.
Check this here

Categories

Resources