Is there any easy way to save the items in listbox to the database.
I am using access database for windows form where user selects items from the combobox and adds it to the list box.
Now i want to add all the items in the listbox to the database separated with comma.
How can i perform this?
Here is the code for the class
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 Purchase_Management
{
public partial class Form1 : Form
{
string connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Amrit\\Desktop\\Database.accdb ;Persist Security Info=False;";
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
comboBox1.SelectedText = "Mr";
comboBox1.Items.Add("Mr");
comboBox1.Items.Add("Mrs");
comboBox1.Items.Add("Miss");
DataSet ds = GetAllItems();
comboBox2.DataSource = ds.Tables[0];
comboBox2.DisplayMember = "Product Name";
}
public DataSet GetAllItems()
{
DataSet dataSet = new DataSet();
// Create connection object
OleDbConnection oleConn = new OleDbConnection(connString);
try
{
oleConn.Open();
string sql = "SELECT [Product Name] FROM [Product]";
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(sql, oleConn);
dataAdapter.Fill(dataSet, "Product");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
oleConn.Close();
}
if (dataSet.Tables.Count <= 0)
return null;
else
return dataSet;
}
public string InsertUser(string custName, string title, string cust, string phoneNumber, string address1, string address2, string city, string postCode, string country, string itemPurchased)
{
// Create connection object
int ix = 0;
string rTurn = "";
OleDbConnection oleConn = new OleDbConnection(connString);
try
{
oleConn.Open();
string sql = "INSERT INTO [Customer]([Customer's Ebayname], [Title], [Customer's Name], [Phone Number], [Address 1], [Address 2], [City], [Post Code], [Country] , [Item Purchased])" +
"VALUES ( #custName, #title, #cust, #phoneNumber, #address1, #address2, #city, #postCode, #country , #itemPurchased)";
OleDbCommand oleComm = new OleDbCommand(sql, oleConn);
oleComm.Parameters.Add("#custName", OleDbType.Char).Value = custName;
oleComm.Parameters.Add("#title", OleDbType.Char).Value = title;
oleComm.Parameters.Add("#cust", OleDbType.Char).Value = cust;
oleComm.Parameters.Add("#phoneNumber", OleDbType.Char).Value = phoneNumber;
oleComm.Parameters.Add("#address1", OleDbType.Char).Value = address1;
oleComm.Parameters.Add("#address2", OleDbType.Char).Value = address2;
oleComm.Parameters.Add("#city", OleDbType.Char).Value = city;
oleComm.Parameters.Add("#postCode", OleDbType.Char).Value = postCode;
oleComm.Parameters.Add("#country", OleDbType.Char).Value = country;
oleComm.Parameters.Add("#itemPurchased", OleDbType.Char).Value = itemPurchased;
ix = oleComm.ExecuteNonQuery();
if (ix > 0)
rTurn = "User Added";
else
rTurn = "Insert Failed";
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
rTurn = ex.ToString();
}
finally
{
oleConn.Close();
}
return rTurn;
}
private void button1_Click(object sender, EventArgs e)
{
InsertUser(textBox1.Text, comboBox1.Text, textBox2.Text, textBox3.Text, textBox4.Text, textBox5.Text, textBox6.Text, textBox7.Text, textBox8.Text, comboBox2.Text);
if (MessageBox.Show("Customer Details Saved Successfuly") == DialogResult.OK)
{
Form1.ActiveForm.Close();
}
}
private void button2_Click(object sender, EventArgs e)
{
listBox1.Items.Add(comboBox2.Text);
}
private void button3_Click(object sender, EventArgs e)
{
if (this.listBox1.SelectedIndex >= 0)
this.listBox1.Items.RemoveAt(this.listBox1.SelectedIndex);
}
}
}
Step 1
Concatenate all the items in your ListBox. String.Join takes an array of string values, and returns a single String which concatenates them together. Consider using the ListBox.Items property which contains all the items you've added.
Step 2
Insert the string in whichever database you want. If you're reusing the "itemPurchased" column in your Product table you'll be able to use the string you've concatenated from Step 1 above.
Short of writing the entire code for you, I'm not sure what else we can do for you here.
Related
This is my first time attempting to read an Access database and write each row to the console. When I execute the application I get thrown an exception that says, "No value given for one or more required parameters" on the following statement:
OleDbDataReader reader = cmd.ExecuteReader();
I'm relatively new to c# programming and after hours of research, I can't figure out what I'm doing wrong. Here's my code:
private void maintenanceToolStripMenuItem_Click(object sender, EventArgs e)
{
//Use a variable to hold the SQL statement.
string inputString = "SELECT Full_Name, First_Name, Last_Name, Company FROM CONTACTS";
try
{
//Create an OleDbCommand object and pass in the SQL statement and OleDbConnection object
OleDbCommand cmd = new OleDbCommand(inputString, conn);
//Send the CommandText to the connection, and then build an OleDbDataReader.
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine("\t{0}\t{1}", reader.GetString(1));
reader.NextResult();
}
}
reader.Close();
}
catch (Exception ex)
{
error_message = ex.Message;
MessageBox.Show(error_message);
}
In response to the commenters, I'm posting a larger piece of code to eliminate any assumptions and give a better overall picture of what I'm trying to do:
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 AzFloodSquad
{
public partial class frm1DefaultScreen : Form
{
//Initialize the application
String conn_string = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source = C:\\Databases\\AzFloodSquad\\AzFloodSquad.accdb;Persist Security Info=False;";
OleDbConnection conn = null;
String error_message = "";
String q = "";
string varReportId = "";
public frm1DefaultScreen()
{
InitializeComponent();
}
//Load the default form
private void frm1DefaultScreen_Load(object sender, EventArgs e)
{
connectToolStripMenuItem.PerformClick();
contactsToolStripMenuItem.PerformClick();
}
//Exit the application
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
//Start the database
private void connectToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
conn = new OleDbConnection(conn_string);
conn.Open();
disconnectToolStripMenuItem.Enabled = true;
connectToolStripMenuItem.Enabled = false;
}
catch (Exception ex) { MessageBox.Show(ex.Message); }
}
//Stop the database
private void disconnectToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
conn.Close();
disconnectToolStripMenuItem.Enabled = false;
connectToolStripMenuItem.Enabled = true;
}
catch (Exception ex) { MessageBox.Show(ex.Message); }
}
//Clean up database whem form close button clicked
private void frm1DefaultScreen_FormClosing(object sender, FormClosingEventArgs e)
{
disconnectToolStripMenuItem.PerformClick();
}
private void contactsToolStripMenuItem_Click(object sender, EventArgs e)
{
varReportId = "Contacts";
q = "SELECT * " +
"FROM CONTACTS WHERE CONTACTS.CONTACT_TYPE = 'CUSTOMER' " +
"OR CONTACTS.CONTACT_TYPE = 'HOMEOWNER' OR CONTACTS.CONTACT_TYPE = 'HOME OWNER' " +
"OR CONTACTS.CONTACT_TYPE = 'TENANT'" +
"ORDER BY FULL_NAME";
this.Cursor = Cursors.WaitCursor;
run_Query_Parm(q);
this.Cursor = Cursors.Default;
}
//Pull data from the database using the parameter field
private void run_Query_Parm(String q)
{
error_message = "";
try
{
OleDbCommand cmd = new OleDbCommand(q, conn);
OleDbDataAdapter a = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
a.SelectCommand = cmd;
a.Fill(dt);
results.DataSource = dt;
results.AutoResizeColumns();
}
catch (Exception ex)
{
error_message = ex.Message;
MessageBox.Show(error_message);
}
}
//Clear all data from the screen
private void clearFormToolStripMenuItem_Click(object sender, EventArgs e)
{
varReportId = "";
if (this.results.DataSource != null)
{
this.results.DataSource = null;
}
else
{
this.results.Rows.Clear();
}
}
private void maintenanceToolStripMenuItem_Click(object sender, EventArgs e)
{
//Use a variable to hold the SQL statement.
string inputString = "SELECT Full_Name, First_Name, Last_Name, Company FROM CONTACTS";
try
{
//Create an OleDbCommand object and pass in the SQL statement and OleDbConnection object
OleDbCommand cmd = new OleDbCommand(inputString, conn);
//Send the CommandText to the connection, and then build an OleDbDataReader.
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine("\t{0}\t{1}", reader.GetString(1));
reader.NextResult();
}
}
reader.Close();
}
catch (Exception ex)
{
error_message = ex.Message;
MessageBox.Show(error_message);
}
}
Any help provided would be greatly appreciated. Thanks in advance.
I found the problem. Apparently, I had improper syntax on my SELECT statement. When I replaced my SELECT, (shown in the first code example I posted), with the following, it worked fine:
string inputString = "SELECT Contacts.[Account_Number], " +
"Contacts.[Full_Name], Contacts.[ID], Contacts.[Street], " +
"Contacts.[City], Contacts.[State], Contacts.[Zip] FROM Contacts";
I am trying to make something like a Bank Statement Application but i have a problem along the line.
Now it gets the datasource and all , but doesnt get the values from the Database and display on a report viewer. Apparently i am missing something , Hence i decided to bring it on here
Code Looks like this:
namespace TmpZ
{
public partial class BalanceSheet : Form
{
string constring = ConfigurationManager.ConnectionStrings["ConnData"].ConnectionString;
public BalanceSheet()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (accountNo1.Text == "")
{
MessageBox.Show("Please Enter Account Number");
}
else
{
DataTable dtb = new DataTable();
dtb = GenerateBankStatement(dtb);
reportViewer1.LocalReport.DataSources.Clear();
ReportDataSource rpd = new ReportDataSource("DataSet1", dtb);
reportViewer1.LocalReport.DataSources.Add(rpd);
reportViewer1.RefreshReport();
}
}
private DataTable GenerateBankStatement(DataTable dt)
{
using (SqlConnection cn = new SqlConnection(constring))
{
try
{
SqlDataAdapter da = new SqlDataAdapter("SELECT [id] as id, [transaction_desc] as transaction_desc,[credit] as credit, [debit] as debit, [balance] as balance, [transaction_date] as transaction_date FROM transactions WHERE(accountNo1 = '" + accountNo1.Text + "') AND(transaction_date BETWEEN '" + dateFrom.Text + "' AND '" + dateTo.Text + "')", cn);
da.Fill(dt);
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
return dt;
}
}
}
What am I missing? it shows empty data on Boxes in reportviewer.
Ok i finally fixed it. It was an issue with the Date Formatting. I had to make them strings and the code Works Fine at this point. Code now looks like this for those that want to work on something like this Much later
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Reporting.WinForms;
namespace TwpZ
{
public partial class BalanceSheet : Form
{
string constring = ConfigurationManager.ConnectionStrings["ConnData"].ConnectionString;
public BalanceSheet()
{
InitializeComponent();
}
private void BalanceSheet_Load(object sender, EventArgs e)
{
}
private void reportViewer1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
if (accountNo1.Text == "")
{
MessageBox.Show("Please Enter Account Number");
}
else
{
DataTable dtb = new DataTable();
dtb = GenerateBankStatement(dtb);
reportViewer1.LocalReport.DataSources.Clear();
ReportDataSource rpd = new ReportDataSource("DataSet1", dtb);
reportViewer1.LocalReport.DataSources.Add(rpd);
reportViewer1.RefreshReport();
}
}
private DataTable GenerateBankStatement(DataTable dt)
{
using (SqlConnection cn = new SqlConnection(constring))
{
try
{
string dateF = Convert.ToDateTime(dateFrom.Text).ToString("dd-MM-yyyy");
string dateT = Convert.ToDateTime(dateTo.Text).ToString("dd-MM-yyyy");
SqlDataAdapter da = new SqlDataAdapter("SELECT [id] as id, [transaction_desc] as transaction_desc,[credit] as credit, [debit] as debit, [balance] as balance, [transaction_date] as transaction_date FROM transactions WHERE(accountNo1 = '" + accountNo1.Text + "') AND(transaction_date BETWEEN '" + dateF + "' AND '" + dateT + "')", cn);
//SqlDataAdapter da = new SqlDataAdapter("SELECT [id] as id, [transaction_desc] as transaction_desc,[credit] as credit, [debit] as debit, [balance] as balance, [transaction_date] as transaction_date FROM transactions WHERE(accountNo1 = '" + accountNo1.Text + "')", cn);
da.Fill(dt);
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
return dt;
}
}
}
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;
I do have a problem in checking username and password in my registration form. When I tend to register the same username and password that's is already in my database(Access), still it allows to register. I just wanna trap it however, I don't know how to that.
What I want to output is that, I want a trap that says "Account Exists, Try Again!" or "Username Exists!"
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.Text.RegularExpressions;
namespace Login { public partial class Register : Form {
private OleDbConnection personalConn;
private OleDbCommand oleDbCmd = new OleDbCommand();
private String connParam = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\Majel\Tic Tac Toe\Database\data.accdb";
public Register()
{
personalConn = new OleDbConnection(connParam);
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
personalConn.Open();
oleDbCmd.Connection = personalConn;
if (textBox1.Text != "" && textBox2.Text != "")
{
int temp;
oleDbCmd.CommandText = "INSERT INTO data(Users,Pass) Values('" + this.textBox1.Text.ToString() + "','" + this.textBox2.Text + "');";
temp = oleDbCmd.ExecuteNonQuery();
if (temp > 0)
{
textBox1.Text = null;
textBox2.Text = null;
MessageBox.Show("Registration Success!");
this.Hide();
Form1 frm = new Form1();
frm.Show();
}
personalConn.Close();
}
}
catch (Exception)
{
MessageBox.Show("Invalid!, Duplicate Data.");
}
}
Notes: textBox1= username
textBox2= password Your attention is much highly appreciated. Thank you so much in advance.
Here is code which uses oledbcommand parameters using ? placeholder as mentioned in MSDN Reference. Also I have added using block which should Close opened connection implicitly.
using(OleDbConnection con = new OleDbConnection(connParam))
using(OleDbCommand cmd = new OleDbCommand("select count(*) from data where Users = ?"))
{
con.Open();
cmd.Connection = con;
cmd.Parameters.AddWithValue("#UserName", textBox1.Text);
object objRes = cmd.ExecuteScalar();
if (objRes == null || (int)objRes == 0)
{
cmd.Parameters.Clear();
cmd.CommandText = "INSERT INTO data (Users,Pass) values(?, ?);";
cmd.Parameters.AddWithValue("#Users", textBox1.Text);
cmd.Parameters.AddWithValue("#Pass", textBox2.Text);
int iRes = cmd.ExecuteNonQuery();
if(iRes > 0)
MessageBox.Show("Registration Success!");
}
else
errorProvider2.SetError(textBox1, "This username has been using by another user.");
}
You almost never use data (in this case, a username) as the primary key for a record in a database. Chance are, your access database is set up the same way.
This means that there is nothing at the DBMS layer that will stop this from occurring, short of making the username the primary key (not recommended).
The solution is to perform a SELECT query to get the count of records with that username, and only allow the insert if the count is 0. You might be able to write a trigger to do this for you, and make the DBMS "reject" the insert, but given your (apparent) level with databases, I wouldn't try that at this point.
To get the count:
SELECT Count(*) FROM Users WHERE userName=#userName
A paramaterized query here is crucial to protect against SQL injection.
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.Text.RegularExpressions;
namespace Login
{
public partial class Register : Form
{
public Register()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
if(text1Box1.Text == "" || textBox2.Text == "")
{
MessageBox.Show("Mandatory fields password or user is empty");
retrun; //I'm not sure if this return is need. Remove it if MessageBox "breaks" the execution of the code below.
}
OleDbCommand cmd = new OleDbCommand(#"Select * from Data where User=#User");
cmd.Parameters.AddWithValue("#User", textBox1.Text);
DataSet dst = SqlManager.GetDataSet(cmd, "Data");
if(dst.Tables[0].Rows > 0)
{
MessageBox.Show("User already exist");
return; //again i'm not sure that this return is needed.
}
Insert("Data", "User", textBox1.Text, "Pass", textBox2.Text);
textBox1.Text = null;
textBox2.Text = null;
MessageBox.Show("Registration Success!");
this.Hide();
Form1 frm = new Form1();
frm.Show();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
You need 1 class make it SqlManager.
public class SqlManager
{
private String connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\Majel\Tic Tac Toe\Database\data.accdb";
public static GetOleDbConnection(OleDbCommand cmd)
{
if(cmd.Connection == null)
{
OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();
cmd.Connection = conn;
return conn;
}
return cmd.Connection;
}
public static int ExecuteNonQuery(SqlCommand cmd)
{
OleDbConnection conn = GetSqlConnection(cmd);
try
{
return cmd.ExecuteNonQuery();
}
catch
{
throw;
}
finally
{
conn.Close();
}
}
public static DataSet GetDataSet(SqlCommand cmd)
{
return GetDataSet(cmd, "Table");
}
public static DataSet GetDataSet(SqlCommand cmd, string defaultTable)
{
OleDbConnection conn = GetSqlConnection(cmd);
try
{
DataSet resultDst = new DataSet();
using (OleDbDataAdapter adapter = new OleDbDataAdapter(cmd))
{
adapter.Fill(resultDst, defaultTable);
}
return resultDst;
}
catch
{
throw;
}
finally
{
conn.Close();
}
}
}
Here is another method you can put in the form class:
public virtual void Insert(string TableName, params object[] colValues)
{
if (colValues == null || colValues.Length % 2 != 0)
throw new ArgumentException("Invalid column values passed in. Expects pairs (ColumnName, ColumnValue).");
OleDbCommand cmd = new OleDbCommand("INSERT INTO " + TableName + " ( {0} ) VALUES ( {1} )");
string insertCols = string.Empty;
string insertParams = string.Empty;
for (int i = 0; i < colValues.Length; i += 2)
{
string separator = ", ";
if (i == colValues.Length - 2)
separator = "";
string param = "#P" + i;
insertCols += colValues[i] + separator;
insertParams += param + separator;
cmd.Parameters.AddWithValue(param, colValues[i + 1]);
}
cmd.CommandText = string.Format(cmd.CommandText, insertCols, insertParams);
DA.SqlManager.ExecuteNonQuery(cmd);
}
Like other guys tell you use parameters in this case you will avoid sql injection. Read in wikipedia about it. Also I add some structure for your program, it is not perfect but I should write a lot for more. It is possible to have some typos here, because I wrote the code here. How you make the check, you fetch the data from database for the user which you write in textbox1.Text. If the dataSet have rows that means at the moment there is existing user with this name. If you don't know what is data set read System.Data.
You should learn to write data access in other classes !
Try this with your Existing Code :
oleDbCmd.CommandText = "INSERT INTO data(Users,Pass) Values('" + this.textBox1.Text.ToString() + "','" + this.textBox2.Text + "') SELECT '" + this.textBox1.Text.ToString() + "','" + this.textBox2.Text + "' WHERE NOT EXISTS(SELECT Users,Pass FROM data WHERE Users='" + this.textBox1.Text.ToString() +"');";
temp = oleDbCmd.ExecuteNonQuery();
if (temp > 0)
{
textBox1.Text = null;
textBox2.Text = null;
MessageBox.Show("Registration Success!");
this.Hide();
Form1 frm = new Form1();
frm.Show();
}
else
{
MessageBox.Show("Username is already Present !!!");
}
It returns 0 if the username is already present in data.
the code works to a certain extent when I export the data to excel it works fine but if I go back into the application and add, delete or update any of the datagrid when I export the data again it doesn't export the changes. I have deleted the original csv file in case it was an overwriting problem but still get the same problem.
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.SqlClient;
using System.IO;
namespace WindowsFormsApplication1
{
public partial class FormAccounts : Form
{
String constring = #"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\kenny\Documents\Visual Studio 2010\Projects\Cegees 181013\WindowsFormsApplication1\WindowsFormsApplication1\Accounts.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
//String cmdselect = #"select * Accounts";
String cmdupdate = #"update Accounts set date = #date, moneyin = #moneyin, retailin = #retailin, rent = #rent, stock = #stock, transport = #transport, misc = #misc, bills = #bills, comments = #comments where ID = #id";
String cmdinsert = #"insert into Accounts (date, moneyin, retailin, rent, stock, transport, misc, bills, comments) values (#date, #moneyin, #retailin, #rent, #stock, #transport, #misc, #bills, #comments )";
String cmddelete = #"delete from Accounts where ID =#ID";
public FormAccounts()
{
InitializeComponent();
}
private void FormAccounts_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'accountsDataSet.Accounts' table. You can move, or remove it, as needed.
this.accountsTableAdapter.Fill(this.accountsDataSet.Accounts);
}
private void btnAdd_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(constring);
SqlDataAdapter da = new SqlDataAdapter();
da.InsertCommand = new SqlCommand(cmdinsert, con);
try
{
da.InsertCommand.Parameters.Add("#date", SqlDbType.Date);
da.InsertCommand.Parameters["#date"].Value = dtpaccs.Value;
da.InsertCommand.Parameters.Add("#moneyin", SqlDbType.Decimal);
da.InsertCommand.Parameters["#moneyin"].Value = textmoneyin.Text ;
da.InsertCommand.Parameters.Add("#retailin", SqlDbType.Decimal);
da.InsertCommand.Parameters["#retailin"].Value = textretailin.Text;
da.InsertCommand.Parameters.Add("#rent", SqlDbType.Decimal);
da.InsertCommand.Parameters["#rent"].Value = textrent.Text;
da.InsertCommand.Parameters.Add("#stock", SqlDbType.Decimal);
da.InsertCommand.Parameters["#stock"].Value = textstock.Text;
da.InsertCommand.Parameters.Add("#transport", SqlDbType.Decimal);
da.InsertCommand.Parameters["#transport"].Value = texttransport.Text;
da.InsertCommand.Parameters.Add("#misc", SqlDbType.Decimal);
da.InsertCommand.Parameters["#misc"].Value = textmisc.Text;
da.InsertCommand.Parameters.Add("#bills", SqlDbType.Decimal);
da.InsertCommand.Parameters["#bills"].Value = textbills.Text;
da.InsertCommand.Parameters.Add("#comments", SqlDbType.VarChar);
da.InsertCommand.Parameters["#comments"].Value = textcomments.Text;
con.Open();
da.InsertCommand.ExecuteNonQuery();
MessageBox.Show("Data Added");
con.Close();
cleartexts();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
string date = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
string id = dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString();
lbldate.Text = date;
lblID.Text = id;
dtpaccs.Value = Convert.ToDateTime(date);
textmoneyin.Text = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();
textretailin.Text = dataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString();
textrent.Text = dataGridView1.Rows[e.RowIndex].Cells[4].Value.ToString();
textstock.Text = dataGridView1.Rows[e.RowIndex].Cells[5].Value.ToString();
texttransport.Text = dataGridView1.Rows[e.RowIndex].Cells[6].Value.ToString();
textmisc.Text = dataGridView1.Rows[e.RowIndex].Cells[7].Value.ToString();
textbills.Text = dataGridView1.Rows[e.RowIndex].Cells[8].Value.ToString();
textcomments.Text = dataGridView1.Rows[e.RowIndex].Cells[9].Value.ToString();
}
private void btnEdit_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(constring);
SqlDataAdapter da = new SqlDataAdapter();
da.UpdateCommand = new SqlCommand(cmdupdate, con);
try
{
da.UpdateCommand.Parameters.Add("#ID", SqlDbType.Int).Value = lblID.Text;
da.UpdateCommand.Parameters.Add("#date", SqlDbType.Date).Value = lbldate.Text;
da.UpdateCommand.Parameters.Add("#moneyin", SqlDbType.Decimal).Value = textmoneyin.Text;
da.UpdateCommand.Parameters.Add("#retailin", SqlDbType.Decimal).Value = textretailin.Text;
da.UpdateCommand.Parameters.Add("#rent", SqlDbType.Decimal).Value = textrent.Text;
da.UpdateCommand.Parameters.Add("#stock", SqlDbType.Decimal).Value = textstock.Text;
da.UpdateCommand.Parameters.Add("#transport", SqlDbType.Decimal).Value = texttransport.Text;
da.UpdateCommand.Parameters.Add("#misc", SqlDbType.Decimal).Value = textmisc.Text;
da.UpdateCommand.Parameters.Add("#bills", SqlDbType.Decimal).Value = textbills.Text;
da.UpdateCommand.Parameters.Add("#comments", SqlDbType.VarChar).Value = textcomments.Text;
con.Open();
da.UpdateCommand.ExecuteNonQuery();
MessageBox.Show("Accounts Updated");
con.Close();
cleartexts();
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void btnDelete_Click(object sender, EventArgs e)
{
var rindex = dataGridView1.SelectedCells[0].RowIndex;
SqlConnection con = new SqlConnection(constring);
SqlDataAdapter da = new SqlDataAdapter();
da.DeleteCommand = new SqlCommand(cmddelete, con);
try
{
DialogResult dr;
dr = MessageBox.Show("Are you sure you want to delete this record", "Confirmation", MessageBoxButtons.YesNo);
if (dr == DialogResult.Yes)
{
da.DeleteCommand.Parameters.Add("#ID", SqlDbType.Int).Value = accountsDataSet.Accounts[rindex].ID;
con.Open();
da.DeleteCommand.ExecuteNonQuery();
MessageBox.Show("Record Deleted");
con.Close();
cleartexts();
}
else
{
MessageBox.Show("Delete Cancelled");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
public void cleartexts()
{
//Clears textboxes
textmoneyin.Text = "";
textretailin.Text ="";
textrent.Text = "";
textstock.Text = "";
texttransport.Text = "";
textmisc.Text = "";
textbills.Text = "";
textcomments.Text = "";
}
private void exportToolStripMenuItem_Click(object sender, EventArgs e)
{
int cols;
string directory = #"C:\Users\kenny\Documents\Visual Studio 2010\Projects\Cegees 181013\WindowsFormsApplication1\WindowsFormsApplication1\Excel Exports";
string filename = string.Format("{0:dd-MM-yy}__{1}.csv", DateTime.Now, "Accounts");
string path = Path.Combine(directory, filename);
//open file
using (StreamWriter wr = File.CreateText(path))
{
//determine the number of cols and write to file
cols = dataGridView1.Columns.Count;
for (int i = 0; i < cols; i++)
{
wr.Write(dataGridView1.Columns[i].Name.ToString().ToUpper() + ",");
}
wr.WriteLine();
//write rows to excel
for (int i = 0; i < (dataGridView1.Rows.Count - 1); i++)
{
for (int j = 0; j < cols; j++)
{
if (dataGridView1.Rows[i].Cells[j].Value != null)
{
wr.Write(dataGridView1.Rows[i].Cells[j].Value + ",");
}
else
{
wr.Write(",");
}
}
wr.WriteLine();
}
wr.Close();
MessageBox.Show("Operation Complete " +path);
}
}
}
}
Found the problem. The application needs to be shut down and restarted for the new data to copy over. Is there a way to do that once the datagrid has been changed / updated?