I should build software gym.
I want to attach a photo to each employee in a gym.
So I followed the excellent guide on youtube that explains how to attach an image to the data.
The problem is that when I attach the picture is attaching in a new line in the table and not the existing line
thank you!!!!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.IO;
namespace gym
{
public partial class Load_Save : Form
{
OleDbConnection DBConnection = new OleDbConnection();
OleDbDataAdapter DataAdapter;
DataTable LocalDataTable = new DataTable();
int rowPosition=0;
int rowNumber=0;
public Load_Save()
{
InitializeComponent();
}
private void Load_Save_Load(object sender, EventArgs e)
{
ConnectToDatabase();
}
private void ConnectToDatabase()
{
DBConnection.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + Directory.GetCurrentDirectory() + "\\data.mdb";
DBConnection.Open();
DataAdapter = new OleDbDataAdapter("Select * From Workers", DBConnection);
DataAdapter.Fill(LocalDataTable);
if(LocalDataTable.Rows.Count !=0)
{
rowPosition = LocalDataTable.Rows.Count;
}
}
private void btnBrowse_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
pictureBox1.Image = Image.FromFile(openFileDialog1.FileName);
btnSave.Enabled = true;
}
}
private void btnSave_Click(object sender, EventArgs e)
{
StoreData(ConvertImageToBytes(pictureBox1.Image));
}
private byte[] ConvertImageToBytes(Image InputImage)
{
Bitmap BmpImage = new Bitmap(InputImage);
MemoryStream Mystream = new MemoryStream();
BmpImage.Save(Mystream, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] ImageAsBytes = Mystream.ToArray();
return ImageAsBytes;
}
private void StoreData(byte[] ImageAsBytes)
{
if(DBConnection.State.Equals(ConnectionState.Closed))
DBConnection.Open();
try
{
MessageBox.Show("Saving image at index: " + rowPosition.ToString());
OleDbCommand oledbInsert = new OleDbCommand("Insert INTO Workers (id,firtsname,lastname,email,username,job,passw,permission,phone,dateofjoin,photo) VALUES('" + "','" + "','" + "','" + "','" + "','" + "','" + "','" + "','" + "','" + "',#Myphoto)", DBConnection);
OleDbParameter imageParameter = oledbInsert.Parameters.AddWithValue("#photo", SqlDbType.Binary);
imageParameter.Value = ImageAsBytes;
imageParameter.Size = ImageAsBytes.Length;
int rowsAffected = oledbInsert.ExecuteNonQuery();
MessageBox.Show("data stored succ in" + rowsAffected.ToString() + " ROW");
rowPosition++;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
MessageBox.Show(ex.StackTrace.ToString());
}
finally
{
RefreshDBCconnection();
}
}
private void RefreshDBCconnection()
{
DBConnection.Close();
LocalDataTable.Clear();
ConnectToDatabase();
}
}
}
If you want to update something in your database, something that already exists, then in SQL-query you must use UPDATE statement(with id of old record) instead of INSERT. Like so:
UPDATE Workers SET photo=#photo WHERE id=#old_id
Or as variant(nice works if you want to update multiple records/multiple fields at same time, and simplify insert/update code) - you can BEGIN TRANSACTION, delete old record's with "DELETE", insert new one's using INSERT's with same id's, and then COMMIT TRANSACTION.
Related
When I have entered all the details into my Registration form it comes up with my error message and does not store the data in my database. I have tried loads of different ways to store the data into my db however none seem to be working. ID is college ID which is used to store students information.
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 NEWNEABlackjack
{
public partial class Register : Form
{
public Register()
{
InitializeComponent();
}
private void BtnRegistered_Click(object sender, EventArgs e)
{
var myForm = new LOGIN();
myForm.Show();
Close();
string connection = #"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = C:\Users\m2101305\OneDrive - Middlesbrough College\NEW NEA\NEWNEABlackjack\NEWNEABlackjack\DBLogins.mdf; Integrated Security = True";
SqlConnection conn = new SqlConnection(connection);
try
{
string query = "Insert into Table(Id,Username,FirstName,Surname,Password,Email,DOB) Values('" + IDtxtBox.Text + "','" + UNtxtBox.Text + "','" + FNtxtBox.Text + "','" + SNtxtBox.Text + "','" + PasswordtxtBox.Text + "','" + EAtxtBox.Text + "','" + DOBtxtBox.Text + "',)";
SqlDataAdapter ada = new SqlDataAdapter(query, conn);
conn.Open();
ada.SelectCommand.ExecuteNonQuery();
MessageBox.Show("Data Is Saved.");
ClearData();
}
catch
{
MessageBox.Show("ERROR Whilst Saving Data.");
}
finally
{
conn.Close();
}
}
private void ClearData()
{
IDtxtBox.Text = "";
UNtxtBox.Text = "";
FNtxtBox.Text = "";
SNtxtBox.Text = "";
PasswordtxtBox.Text = "";
EAtxtBox.Text = "";
DOBtxtBox.Text = "";
}
}
}
I am trying to create a chart that when, at the push of a button displays a chart that shows the user the number of times a record has appeared in the dataset/table that it is linked to. Please bare in mind that I have little experience with using Charts in Visual Studios/C#.
Currently I am getting this error: Error
This is all the code I have so far:
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;
namespace RRAS
{
public partial class formRRAS : Form
{
public OleDbConnection DataConnection = new OleDbConnection();
public formRRAS()
{
InitializeComponent();
}
private void formRRAS_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'database1DataSet.tblReject_test' table. You can move, or remove it, as needed.
this.tblReject_testTableAdapter.Fill(this.database1DataSet.tblReject_test);
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnSearch_Click(object sender, EventArgs e)
{
//This creates the String Publisher which grabs the information from the combo box on the form.
//Select and Dataconnection are also defined here.
string Select = "SELECT * FROM tblReject_test";
string DataConnection;
string Department = txtDepartment.Text;
string Start_Date = txtStart.Text;
string End_Date = txtEnd.Text;
string Anatomy = txtAnatomy.Text;
string RFR = cmbRFR.Text;
string Comment = txtComment.Text;
//Select defines what should be loaded on to the dataset.
if (Department != "")
{
Select = Select + " WHERE department_id =" + "'" + Department + "'";
if (Anatomy != "")
{
Select = Select + "AND body_part_examined =" + "'" + Anatomy + "'";
if (Start_Date != "")
{
Select = Select + " AND study_date =" + "'" + Start_Date + "'";
if (End_Date != "")
{
Select = Select + " AND study_date =" + "'" + End_Date + "'";
if (RFR != "")
{
Select = Select + " AND reject_category =" + "'" + RFR + "'";
if(Comment != "")
{
Select = Select + " AND reject_comment =" + "'" + Comment + "'";
}
}
}
}
}
}
else
{
Select = "SELECT * FROM tblReject_test";
}
//DataConnection connects to the database.
string connectiontring= "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\Database1.mdb";
DataConnection = new OleDbConnection(connectiontring);
//The DataAdapter is the code that ensures both the data in the Select and DataConnection strings match.
OleDbDataAdapter rdDataAdapter = new OleDbDataAdapter(Select, DataConnection);
try
{
//It then clears the datagridview and loads the data that has been selected from the DataAdapter.
database1DataSet.tblReject_test.Clear();
rdDataAdapter.Fill(this.database1DataSet.tblReject_test);
}
catch (OleDbException exc)
{
System.Windows.Forms.MessageBox.Show(exc.Message);
}
}
private void btnLoadChart_Click(object sender, EventArgs e)
{
try
{
int count = database1DataSet.Tables["tblReject_test"].Rows.Count;
DataConnection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = DataConnection;
string query = "SELECT * FROM tblReject_test";
command.CommandText = query;
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
charRejections.Series["RFR"].Points.AddXY(reader["reject_category"].ToString(), reader[count].ToString());
}
DataConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
}
}
Your code wouldn't compile as you are assigning a string to DataConnection (instance of OleDbConnection).
The correct usage should be as following.
string connectiontring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\Database1.mdb";
DataConnection = new OleDbConnection(connectiontring));
Also, your code doesn't close Database connection in case of exception.
It would be recommended to use the code as shown below. This is taken from MSDN
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
try
{
connection.Open();
Console.WriteLine("DataSource: {0} \nDatabase: {1}",
connection.DataSource, connection.Database);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
// The connection is automatically closed when the
// code exits the using block.
}
I have created an app linked to a local database. It works well, but the only problem is that after I press the insert button, data is inserted in db, but it is not showed in the GridView, only after I close and reopen the application. How can I make it show the data right after I press the button which inserts the values? Thanks !
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlServerCe;
using System.IO;
namespace Gradinita
{
public partial class Grupa : Form
{
string nume = "";
List<Label> labels = new List<Label>();
public Grupa(string nume)
{
InitializeComponent();
this.nume = nume;
}
private void Grupa_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'grupeDataSet8.copii' table. You can move, or remove it, as needed.
this.copiiTableAdapter2.Fill(this.grupeDataSet8.copii);
// TODO: This line of code loads data into the 'grupeDataSet7.copii' table. You can move, or remove it, as needed.
this.copiiTableAdapter1.Fill(this.grupeDataSet7.copii);
// TODO: This line of code loads data into the 'grupeDataSet3.copii' table. You can move, or remove it, as needed.
this.copiiTableAdapter.Fill(this.grupeDataSet3.copii);
var connString = (#"Data Source=" + System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)) + #"\Grupe.sdf");
using (var conn = new SqlCeConnection(connString))
{
try
{
conn.Open();
var query = "SELECT * FROM grupe WHERE Nume='" + nume + "'";
var command = new SqlCeCommand(query, conn);
var dataAdapter = new SqlCeDataAdapter(command);
var dataTable = new DataTable();
dataAdapter.Fill(dataTable);
label1.Text = dataTable.Rows[0][0].ToString();
label2.Text = dataTable.Rows[0][1].ToString();
label3.Text = dataTable.Rows[0][2].ToString();
label4.Text = dataTable.Rows[0][3].ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
private void button1_Click(object sender, EventArgs e)
{
if (checkBox1.Checked)
{
label5.Text = ("1");
}
if (checkBox2.Checked)
{
label5.Text = ("0");
}
textBox1.Text = (Convert.ToInt32(textBox5.Text) - Convert.ToInt32(textBox6.Text)).ToString();
var connString = (#"Data Source=" + Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName + #"\Grupe.sdf");
using (var conn = new SqlCeConnection(connString))
{
try
{
conn.Open();
var query = "INSERT INTO copii(prezenta, Nume, Prenume, Program, Taxa, Achitat, Diferenta) VALUES('" + label5.Text + "', '" + textBox2.Text.Trim() + "', '" + textBox3.Text.Trim() + "', '" + textBox4.Text.Trim() + "', '" + textBox5.Text.Trim() + "', '"+ textBox6.Text.Trim()+"', '"+ textBox1.Text.Trim() +"');";
MessageBox.Show(query);
var command = new SqlCeCommand(query, conn);
command.ExecuteNonQuery();
dataGridView1.Refresh(); //not working obviously
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}
You need to re-query the data and rebind the datatable.
Something like:
dataGridView1.DataSource = SomeDataTableSource;
dataGridView1.DataBind();
I managed to bypass this by re-adding the grid to the control. First, you copy the grid in a variable, then you remove it from the parent control, and then you add the variable to the controls of that control.
var grid = dataGridView1.Parent.Controls["dataGridView1"];
var ctr = dataGridView1.Parent;
ctr.Controls.Remove(dataGridView1);
ctr.Controls.Add(grid);
It's not tested and I might have mistaken some names cause i don't have a VS installed here, but you get the idea. Not the most elegant solution, but it worked for me. You can also try dataGridView1.Refresh() - which it didn't work for me.
I am trying to insert an Access table record with information from a combobox. I am using a winform and C#. I have simplified my project to just include the problem area. I am showing three methods with 4 controls (2 buttons and 2 comboboxes. The first method is connecting to an Access database and then showing a list of the tables and views in the first combobox. this method will also call the last method, SelectName() and fill the second combobox with field contents from a predetermined table from the selected database. The second method (buttonInsert_Click()) is where my problem lies. I would like the method to insert into one of the selected tables from combobox1 the selected item from combobox2 when the insert button is clicked. The only content I can get to insert into the selected table is
System.Data.DataRowView
The C# section of my project is below. Any suggestions are appreciated. Thank You.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
namespace DbApp
{
public partial class Form1 : Form
{
private char ch = '"';
private OleDbConnection dbConn;
private string sql = "";
public Form1()
{
InitializeComponent();
}
private void buttonConnect_Click(object sender, EventArgs e)
{
string connectionString = "";
string stringData = "";
openFileDialog1.Filter = "";
openFileDialog1.ShowDialog();
Text = openFileDialog1.FileName;
stringData = openFileDialog1.FileName;
connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + ch + Text + ch;
if (dbConn != null)
dbConn.Close();
dbConn = new OleDbConnection(connectionString);
dbConn.Open();
comboBox1.Items.Clear();
DataTable info = dbConn.GetSchema("Tables");
for (int x = 0; x < info.Rows.Count; ++x)
{
if ((info.Rows[x][3].ToString() == "TABLE") || (info.Rows[x][3].ToString() == "VIEW"))
{
comboBox1.Items.Add((object)info.Rows[x][2].ToString());
}
}
SelectName();
}
private void buttonInsert_Click(object sender, EventArgs e)
{
string name = this.comboBox2.SelectedItem.ToString();
try
{
dbConn = new OleDbConnection();
dbConn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + ch + openFileDialog1.FileName + ch;
dbConn.Open();
sql = "INSERT INTO " + this.comboBox1.SelectedItem.ToString() + " (Names)" +
"Values (#name)";
OleDbCommand myCommand = new OleDbCommand(sql, dbConn);
myCommand.Parameters.Add("#name", OleDbType.VarChar).Value = name;
myCommand.ExecuteNonQuery();
myCommand.Connection.Close();
}
catch (Exception err)
{
MessageBox.Show("Error: " + err.Message.ToString());
}
}
private void SelectName()
{
string strCon = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + ch + openFileDialog1.FileName + ch;
try
{
using (dbConn = new OleDbConnection(strCon))
{
dbConn.Open();
sql = "SELECT Name FROM Names";
OleDbDataAdapter adapter = new OleDbDataAdapter(new OleDbCommand(sql, dbConn));
DataSet ds = new DataSet();
adapter.Fill(ds, "Names");
comboBox2.Items.Clear();
this.comboBox2.DataSource = ds.Tables["Names"];
this.comboBox2.DisplayMember = "Name";
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message.ToString());
}
}
}
}
Try this:
string name = this.comboBox2.Text;
Below is the code I am working with to try to insert data into my 'ArticlesTBL' table. I also want to upload an image file to my computer.
I am getting an error reading: Incorrect syntax near 'UploadedUserFiles'.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;
public partial class _CopyOfSubmitArticle : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void uploadbutton_Click(object sender, EventArgs e)
{
string UpPath = Server.MapPath("~/UploadedUserFiles");
int imgSize = FileUpload1.PostedFile.ContentLength;
string imgName = FileUpload1.FileName;
string imgPath = "UploadedUserFiles/" + imgName;
if (FileUpload1.PostedFile.ContentLength > 1000000)
{
Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Alert", "alert('File is too big')", true);
}
else
{
FileUpload1.SaveAs(Server.MapPath(imgPath));
myinfo.Text = "file" + imgPath + "uploaded.";
}
String connectionString = WebConfigurationManager.ConnectionStrings["ConnectAntiFrack"].ConnectionString;
SqlConnection myConnection = new SqlConnection(connectionString);
myConnection.Open();
string ArticleImg = "UploadedUserFiles/" + FileUpload1.FileName;
string ArticleTitle = ArticleTitleTextBox.Text;
string ArticleContent = ArticleContentTextBox.Text;
string ArticleType = ArticleTypeDropdown.Text.ToString();
string ArticleAuthor = ArticleAuthorTextBox.Text.ToString();
string ArticleBrief = ArticleBriefTextBox.Text;
string ArticleDateTime = DateTime.Now.ToShortTimeString();
string query = "INSERT INTO ArticlesTBL (ArticleTitle, ArticleContent, ArticleType, ArticleImg, ArticleBrief, ArticleDateTime, ArticleAuthor, ArticlePublished, ArticleHomeDisplay, ArticleViews) VALUES (" + ArticleTitle +", " + ArticleContent +", "+ ArticleType +" " + ArticleImg +", "+ ArticleBrief +"," + ArticleDateTime + ", "+ ArticleAuthor +",'False', 'False', '0')";
SqlCommand myCommand = new SqlCommand(query, myConnection);
myCommand.ExecuteNonQuery();
// myinfo.Text = "connection to db is made";
myConnection.Close();
}
You should use parameters in your query to prevent attacks, like if someone entered '); drop table ArticlesTBL;--' as one of the values.
string query = "INSERT INTO ArticlesTBL (ArticleTitle, ArticleContent, ArticleType, ArticleImg, ArticleBrief, ArticleDateTime, ArticleAuthor, ArticlePublished, ArticleHomeDisplay, ArticleViews)";
query += " VALUES (#ArticleTitle, #ArticleContent, #ArticleType, #ArticleImg, #ArticleBrief, #ArticleDateTime, #ArticleAuthor, #ArticlePublished, #ArticleHomeDisplay, #ArticleViews)";
SqlCommand myCommand = new SqlCommand(query, myConnection);
myCommand.Parameters.AddWithValue("#ArticleTitle", ArticleTitleTextBox.Text);
myCommand.Parameters.AddWithValue("#ArticleContent", ArticleContentTextBox.Text);
// ... other parameters
myCommand.ExecuteNonQuery();
(xkcd)
using System;
using System.Data;
using System.Data.SqlClient;
namespace InsertingData
{
class sqlinsertdata
{
static void Main(string[] args)
{
try
{
SqlConnection conn = new SqlConnection("Data source=USER-PC; Database=Emp123;User Id=sa;Password=sa123");
conn.Open();
SqlCommand cmd = new SqlCommand("insert into <Table Name>values(1,'nagendra',10000);",conn);
cmd.ExecuteNonQuery();
Console.WriteLine("Inserting Data Successfully");
conn.Close();
}
catch(Exception e)
{
Console.WriteLine("Exception Occre while creating table:" + e.Message + "\t" + e.GetType());
}
Console.ReadKey();
}
}
}