inserting textbox value to sql server using c# - c#

I need to add a text box value to SQL Server database table. Below is my code:
private void button1_Click(object sender, EventArgs e)
{
string str = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\timetablesystem.mdf;Integrated Security=True;User Instance=True";
SqlConnection con = new SqlConnection(str);
string qry = "insert into SubjectMaster (SubjectName) values (#TxtSubjectName)";
con.Open();
SqlCommand cmd = new SqlCommand(qry, con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#TxtSubjectName", TxtSubjectName.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Added Successfully!!");
con.Close();
}
But, data should not add in table... please help me...
thanks for ur help...

Try debugging your query first if it works i think your connection with your db isnt working.
string str = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\timetablesystem.mdf;Integrated Security=True;User Instance=True";
is there supposed to be this '.' after data source Data Source=.\\SQLEXPRESS

try this and tell me what is the message information content
private void button1_Click(object sender, EventArgs e)
{
string str = "Server=.\SQLEXPRESS;Database=TestDB;Trusted_Connection=True;";
using( SqlConnection con = new SqlConnection(str)){
try{
con.Open();
string qry = "insert into SubjectMaster (SubjectName) values (#TxtSubjectName)";
SqlCommand cmd = new SqlCommand(qry, con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#TxtSubjectName", TxtSubjectName.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Added Successfully!!");
}
catch{
MessageBox.Show("connection is failed!!");
}
}
}

try this
SqlConnection con = new SqlConnection(#"Data Source=SL-20\SQLEXPRESS;Initial Catalog=TestDB;User ID=sa;Password=sl123;");
string query = " insert into name(name)values('" + TextboxTest.Text + "')";
con.Open();
SqlCommand cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
con.Close();

Related

"ExecuteScalar: Connection property has not been initialized."

I'm new to c# and currently I have some problems when I'm running this program without debugging.
This is the login page for my project. I've create a service-based database and I want to connect to the data which is username and password in the table 'Table' which is in the database.
However, I've encountered an issue which is "ExecuteScalar: Connection property has not been initialized." when I'm running this code.
Can anyone help me with this?
private void button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=c:\users\hp\documents\visual studio 2015\Projects\PersonalFinancialSoftware\PersonalFinancialSoftware\Login.mdf;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "SELECT COUNT (*) FROM Table where UserID = #userid AND Password = #password";
cmd.Parameters.AddWithValue("#userid", textBox1.Text);
cmd.Parameters.AddWithValue("#password", textBox2.Text);
object result = cmd.ExecuteScalar();
conn.Open();
string useridlogin = Convert.ToString(result);
conn.Close();
if (useridlogin != " ")
{
Home_Page homepage = new Home_Page();
homepage.Show();
}
else
{
MessageBox.Show("Invalid ID or password, please try again!", "Info", MessageBoxButtons.OK);
}
}
I can see that you've executed the ExecuteScalar method before opening the SQL Database connection, resulting in error you're getting.
Open the connection before ExecuteScalar method, and you're done.
private void button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=c:\users\hp\documents\visual studio 2015\Projects\PersonalFinancialSoftware\PersonalFinancialSoftware\Login.mdf;Integrated Security=True");
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "SELECT COUNT (*) FROM Table where UserID = #userid AND Password = #password";
cmd.Parameters.AddWithValue("#userid", textBox1.Text);
cmd.Parameters.AddWithValue("#password", textBox2.Text);
object result = cmd.ExecuteScalar();
string useridlogin = Convert.ToString(result);
conn.Close();
if (useridlogin != " ")
{
Home_Page homepage = new Home_Page();
homepage.Show();
}
else
{
MessageBox.Show("Invalid ID or password, please try again!", "Info", MessageBoxButtons.OK);
}
}
You have open connection after ExecuteScalar thats you are getting error, You must open connection befor ExecuteScalar try this code
private void button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=c:\users\hp\documents\visual studio 2015\Projects\PersonalFinancialSoftware\PersonalFinancialSoftware\Login.mdf;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
conn.Open();
cmd.CommandText = "SELECT COUNT (*) FROM Table where UserID = #userid AND Password = #password";
cmd.Parameters.AddWithValue("#userid", textBox1.Text);
cmd.Parameters.AddWithValue("#password", textBox2.Text);
object result = cmd.ExecuteScalar();
string useridlogin = Convert.ToString(result);
conn.Close();
if (useridlogin != " ")
{
Home_Page homepage = new Home_Page();
homepage.Show();
}
else
{
MessageBox.Show("Invalid ID or password, please try again!", "Info", MessageBoxButtons.OK);
}
}
In your code SQL query find connection. But you have open it after ExecuteScalar so this is giving you an error.

