Insert does not working on Service Based Database in C# - c#

I have created a service based database in visual studio 2017. It works with a select statement but INSERT statement doesn't work. Here is my code.
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.Configuration;
using System.Data.SqlClient;
namespace RestaurantApp
{
public partial class Form1 : Form
{
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\SerinCafe.mdf;Integrated Security=True");
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
conn.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO Product (Id, ProductDescription, UnitPrice, SystemDate) Values (1,'Çay', 1, '01.01.2017')", conn);
cmd.ExecuteNonQuery();
SqlCommand cmd1 = new SqlCommand("SELECT * FROM Product", conn);
SqlDataAdapter da = new SqlDataAdapter(cmd1);
DataTable dt = new DataTable();
da.Fill(dt);
conn.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
Application.Exit();
}
I saw the same problem on different topics but there wasn't a clear solution that applies for me.
EDIT: On the SQL Server Object Explorer there is another database under the folder debug/bin. Now I checked it and I saw that data is inserted as I wanted. But it doesn't stay same. I changed the sql query as id = 3 and checked again. Previous data has gone. Newly inserted data is only there.

I have tested the code it works fine.Make sure you provided the connection string correctly.

Related

Chart COUNT Query C#?

Kinda new to C#, I'm a bit confused with this issue I encountered in my codes for a school assignment. Trying to make a Room Activity chart in a winform for a school project where the SQL COUNT query I input counts the rows that have the value 'Room Activity' under the Event column but for some odd reason, I receive an ArgumentException wasn't handled error that tells me Column with name 'Event' was not found.
What am I doing wrong with my code?
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.Windows.Forms.DataVisualization.Charting;
using System.Configuration;
using System.Data.SqlClient;
namespace Database_Chart_test
{
public partial class Form1 : Form
{
string strConnectionString = ConfigurationManager.ConnectionStrings["Database_Chart_test.Properties.Settings.LibrarySystemConnectionString"].ConnectionString;
public Form1()
{
InitializeComponent();
}
private void Activitychart_Click(object sender, EventArgs e)
{
}
private void RoomChart()
{
SqlConnection con = new SqlConnection(strConnectionString);
DataSet ds = new DataSet();
con.Open();
SqlDataAdapter adapt = new SqlDataAdapter("SELECT COUNT(*) FROM Log WHERE Event = 'Room Activity'", con);
adapt.Fill(ds);
Activitychart.DataSource = ds;
Activitychart.Series["WithActivity"].XValueMember = "Event";
Activitychart.Series["WithActivity"].YValueMembers = "Event";
con.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'librarySystemDataSet1.RoomsBooking' table. You can move, or remove it, as needed.
this.roomsBookingTableAdapter.Fill(this.librarySystemDataSet1.RoomsBooking);
// TODO: This line of code loads data into the 'librarySystemDataSet.Log' table. You can move, or remove it, as needed.
this.logTableAdapter.Fill(this.librarySystemDataSet.Log);
RoomChart();
}
}
}
After SELECT COUNT(*) FROM Log WHERE Event = 'Room Activity' executed, it will return a table with 1 column and 1 row (the count number).
Query result:
So the cause of the ArgumentException is that there is no column named Event in ds.Tables[0].
If you want to get the count, just call ExecuteScalar Method
using (SqlConnection conn = new SqlConnection(strConnectionString))
{
string strSQL = "SELECT COUNT(*) FROM Log WHERE Event = 'Room Activity'";
SqlCommand cmd = new SqlCommand(strSQL, conn);
conn.Open();
int count = (int)cmd.ExecuteScalar();
// add data point
Activitychart.Series["WithActivity"].Points.AddXY("Event", count);
Console.WriteLine("The count is {0}", count);
}
In addition, according to the code you provided, you are trying to use Event(a string) as YValueMembers. This does not seem reasonable. Generally, YValueMembers should be of numeric type.

Getting table data into Gridview in C# (SQLite) is not working

I want to show my data that I have stored in a SQLite database in an ASP.net page which I code in C#.
I searched a lot on the internet and in my previous question someone showed me a really helpfull article. I used the code but it still doesn't work.
What I want is to get the first three columns in my gridview. So "woord", "vertaling" and "gebruiker" from the table "tbWoorden" should be displayed in the gridview.
This is my code:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Scripts_Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnTest_Click(object sender, EventArgs e)
{
string connectionString =
#"Data Source=C:/Users/elias/Documents/Visual Studio 2017/WebSites/WebSite7/App_Data/overhoren.db";
using (var conn = new System.Data.SQLite.SQLiteConnection(connectionString))
{
conn.Open();
DataSet dsTest = new DataSet();
// Create a SELECT query.
string strSelectCmd = "SELECT woord,vertaling,gebruiker FROM tbWoorden";
// Create a SqlDataAdapter object
// SqlDataAdapter represents a set of data commands and a
// database connection that are used to fill the DataSet and
// update a SQL Server database.
SqlDataAdapter da = NewMethod(conn, strSelectCmd);
// Fill the DataTable named "Person" in DataSet with the rows
// returned by the query.new n
da.Fill(dsTest, "tbWoorden");
// Get the DataView from Person DataTable.
DataView dvPerson = dsTest.Tables["tbWoorden"].DefaultView;
// Set the sort column and sort order.
dvPerson.Sort = ViewState["SortExpression"].ToString();
// Bind the GridView control.
grdMijnLijsten.DataSource = dvPerson;
grdMijnLijsten.DataBind();
using (var command = new System.Data.SQLite.SQLiteCommand(conn))
{
command.Connection = conn;
command.CommandText =
#"SELECT[vertaling], [woord] FROM[tbWoorden] WHERE[woord] = 'ans'";
using (var reader = command.ExecuteReader())
{
string test = "";
}
}
}
}
private static SqlDataAdapter NewMethod(System.Data.SQLite.SQLiteConnection conn, string strSelectCmd)
{
return new SqlDataAdapter(strSelectCmd, conn);
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void grdMijnLijsten_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
The error I get is: cannot convert from 'System.Data.SQLite.SQLiteConnection' to 'string'.
The part that causes the error is the conn string in the NewMethod:
private static SqlDataAdapter NewMethod(System.Data.SQLite.SQLiteConnection conn, string strSelectCmd)
{
return new SqlDataAdapter(strSelectCmd, conn);
}
What do I have to change?
Thanks in advance, Elias
You have to use SQLiteDataAdapter (from the SQLite family) instead of SqlDataAdapter (which is part of the SQLClient family)

method is not being called by application

My method is not being called by my application. I've used breakpoints and it's never initiated in the code. I'm building a C# Windows Forms application using an Azure Database, but the DataGridView is never being filled neither is the code being called at all... I have noooo clue whatsoever why..
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;
using System.Configuration;
namespace MyWinFormsProj
{
public partial class CompanyForm : Form
{
public CompanyForm()
{
InitializeComponent();
}
//Connection String
string cs = ConfigurationManager.ConnectionStrings
["MyConnetion"].ConnectionString;
// Load all employees
private void dataEmployees_Load()
{
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand
(
"Select fname,ename FROM dbo.Users", con
);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
dataEmployees.DataSource = dt;
}
}
// Crate company
private void createCompany_Click_1(object sender, EventArgs e)
{
if (textBoxCompanyName.Text == "")
{
MessageBox.Show("Fill out information");
return;
}
using (SqlConnection con = new SqlConnection(cs))
{
//Create SqlConnection
con.Open();
SqlCommand cmd = new SqlCommand(
"insert into dbo.Company (companyName)
values(#companyName)", con);
cmd.Parameters.AddWithValue(
"#companyName", textBoxCompanyName.Text);
SqlDataAdapter adapt = new SqlDataAdapter(cmd);
MessageBox.Show("Grattis! Du har skapat ett företag");
}
}
}
}
The second method is working and is doing what it is supposed to do, but the first one is never called..
you need to set an event handler on the gridView onLoad and pass this method to the handler
public void GridView_OnLoad(object sender, EventArgs e)
{
dataEmployees_Load();
}
You need to fix your method signature to look like this:
private void dataEmployees_Load(object sender, EventArgs e)
Then, in your GirdView, you need to set this function as handler for event "onload":
OnLoad="dataEmployees_Load"
Thank you guys for your answers it helped my solve the problem. Like you were saying the problem was in the method not being called. So I called it directly on initiliazeComponent like this.
public partial class CompanyForm : Form
{
public CompanyForm()
{
InitializeComponent();
Load += new EventHandler(dataEmployees_Load); //Added this code
}
// Load all employees
private void dataEmployees_Load(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand
(
"Select fname,ename FROM dbo.Users", con
);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
dataEmployees.DataSource = dt;
}
}

C# button that would add text from one textbox into another textbox based on a SQL query

I am new to C# and need to create a little form application, that has two textboxes one that asks for a [File_ID] then when button is pressed send that number to a query and in another textbox display the output.
I have been playing around with it a bit, and have something like this. But it is not working. I am not sure if I should go on a different direction. I would REALLY appreciate your help.
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 testing
{
public partial class Form1 : Form
{
String str,dr;
SqlConnection con = new SqlConnection("Data Source=USHOU2016\\USFi;Initial Catalog=HOU_2016_Project;Integrated Security=True");
SqlCommand cmd;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
con.Open();
str = "SELECT TOP 1,[Sender Name],[Subject] from [OLE DB Destination] WHERE [CHAT #] ='" + textBox1.Text + "'";
cmd = new SqlCommand(str, con);
// dr = cmd.ExecuteReader();
con.Close();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
textBox1.Text = cmd.ExecuteScalar().ToString();
}
}
}
Your SQL query syntax is wrong it should rather be below. You have a extra , after TOP 1 .. remove that
SELECT TOP 1 [Sender Name],[Subject] from [OLE DB Destination] WHERE...
Again in your button click you are just creating the command cmd = new SqlCommand(str, con); but never executing it. and just closing the connection.
In textBox2_TextChanged event handler you are trying to execute the query but connection has already gone. I think it's time you should consider reading about ADO.NET
This should do the trick. A couple of things to note:
since the button is executing your sql and populating the 2nd textbox, there's no need for the textbox_changed event
Using string concatenation to append your variables to your sql query is bad practice and makes your code susceptible to Sql Injection. Instead, parameterize your sql inputs as shown in the code below.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string query = "SELECT TOP 1,[Sender Name],[Subject] "
+ " from[OLE DB Destination] WHERE[CHAT #] = :chatId ";
using (SqlConnection con = new SqlConnection("Data Source=USHOU2016\\USFi;Initial Catalog=HOU_2016_Project;Integrated Security=True"))
{
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("chatId", textBox1.Text); //use Sql parameters to protect yourself against Sql Injection!
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
reader.Read();
textBox2.Text = reader[0] + " " + reader[1]; //or however you want your output formatted
}
reader.close();
}
}
}

