How to save data to Service-based Database in Visual Studio - c#

I have a local Db named NumLeter.mdf whit two tables: LeterTb and NumberTb. I want to insert in NumberTb new values, when the application is running the new values that I inserted show to me correctly as if they had been inserted, but when close the application and clic in Show Table Data the new data was not added in the table. I have instaled EntityFramework v:6.1.3. This 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.SqlClient;
namespace LearningVS
{
public partial class Form1 : Form
{
SqlConnection conexion;
public Form1()
{
InitializeComponent();
conexion = cConexion.getConexion();
}
private void btInsertNum_Click(object sender, EventArgs e)
{
insertNumber();
}
public void insertNumber()
{
SqlCommand command = new SqlCommand();
command.Connection = conexion;
command.CommandText = "INSERT INTO NumberTb(numberA, numberB, numberC) VALUES(#numberA, #numberB, #numberC)";
command.Parameters.Add("numberA", SqlDbType.Int, 3).Value = this.txNumberA.Text;
command.Parameters.Add("numberB", SqlDbType.Int, 3).Value = this.txNumberB.Text;
command.Parameters.Add("numberC", SqlDbType.Int, 3).Value = this.txNumberC.Text;
command.ExecuteNonQuery();
//testing this either
/*SqlDataAdapter datAdapt = new SqlDataAdapter(command);
NumLeterDataSet dtSet = new NumLeterDataSet();
datAdapt.FillSchema(dtSet, SchemaType.Source, "NumberTb");
datAdapt.Fill(dtSet, "NumberTb");
datAdapt.Update(dtSet.NumberTb);*/
}
//Also I tried by creating ADO.NET Entity Data Model whit the same result
private void button1_Click(object sender, EventArgs e)
{
using (var db = new NumDbModel())
{
var numbers = new NumberTb()
{
numberA = 22,
numberB = 33,
numberC = 44,
};
db.NumberTBs.Add(numbers);
db.SaveChanges();
}
}
}}
this is where I handle the connection
namespace LearningVS
{
class cConexion
{
private static SqlConnection conexion;
public static SqlConnection getConexion()
{
if (conexion != null)
{
return conexion;
}
conexion = new SqlConnection(Properties.Settings.Default.NumLetersConnectionString);
try
{
conexion.Open();
return conexion;
}
catch (Exception e)
{
System.Windows.Forms.MessageBox.Show("Error de conexión" + e.Message);
return null;
}
}
public static void cerrarConexion()
{
if (conexion != null)
{
conexion.Close();
}
}
}}

Related

Passing updates back to sql server from a datagrid viewer

I have an sqladapter declared inside a private void and I cant refence it for the update void.
Can anyone advise where I should declare it so it is available in the whole script please?
SqlAdapter is called sqlDataAdap.
The sqladapter is declared in the GetList void and then needs to be called in here but cant be referenced.
private void UpdateRowToDatabase() {
if (LastDataRow!=null) {
if (LastDataRow.RowState==
DataRowState.Modified) {
sqlDataAdap.Update(LastDataRow);
}
}
}
Cheers for the help - it's hard being a newb again!
Dave
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data;
using System;
using System.Data.SqlClient; //For SQL Connection
namespace Reference_Table_Updater
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.Load += Form1_Load;
}
void GetList()
{
String strConnection = "server=myserver';" +
"Database='Scratchpad';" +
"Integrated Security=SSPI";
SqlConnection con = new SqlConnection(strConnection);
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = con;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "Select * from dbo.UPDATE_Test";
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);
DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
dataGridView1.DataSource = dtRecord;
dataGridView1.Refresh();
//con.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
GetList();
}
private DataRow LastDataRow = null;
private void UpdateRowToDatabase() {
if (LastDataRow!=null) {
if (LastDataRow.RowState==
DataRowState.Modified) {
sqlDataAdap.Update(LastDataRow);
}
}
}
private void regionBindingSource_PositionChanged(
object sender, EventArgs e)
{
BindingSource thisBindingSource =
(BindingSource)sender;
DataRow ThisDataRow=
((DataRowView)thisBindingSource.Current).Row;
if (ThisDataRow==LastDataRow) {
throw new ApplicationException("It seems the" +
" PositionChanged event was fired twice for" +
" the same row");
}
UpdateRowToDatabase();
LastDataRow = ThisDataRow;
}
private void MainForm_FormClosed(
object sender, FormClosedEventArgs e)
{
UpdateRowToDatabase();
}
}
}