How to Retrieve Date and time from SQL to datetimepicker in c#?

If I enter a value(already entered in DB) and click a button(Retrieve) in my windows form, I have to retrieve date and time to my datetimepicker1 from SQL(already entered values).
Please correct my code.
This is my code.
private void button9_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=NIFAL;Initial Catalog=LaundrySystem;Integrated Security=True;");
con.Open();
str = "select * from LaundrySystemTable where laundID='" + textBox1.Text.Trim() + "'";
cmd = new SqlCommand(str, con);
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
string temp1 = reader["entryDate"].ToString();
DateTime dt1 = DateTime.Parse(temp1);
dateTimePicker1.Value = dt1.ToString("MM:dd:yyyy");
reader.Close();
con.Close();
}
}
NEVER use such an SQL that is open to SQL inkjection attacks, use parameters instead:
using (SqlConnection con = new SqlConnection("Data Source=NIFAL;Initial Catalog=LaundrySystem;Integrated Security=True;"))
{
string sql = "select entryDate from LaundrySystemTable where laundID=#id";
var cmd = new SqlCommand( sql, con );
cmd.Parameters.AddWithValue( "#id", textBox1.Text.Trim() ); // if its type is not string, then do the conversion here
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
dateTimePicker1.Value = (DateTime?)reader["entryDate"];
}
con.Close();
}

C# Listview , Data type Mismatch on insertion of record

I want to insert some data into Database Using C#
But I get below error
Error:Data type Mismatch when try to Execute
cmd1.ExecuteNonQuery();
private void btnFirst_Click(object sender, EventArgs e)
{
conString =Properties.Settings.Default.TransportationConnectionString;
con.ConnectionString = conString;
System.Data.OleDb.OleDbCommand cmd1 = new System.Data.OleDb.OleDbCommand();
cmd1.Connection = con;
cmd1.CommandText = "INSERT INTO [BillingGrd] ([InvoiceNo],[FromLocation],[ToLocation],[Material],[Trip],[MetricTon],[BillWeight],[Rate],[BillAmount],[GrandTotal]) Values (#InvoiceNo,#FromLocation,#ToLocation,#Material,#Trip,#MetricTon,#BillWeight,#Rate,#BillAmount,#GrandTotal)";
for(inc=0;inc<listView1.Items.Count;inc++)
{
cmd1.Parameters.AddWithValue("#InvoiceNo", txtBilNo.Text);
cmd1.Parameters.AddWithValue("#FromLocation", listView1.Items[inc].SubItems[0].Text);
cmd1.Parameters.AddWithValue("#ToLocation", listView1.Items[inc].SubItems[1].Text);
cmd1.Parameters.AddWithValue("#Material", listView1.Items[inc].SubItems[2].Text);
cmd1.Parameters.AddWithValue("#Trip", listView1.Items[inc].SubItems[3].Text);
cmd1.Parameters.AddWithValue("#MetricTon", listView1.Items[inc].SubItems[4].Text);
cmd1.Parameters.AddWithValue("#BillWeight", listView1.Items[inc].SubItems[5].Text);
cmd1.Parameters.AddWithValue("#Rate", listView1.Items[inc].SubItems[6].Text);
cmd1.Parameters.AddWithValue("#BillAmount", listView1.Items[inc].SubItems[7].Text);
cmd1.Parameters.AddWithValue("#GrandTotal", textBox1.Text);
}
con.Open();
cmd1.ExecuteNonQuery();//error here datatype mismatch
con.Close();
}
Try This might be work for you.....
if not Then let me know by comment
private void btnFirst_Click(object sender, EventArgs e)
{
conString =Properties.Settings.Default.TransportationConnectionString;
con.ConnectionString = conString;
System.Data.OleDb.OleDbCommand cmd1 = new System.Data.OleDb.OleDbCommand();
cmd1.Connection = con;
for(inc=0;inc<listView1.Items.Count;inc++)
{
cmd1.CommandText="";
con.Open();
cmd1.CommandText = "INSERT INTO [BillingGrd] ([InvoiceNo],[FromLocation],[ToLocation],[Material],[Trip],[MetricTon],[BillWeight],[Rate],[BillAmount],[GrandTotal]) Values ('"+txtBilNo.Text+"','"+listView1.Items[inc].SubItems[0].Text+"','"+listView1.Items[inc].SubItems[1].Text+"','"+listView1.Items[inc].SubItems[2].Text+"','"+listView1.Items[inc].SubItems[3].Text+"','"+listView1.Items[inc].SubItems[4].Text+"','"+listView1.Items[inc].SubItems[5].Text+"','"+listView1.Items[inc].SubItems[6].Text+"','"+listView1.Items[inc].SubItems[7].Text+'")";
cmd1.ExecuteNonQuery();//error here datatype mismatch
con.Close();
}
}

