Adding data in sql Table columns - c#

I have this basic WinForms application user interface:
And I want to add the data both to the DataGridView and the sql table, when the "Gem" button is clicked. I have this following code:
private void Form2_Load(object sender, EventArgs e)
{
try
{
con = new SqlConnection();
con.ConnectionString = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Produkt.mdf;Integrated Security=True";
con.Open();
//adap = new SqlDataAdapter("select SN, FName as 'Navn', MName as 'Vare nr', LName as 'Antal', Age from Produkt", con);
string sql = "SELECT Navn, Varenr, Antal, Enhed, Priseksklmoms, Konto FROM ProduktTable";
adap = new SqlDataAdapter(sql, con);
ds = new System.Data.DataSet();
adap.Fill(ds, "ProduktTable");
dataGridView1.DataSource = ds.Tables["ProduktTable"];
}
catch (Exception ex)
{
MessageBox.Show("Error\n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void button1_Click(object sender, EventArgs e)
{
string navn = textBox2.Text;
int varenr = int.Parse(textBox3.Text);
float antal = (float)Convert.ToDouble(textBox4.Text);
string enhed = textBox5.Text;
string konto = comboBox2.Text;
float pris = (float)Convert.ToDouble(textBox6.Text);
dataGridView1.Rows[0].Cells[0].Value = navn;
dataGridView1.Rows[0].Cells[1].Value = varenr;
string StrQuery;
try
{
SqlCommand comm = new SqlCommand();
comm.Connection = con;
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
StrQuery = #"INSERT INTO tableName ProduktTable ("
+ dataGridView1.Rows[i].Cells["Varenr"].Value + ", "
+ dataGridView1.Rows[i].Cells["Antal"].Value + ");";
comm.CommandText = StrQuery;
comm.ExecuteNonQuery();
}
}
catch (Exception ex)
{
MessageBox.Show("Error\n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
This is just an example with the purpose for storing the string "navn" and the integer "Varenr" in the DataGridView and the sql. When Im running the application and clicking on the button, following error occurs:
What's wrong with the procedure ?.
Thanks in advance

The format for an insert name doesn't require the words tableName. It wants the actual table name.
INSERT INTO tableName ProduktTable
should be
INSERT INTO ProduktTable
assuming Produ**K**tTable isn't a typo.

Related

Data Mismatch In Criteria Expression

I am trying to delete data from a Database AND the DataGridViewer using Winforms on Visual Studio. The way I am doing this is selecting a cell, and based on where that cell is, that row will be deleted. The selected row will read two strings and one date. I've tested the two strings and they work perfectly when deleting data. When it comes to the date, it doesn't seem to work for me, I keep getting an error. The error message will be attached as an image and the code will be below. I am fairly new to C# and SQL, just to put that out there.
private void delete_Click(object sender, EventArgs e)
{
foreach (DataGridViewCell theCell in daily_log.SelectedCells)
{
if (theCell.Selected)
{
string eid = daily_log[0, theCell.RowIndex].Value.ToString();
string aid = daily_log[4, theCell.RowIndex].Value.ToString();
DateTime dt = Convert.ToDateTime(daily_log[5, theCell.RowIndex].Value);
try
{
connection.Open();
using (OleDbCommand cmd = new OleDbCommand("DELETE FROM DailyLog WHERE EmployeeID='" + eid + "' AND ActivityID = '" + aid + "' AND Date = '" + dt.Date + "'", connection))
{
cmd.ExecuteNonQuery();
}
connection.Close();
daily_log.Rows.RemoveAt(theCell.RowIndex);
}
catch (Exception ex)
{
MessageBox.Show("Err: " + ex);
}
}
}
}
Is this a conversion error? And if so, how would I fix this?
You could try to use OledbParameter to delete data from access database.
Here is a code example you can refer to.
OleDbConnection conn = new OleDbConnection("connstr");
private void button1_Click(object sender, EventArgs e)
{
foreach (DataGridViewCell theCell in dataGridView1.SelectedCells)
{
if (theCell.Selected)
{
string id = dataGridView1[0, theCell.RowIndex].Value.ToString();
string aid = dataGridView1[1, theCell.RowIndex].Value.ToString();
DateTime dt = Convert.ToDateTime(dataGridView1[2, theCell.RowIndex].Value);
try
{
conn.Open();
string sql = "delete from DailyLog where ID=#ID AND AID=#AID AND Date=#Date";
using (OleDbCommand cmd = new OleDbCommand(sql, conn))
{
cmd.Parameters.AddWithValue("#ID", id);
cmd.Parameters.AddWithValue("#AID", aid);
cmd.Parameters.AddWithValue("#Date", dt);
cmd.ExecuteNonQuery();
}
dataGridView1.Rows.RemoveAt(theCell.RowIndex);
}
catch (Exception ex)
{
MessageBox.Show("Err: " + ex);
}
}
}
conn.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
conn.Open();
string query = "select * from DailyLog";
OleDbDataAdapter da = new OleDbDataAdapter(query, conn);
OleDbCommandBuilder builder = new OleDbCommandBuilder(da);
var ds = new DataSet();
da.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
conn.Close();
}
Result:
Your Ids are probably numeric, and Date is a reserved word, so try with:
"DELETE FROM DailyLog WHERE EmployeeID = " + eid + " AND ActivityID = " + aid + " AND [Date] = #" + dt.Date.ToString("yyyy'/'MM'/dd") + "#"
That said, go for using parameters.
{

Update DB with updated Textbox Information in C#

Trying to update the first name of the student there is a textbox "FirstNameTextbox" information was loaded to it from the DB, when I change the information in the textbox and try to write the changes it read only the original data.So if it loaded "Craig" as the first name from the DB, i would edit and put "Chris" in the textbox, what happens is that Craig is written to the DB and not "Chris"
int stuID = getSqlStuID(IDNUMLabel.Text);
SqlConnection conn = new SqlConnection(GetConnectionString());
string sqlUpdateStudent = "Update tblStudent set fname = #fname where stuID = #stuID";
SqlCommand cmd = new SqlCommand(sqlUpdateStudent, conn);
conn.Open();
cmd.Parameters.AddWithValue("#stuID", stuID);
cmd.Parameters.AddWithValue("#fname", FirstNameTextbox.Text);
cmd.ExecuteNonQuery();
ErrorMessage.Text = "Success";
protected void Page_Load(object sender, EventArgs e)
{
if (Session["User"] != null)
{
IDNUMLabel.Text = Session["User"].ToString();
getStuData(Session["User"].ToString());
}
else
{
Response.Redirect("../Login/Login.aspx");
}
}
private void getStuData(string id)
{
SqlConnection conn = new SqlConnection(GetConnectionString());
string sql = "Select fname, sname From tblStudent Where idnumber = '" + id + "' ";
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
conn.Open();
SqlDataReader selectedRecord = cmd.ExecuteReader();
cmd.CommandType = CommandType.Text;
while (selectedRecord.Read())
{
FirstNameTextbox.Text = selectedRecord["fname"].ToString();
LastNameTextbox.Text = selectedRecord["sname"].ToString();
}
selectedRecord.Close();
}
catch (System.Data.SqlClient.SqlException ex)
{
//id = 0;
//string msg = "Error reading Student ID";
//msg += ex.Message;
//throw new Exception(msg);
}
catch (Exception ex)
{
}
finally
{
conn.Close();
}
}
At what point do you make the actual update? After a button was pressed, after the value was entered on the textbox...? You're missing the method in which the code that handles the update is placed...
Maybe this could help: How to display data from database into textbox, and update it

SqlDataAdapter Insert Database not working C# winform

I am trying to insert data into a SQL Server database and show on DatagridView from a C# Winforms.
I click on the Insert button no error shows, but no data is being Insert into the database and Datagridview becomes blank.
I re-debug that can see data update in datagridview, but the database is not on Visual Studio Server Explorer DataBase(picture1).
On the other hand.I set breakpoint when click Insert Button,that jump over line 42~46.Directly to line 50.ex(picture2).
picture1
picture2
Edit:
The question now is when I click insert button,datagridview have update new data.But database no insert new data.Database only two data.
Edit2
I changed connection string AttachDbFilename.
AttachDbFilename=C:\Vis\NO4\WindowsFormsApplication1\App_Dat‌​a\Database1.mdf;
The value can insert database.
Here is the connection string:
<add name="con1" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True"
providerName="System.Data.SqlClient" />
Here is the Form_load and load_grid function
SqlConnection con;
SqlDataAdapter da;
DataSet ds = new DataSet();
DataTable dt = new DataTable();
public Form1()
{
InitializeComponent();
string connectionString = ConfigurationManager.ConnectionStrings["con1"].ConnectionString;
con = new SqlConnection(connectionString);
}
private void Form1_Load(object sender, EventArgs e)
{
load_grid();
}
public void load_grid()
{
dt.Clear();
SqlDataAdapter da1 = new SqlDataAdapter();
try
{
string sql = "SELECT * FROM profile";
con.Open();
da1.SelectCommand = new SqlCommand(sql, con);
da1.Fill(ds);
da1.Fill(dt);
con.Close();
dataGridView1.DataSource = dt;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Here is the Insert Button
private void button1_Click(object sender, EventArgs e)
{
string ac = textBox1.Text;
string bd = textBox2.Text;
string sex = textBox2.Text;
string sql = "INSERT INTO profile(ac,bd,sex)VALUES('" + ac + "','" + bd + "','" + sex + "')";
try
{
con.Open();
da = new SqlDataAdapter();
da.InsertCommand = new SqlCommand(sql, con);
da.InsertCommand.ExecuteNonQuery();
da.Update(dt);
MessageBox.Show("INsert success...!!");
load_grid();
con.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Here is the design of the Costumer table
CREATE TABLE [dbo].[profile] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[ac] NVARCHAR (50) NULL,
[bd] NVARCHAR (50) NULL,
[sex] NVARCHAR (50) NULL,
PRIMARY KEY CLUSTERED ([Id] ASC));
Not sure where the issue is here.
Picture2 shows an exception that connection is already open so, try following before opening a connection. You are calling load_grid(); before closing connection.
I have update all code, use it as explained below:
Edit- Second Revision:
public void load_grid()
{
dt.Clear();
SqlDataAdapter da1 = new SqlDataAdapter();
try
{
string sql = "SELECT * FROM profile";
con.Open();
da1.SelectCommand = new SqlCommand(sql, con);
da1.Fill(ds);
da1.Fill(dt);
con.Close();
dataGridView1.DataSource = dt;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (con.State != System.Data.ConnectionState.Closed)
con.Close();
}
}
private void button1_Click(object sender, EventArgs e)
{
string ac = textBox1.Text;
string bd = textBox2.Text;
string sex = textBox2.Text;
string sql = "INSERT INTO profile(ac,bd,sex)VALUES('" + ac + "','" + bd + "','" + sex + "')";
try
{
con.Open();
da = new SqlDataAdapter();
da.InsertCommand = new SqlCommand(sql, con);
da.InsertCommand.ExecuteNonQuery();
da.Update(dt);
con.Close();
MessageBox.Show("INsert success...!!");
load_grid();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (con.State != System.Data.ConnectionState.Closed)
con.Close();
}
}

How to Insert Data to the Database? - User Defined Classes

I'm Experimenting with databases and I'm finding different methods to optimize my codes. Here I'm using a different class to stop re writing the same codes such as for add, Delete and update we use the same ExecuteNonQuery() method. So far Update delete methods worked well except the Insert. Compiler doesn't give any errors but the values taken from the text boxes doesn't go to the variable string query. I'm new to c# coding. Can anyone help me? or an advice?
using DBconnectionExercise.DBConnection_Components;
namespace DBconnectionExercise
{
public partial class Student_Form : Form
{
DBComps dc = new DBComps();
//public string constring;
//public SqlConnection con = null;
//public SqlCommand com = null;
public String query;
public Student_Form()
{
InitializeComponent();
//constring = "Data Source=ASHANE-PC\\ASHANESQL;Initial Catalog=SchoolDB;Integrated Security=True";
//con = new SqlConnection(constring);
dc.ConnectDB();
}
private void Form1_Load(object sender, EventArgs e)
{
loadGridData();
}
private void dtp_dob_ValueChanged(object sender, EventArgs e)
{
DateTime Now = DateTime.Today;
DateTime Dob = dtp_dob.Value.Date;
int a = Now.Year - Dob.Year;
if (Now < Dob.AddYears(a)) a--;
tb_Age.Text = a.ToString();
}
private void loadGridData()
{
try
{
query = "Select * from tb_Student";
//dc.OpenCon();
//SqlDataAdapter da = new SqlDataAdapter(query, con);
DataTable dt1 = new DataTable();
dt1 = dc.Data_Table(query);
//da.Fill(dt);
Stu_DataGrid.DataSource = dt1;
//con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void ClearData()
{
tb_Name.Clear();
tb_Address.Clear();
tb_Telno.Clear();
tb_Search.Clear();
tb_Age.Clear();
dtp_dob.Value = DateTime.Today;
}
private void btn_Add_Click(object sender, EventArgs e)
{
try
{
String name = tb_Name.Text;
DateTime dob = dtp_dob.Value.Date;
int age = Convert.ToInt32(tb_Age.Text);
String Address = tb_Address.Text;
int telno = Convert.ToInt32(tb_Telno.Text);
int line = 0;
//con.Open();
query = "Insert into tb_Student values(#Stu_Name, #Stu_DOB, #Age, #Stu_Address, #Stu_Tel_no)";
//query = "Insert into tb_Student (Stu_Name, Stu_DOB, Age, Stu_Address, Stu_Tel_no) Values('" + name + "','" + dob + "','" + age + "','" + Address + "','" + telno + "')";
MessageBox.Show(query);
//com = new SqlCommand(query, con);
// This is the Insert/save code
DBComps.com.Parameters.AddWithValue("#Stu_Name", name);
DBComps.com.Parameters.AddWithValue("#Stu_DOB", dob);
DBComps.com.Parameters.AddWithValue("#Age", age);
DBComps.com.Parameters.AddWithValue("#Stu_Address", Address);
DBComps.com.Parameters.AddWithValue("#Stu_Tel_no", telno);
//line = com.ExecuteNonQuery();
line = dc.ExeNonQuery(query);
//com.Dispose();
//con.Close();
if (line > 0)
{
loadGridData();
ClearData();
MessageBox.Show("Data saved sucessfully!", "Data Saved", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
MessageBox.Show("Data not Saved", "Error Save", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
This is the DBComps class which I used to write the Sql Function methods.
namespace DBconnectionExercise.DBConnection_Components
{
public class DBComps
{
public String conSring;
public SqlConnection con = null;
public static SqlCommand com = null;
public void ConnectDB()
{
conSring = "Data Source=ASHANE-PC\\ASHANESQL;Initial Catalog=SchoolDB;Integrated Security=True";
con = new SqlConnection(conSring);
}
public void OpenCon()
{
con.Open();
}
public void CloseCon()
{
con.Close();
}
public int ExeNonQuery(String query) //the method for Insert, update and delete.
{
int line = 0;
OpenCon();
com = new SqlCommand(query, con);
line = com.ExecuteNonQuery();
com.Dispose();
CloseCon();
return line;
}
}
}
This is really really bad way of talking to database, its hackable using SQL injection and since you are learning, its right time to point this out:
query = "Insert into tb_Student values('"+ name +"','"+ dob +"','"+ age +"','"+ Address +"','"+ telno +"')";
read up on sql injection as to why and how, and look for best practices to find out better ways .
OK finally I came up with the Answer to my question as I expected. Here how to do this;
private void btn_Add_Click(object sender, EventArgs e)
{
try
{
String name = tb_Name.Text;
DateTime dob = dtp_dob.Value.Date;
int age = Convert.ToInt32(tb_Age.Text);
String Address = tb_Address.Text;
int telno = Convert.ToInt32(tb_Telno.Text);
int line = 0;
query = "Insert into tb_Student values('"+ name +"','"+ dob +"','"+ age +"','"+ Address +"','"+ telno +"')";
MessageBox.Show(query); //To see it works!
line = dc.ExeNonQuery(query);
if (line > 0)
{
loadGridData();
ClearData();
MessageBox.Show("Data saved sucessfully!", "Data Saved", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
MessageBox.Show("Data not Saved", "Error Save", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Always remember to write the query statement variables/values exactly as to coincide with the table headers. Otherwise it will generate errors. Thanks everyone for helping with this question! :-)

Connect to two tables

I have created comboBox and filled with one column, after I choose item from the combobox I would like to show other column in the textboxs so I wrote code to make it happen but what if I want to choose column from another table I mean I would like to show couple of columns from two different table in the textbox when I hit the combobox
Here is my code:
private void comboLname_SelectedIndexChanged(object sender, EventArgs e)
{
string conn = "Data Source=srv-db-02;Initial Catalog=rmsmasterdbtest;Persist Security Info=True;User ID=test;Password=*******";
string Query = "select * from rmsmasterdbtest.dbo.customer where LastName= '" + comboLname.Text + "' ;";
SqlConnection Myconn = new SqlConnection(conn);
SqlCommand cmdDataBase = new SqlCommand(Query, Myconn);
SqlDataReader Reader;
try
{
Myconn.Open();
Reader = cmdDataBase.ExecuteReader();
while (Reader.Read())
{
string ID = Reader.GetInt32(Reader.GetOrdinal("ID")).ToString();
string AccountNuber = Reader.GetString(Reader.GetOrdinal("AccountNumber"));
//string Time = Reader.GetString(Reader.GetOrdinal("Time"));
// string Deposit = Reader.GetString(Reader.GetOrdinal("Deposit"));
string sstatus = Reader.GetString(Reader.GetOrdinal("status"));
string slastname = Reader.GetString(Reader.GetOrdinal("lastname"));
txtid.Text = ID;
txtacnum.Text = AccountNuber;
//txttime.Text = Time;
//txtdeposit.Text = Deposit;
txtstatus.Text = sstatus;
txtlname.Text = slastname;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
Myconn.Close();
}
}

Categories