SQL not working on c# but working in SQL Server Management Studio

Update should be updating the data in the confirm table with the given parameters. However no input gets updated/inputted despite there being no errors.
When the exact same query is inputted into the SQL Server Management Studio there is no errors and the rows are updated.
Why is the table not being updated?
There are 3 columns in the table - orderid (which is passed from another table) and then staffid and confirmed which should both be NULL - and are - until the rows are updated. orderid = int not null, staffid = int, confirmed = string.confirm database
The view is a left outer join, meaning that it shows the values that need to be update by the by.
[sql][2]
database diagram
Form
How can this be fixed, its been like this for two days.
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.Data.SqlTypes;
namespace ComicBookShop
{
public partial class orders_confirm : Form
{
public orders_confirm()
{
InitializeComponent();
}
//database details
string connString = "Data Source = BLAH BLAH BLAH";
private void btnBack_Click(object sender, EventArgs e)
{
this.Hide();
ManagmentMain fm = new ManagmentMain();
fm.Show();
}
private void orders_confirm_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(connString);
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM staff_view", con))
{
cmd.CommandType = CommandType.Text;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
//Set AutoGenerateColumns False
dataGridView5.AutoGenerateColumns = true;
dataGridView5.DataSource = dt;
}
}
}
con.Close();
}
}
private void btnUpdate_Click(object sender, EventArgs e)
{
if (txtConfirmed.Text == "" || txtorder.Text == "" || txtstaff.Text == "")
{
MessageBox.Show("Please fill textboxes");
return;
}
//database details
string connString = "Data Source = aak; Initial Catalog = aa; User ID = aa; Password = aa";
SqlConnection con = new SqlConnection(connString);
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand command = con.CreateCommand())
{
try
{
con.Open();
command.CommandText = "Update dbo.confirm set staffid=#staffid, confirmed=#confirmed where orderid =#orderid";
command.Parameters.AddWithValue("#orderid", txtorder.Text);
command.Parameters.AddWithValue("#staffid", txtstaff.Text);
command.Parameters.AddWithValue("#confirmed", txtConfirmed.Text);
command.ExecuteNonQuery();
con.Close();
MessageBox.Show("Updated");
}
catch (SqlException ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
}
}
this is the part of the code where the data should be inserted
private void btnUpdate_Click(object sender, EventArgs e)
{
if (txtConfirmed.Text == "" || txtorder.Text == "" || txtstaff.Text == "")
{
MessageBox.Show("Please fill textboxes");
return;
}
//database details
string connString = "Data Source = aak; Initial Catalog = aa; User ID = aa; Password = aa";
SqlConnection con = new SqlConnection(connString);
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand command = con.CreateCommand())
{
try
{
con.Open();
command.CommandText = "Update dbo.confirm set staffid=#staffid, confirmed=#confirmed where orderid =#orderid";
command.Parameters.AddWithValue("#orderid", txtorder.Text);
command.Parameters.AddWithValue("#staffid", txtstaff.Text);
command.Parameters.AddWithValue("#confirmed", txtConfirmed.Text);
command.ExecuteNonQuery();
con.Close();
MessageBox.Show("Updated");
}
catch (SqlException ex)
{
Console.WriteLine(ex.Message);
}
}
}
Try setting parameters with their corresponding data types:
command.Parameters.Add("orderid", SqlDbType.Int);
command.Parameters["orderid"].Value = int.Parse(txtorder.Text);
Do the same for staffid.
I think the issue is you are passing string where int is expected.

c# : How to get data from database and pass to another form?