Read data from Access Database into listbox

Can someone tell me how to fix this error?
SqlCommand cmd = new SqlCommand(sqlCmd, conn)
--> conn: Aurgument type 'System.Data.OleDb.OleDbConnection' is not assignable to parameter type 'System.Data.SqlClient.SqlConnection'.
private void Form1_Load(object sender, EventArgs e)
{
string connString = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=C:\\Users\\KevinDW\\Desktop\\dotNET\\Week 5\\Prak1\\demo1.accdb";
OleDbConnection conn = new OleDbConnection(connString);
conn.Open();
string sqlCmd = "SELECT CursusNaam FROM tblCursus";
SqlCommand cmd = new SqlCommand(sqlCmd, conn);
using (SqlDataReader reader = cmd.ExecuteReader())
{
listBox1.Items.Add(reader);
}
conn.Close();
}
}
You're mixing up Sql and OleDb
Use OleDbCommand instead of SqlCommand
and use OleDBDataReader instead of SqlDataReader
For example:
private void Form1_Load(object sender, EventArgs e)
{
string connString = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=C:\\Users\\KevinDW\\Desktop\\dotNET\\Week 5\\Prak1\\demo1.accdb";
OleDbConnection conn = new OleDbConnection(connString);
conn.Open();
string sqlCmd = "SELECT CursusNaam FROM tblCursus";
OleDbCommand cmd = new OleDbCommand(sqlCmd, conn);
using (OleDBDataReader reader = cmd.ExecuteReader())
{
listBox1.Items.Add(reader);
}
conn.Close();
}
}
You are using SqlCommand/etc which requires the use of SqlConnection object instead of OleDbConnection.
Is it a SQL database you are connecting to? If so use SqlConnection instead
Edit: Obviously not, reading the connection string ... :D

Fill DropDownList from database

I am new to C# and trying to populate a DropDownList based on a database value. I tried connecting to database as shown below - tested with the statement and it says connected. Can I assume this is correct? Am I on the right track? Also, how do I then select value from the table and fill DropDownList with a field?
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection (
"Data Source=.\\SQLEXPRESS;AttachDbFilename=C:customers.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
try
{
connection.Open();
TextBox1.Text = "connected";
}
catch (Exception)
{
TextBox1.Text = " not connected";
}
}
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection (
"Data Source=.\\SQLEXPRESS;AttachDbFilename=C:customers.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
try
{
SqlDataReader dReader;
SqlCommand cmd = new SqlCommand();
cmd.Connection = connection;
cmd.CommandType = CommandType.Text;
cmd.CommandText ="Select distinct [Name] from [Names]" +
" order by [Name] asc";
connection.Open();
dReader = cmd.ExecuteReader();
if (dReader.HasRows == true)
{
while (dReader.Read())
//Names collection is a combo box.
namesCollection.Add(dReader["Name"].ToString());
}
else
{
MessageBox.Show("Data not found");
}
dReader.Close()
TextBox1.Text = "connected";
}
catch (Exception)
{
TextBox1.Text = " not connected";
}
}
Hope that helps................
It's So Much Simple :----
SqlConnection con = new SqlConnection();
DataSet ds = new DataSet();
con.ConnectionString = #"Data Source=TOP7\SQLEXPRESS;Initial Catalog=t1;Persist Security Info=True;User ID=Test;Password=t123";
string query = "Select * from tbl_User";
SqlCommand cmd = new SqlCommand(query, con);
cmd.CommandText = query;
con.Open();
SqlDataAdapter adpt = new SqlDataAdapter(cmd);
adpt.Fill(ds);
comboBox1.Items.Clear();
comboBox1.DisplayMember = "UserName";
comboBox1.ValueMember = "UserId";
comboBox1.DataSource = ds.Tables[0];
------------------------------------------------------------------------
using (SqlConnection con = new SqlConnection("Data Source = NIPOON; Initial Catalog = CustomerOrders; Integrated Security = true"))
{
SqlCommand cmd = new SqlCommand("SELECT Name FROM Customer", con);
con.Open();
dropDownList.DataSource = cmd.ExecuteReader();
dropDownList.DataTextField = "Name";
dropDownList.DataValueField = "Name";
dropDownList.DataBind();
}

Categories