How to fix 'System.Data.OleDb.OleDbException'?

first off sorry to ask how to fix this error (i know its a common question) but i am quite new to C# and I cannot seem to find a solution for it.
I am making a windows form that imports data from an excel file and displays it in a DataGridView. When executing I get the error:
"An unhandled exception of type 'System.Data.OleDb.OleDbException'
occurred in System.Data.dll Additional information: No value given for
one or more required parameters."
Here is my code:
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;
using System.IO;
namespace WindowsFormsApplication2
{
public partial class CurrentOrders : Form
{
public CurrentOrders()
{
InitializeComponent();
}
private void CurrentOrders_Load(object sender, EventArgs e)
{
}
private void BackBtn_Click(object sender, EventArgs e)
{
NewOrder NewOrd = new NewOrder();
this.Hide();
NewOrd.Show();
}
private void DataGridViewLOG_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Tombies\Documents\Visual Studio 2013\Projects\WindowsFormsApplication2\WindowsFormsApplication2\PCSsheet.xls" + #";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=1;ImportMixedTypes=Text;TypeGuessRows=0""";
OleDbCommand command = new OleDbCommand
(
"SELECT DATE, CUSTOMER, PO, COMMENTS, PCS FROM [LOG$]", conn
);
DataSet DsOrderLOG = new DataSet();
OleDbDataAdapter Adapter = new OleDbDataAdapter(command);
conn.Open();
Adapter.Fill(DsOrderLOG);
conn.Close();
DataGridViewLOG.DataSource = DsOrderLOG.Tables[0];
}
}
}
I know it has something to do with the 'Adapter.Fill' at the bottom, but from there on I'm lost.
Any help is appreciated!
Date is probably the culprit. Try putting it (an all other column names, for that matter) in brackets:
"SELECT [DATE], [CUSTOMER], [PO], [COMMENTS], [PCS] FROM [LOG$]", conn

Categories