I'm building a desktop application where when a used logged it in new his Id will be appeared in textBox. But in my case query run successfully but id doesn't appear in textBox..can anyone help me to find it out please?
First form of User logged in (Form1.cs)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace EmployeeApp
{
public partial class login : Form
{
public login()
{
InitializeComponent();
}
public string employeeID;
private void exitButton_Click(object sender, EventArgs e)
{
this.Close();
}
private void loginButton_Click(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection(#"Data Source=INCEPSYS-SE\TEST;Initial Catalog=Employee;Integrated Security=True");
connection.Open();
String query = "select * from Employees where Name = '" + nameTextBox.Text + " ' and Password = '" + passwordTextBox.Text + "'";
SqlCommand command = new SqlCommand(query, connection);
SqlDataReader myReader = command.ExecuteReader();
while (myReader.Read())
{
string employeeID = myReader["EmployeeID"].ToString();
}
myReader.Close();
SqlDataAdapter sda = new SqlDataAdapter(query,connection);
connection.Close();
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count == 1)
{
this.Hide();
Entry ss = new Entry(employeeID);
ss.Show();
}
else
{
MessageBox.Show("Please Check your Username & password");
}
}
}
}
Second form (Entry.cs)
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;
namespace EmployeeApp
{
public partial class Entry : Form
{
public Entry()
{
InitializeComponent();
}
public Entry(string employeeId)
{
InitializeComponent();
idTextBox.Text = employeeId;
}
private void reportButton_Click(object sender, EventArgs e)
{
Report report = new Report();
report.Show();
}
}
}
Remove local variable declaration, because employeeID is a global variable and already declared first, so when you prefix it using string its create another local variable which is not accessible outside this scope
while (myReader.Read())
{
employeeID = myReader["EmployeeID"].ToString();
}
You have a local variable. You can correct and optimize you code like this:
private void loginButton_Click(object sender, EventArgs e)
{
//If use set quote into your textbox
string name = nameTextBox.Text.Replace("'", "''");
string pass = passwordTextBox.Text.Replace("'", "''");
String query = string.Format("select * from Employees where Name = '{0}' and Password = '{1}'", name, pass);
string employeeID = "";
using (SqlConnection connection = new SqlConnection(#"Data Source=INCEPSYS-SE\TEST;Initial Catalog=Employee;Integrated Security=True"))
{
connection.Open();
using (SqlDataAdapter sda = new SqlDataAdapter(query, connection))
{
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count > 0)
{
employeeID = dt.Rows[0]["EmployeeID"].ToString();
this.Hide();
Entry ss = new Entry(employeeID);
ss.Show();
}
else
{
MessageBox.Show("Please Check your Username & password");
}
dt.Dispose();
}
}
}

Import All Access Table Data Into SQL Server Table

I am needing to take all of my access tables and create the exact same table in SQL Server 2008 with data and keys/constraints. The below syntax will insert data if the table already exists, but how do I do it if the table does not exist? Or is there a better method programmatic ally in play to already achieve this result?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AccessToSQL
{
public partial class Form1 : Form
{
const string databaselocation = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Database1.accdb;Persist Security Info = False;";
List<string> tables = new List<string>();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
GetTableNames();
const string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Database1.accdb;Persist Security Info = False;";
const string connectionStringDest = "Data Source = TO\\SQLEXPRESS;Initial Catalog=Testing;Integrated Security=SSPI;";
using (var sourceConnection = new OleDbConnection(connectionString))
{
sourceConnection.Open();
using (var destinationConnection = new SqlConnection(connectionStringDest))
{
destinationConnection.Open();
foreach (string tbl in tables)
{
var commandSourceData = new OleDbCommand("Select * from "+tbl, sourceConnection);
var reader = commandSourceData.ExecuteReader();
using (var bulkCopy = new SqlBulkCopy(destinationConnection))
{
bulkCopy.DestinationTableName = "dbo."+tbl;
try { bulkCopy.WriteToServer(reader); }
catch (Exception ex) { MessageBox.Show(ex.Message); }
finally { reader.Close(); }
}
}
}
}
}
public List<string> GetTableNames()
{
try {
using (OleDbConnection con = new OleDbConnection(databaselocation))
{
con.Open();
//DataTable schema = con.GetSchema("Columns");
//foreach (DataRow row in schema.Rows)
//{
// tables.Add(row.Field<string>("TABLE_NAME"));
//}
foreach (DataRow r in con.GetSchema("Tables").Select("TABLE_TYPE = 'TABLE'"))
{
tables.Add(r["TABLE_NAME"].ToString());
}
return tables;
}
}
catch (Exception ex) { MessageBox.Show(ex.Message); }
return tables;
}
}
}

Why do i keep getting a blank form C#

I have a login_form and an admin_form. whenever I try to login I keep getting an empty form. why do I keep getting it?
this my login_form 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.SqlClient;
using System.IO;
namespace InternationalStudentsSociteySmartSystem
{
public partial class login_form : Form
{
public login_form()
{
InitializeComponent();
}
private void login_button_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=.;Initial Catalog=ISSSS_DB;Integrated Security=True");
SqlDataAdapter sda = new SqlDataAdapter("Select Count(*) from Table_1 where FullName='" + username_text.Text + "' and Password='" + password_text.Text + "' and Role='" + comboBox1.Text + "'", con);
DataTable dt = new System.Data.DataTable();
sda.Fill(dt);
if (dt.Rows[0][0].ToString() == "1")
{
SqlDataAdapter sda1 = new SqlDataAdapter("Select Role from Table_1 where FullName='" + username_text.Text + "' and Password='" + password_text.Text + "'", con);
DataTable dt1 = new System.Data.DataTable();
sda1.Fill(dt1);
if (dt1.Rows[0][0].ToString() == "Administrator")
{
admin_form ss = new admin_form();
ss.Show();
}
if (dt1.Rows[0][0].ToString() == "Committee")
{
committee_form ss = new committee_form();
ss.Show();
}
if (dt1.Rows[0][0].ToString() == "Secretary")
{
secretary_form ss = new secretary_form();
ss.Show();
}
}
}
}
}
and this is my admin_form 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.SqlClient;
using System.IO;
namespace InternationalStudentsSociteySmartSystem
{
public partial class admin_form : Form
{
SqlConnection conn = new SqlConnection("Data Source=TAREK-PC;Initial Catalog=ISSSS_DB;Integrated Security=True");
SqlCommand command;
string imgLoc;
SqlDataReader myReader;
public admin_form(string username)
{
InitializeComponent();
}
public admin_form()
{
// TODO: Complete member initialization
}
private void button1_Click(object sender, EventArgs e)
{
welcome_text.Text = "Welcome!";
try
{
string sql = "SELECT Image FROM Table_1 WHERE FullName='" + admin_name_text.Text + "'";
if (conn.State != ConnectionState.Open)
conn.Open();
command = new SqlCommand(sql, conn);
SqlDataReader reader = command.ExecuteReader();
reader.Read();
if (reader.HasRows)
{
byte[] img = (byte[])(reader[0]);
if (img == null)
admin_picturebox.Image = null;
else
{
MemoryStream ms = new MemoryStream(img);
admin_picturebox.Image = Image.FromStream(ms);
}
}
else
{
}
conn.Close();
}
catch (Exception ex)
{
conn.Close();
MessageBox.Show(ex.Message);
}
}
private void admin_form_Load(object sender, EventArgs e)
{
admin_picturebox.SizeMode = PictureBoxSizeMode.StretchImage;
}
private void register_committee_button_Click(object sender, EventArgs e)
{
register_committee_form rcf = new register_committee_form();
rcf.Show();
}
}
}
as you can see I also have to other forms which are committee_form and secretary_form (which they work just fine) but I didn't write their code yet. so I figured the problem is with admin form...
I appreciate the help, thanks.
You are calling the admin_form constructor that doesn't take any parameters. In that constructor the call to InitializeComponent is missing. So your admin_form is totally blank
You should add the call to InitializeComponent also to the parameterless constructor of admin_form.
public admin_form(string username)
{
InitializeComponent();
}
public admin_form()
{
// TODO: Complete member initialization
InitializeComponent();
}
As a side note, not related to your actual problem. Your code that access the database is vulnerable to Sql Injection hacks. And you will have a lot of problems to parse your input data. You should start immediately to use a parameterized query approach instead of string concatenation

Categories