hello every i was trying to create simple student form n add the data to the database but coudlnt do this, there was no error during the execution of the program, application executes nicely but no changes in the table, n the values are nt inserted into the table, what might b the problem plz suggest me, im writing my code below..
thanq in advance :)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
namespace School.Project
{
class Student
{
public static string constr = System.Configuration.ConfigurationManager.ConnectionStrings"SchoolConnectionString"].ConnectionString;
public static int AddStudent(string title, string fname, string lname, string fathername, string gender, string clas, string sec, int age, string dob, string religion, string caste, string image, string address, string homeno, string cell, string email)
{
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlTransaction t = con.BeginTransaction();
SqlCommand cmd = new SqlCommand("INSERT INTO Student (Title,FirstName,LastName,FatherName,Gender,Class,Section,Age,DateOfBirth,Religion,Caste,Image,Address,HomePhone,CellPhone,Email) VALUES(#Title,#FirstName,#LastName,#FatherName,#Gender,#Class,#Section,#Age,#DateOFBirth,#Religion,#Caste,#Image,#Address,#HomePhone,#CellPhone,#Email)",con);
cmd.Parameters.AddWithValue("#Title", title);
cmd.Parameters.AddWithValue("FirstName", fname);
cmd.Parameters.AddWithValue("LastName", lname);
cmd.Parameters.AddWithValue("#FatherName", fathername);
cmd.Parameters.AddWithValue("#Gender", gender);
cmd.Parameters.AddWithValue("#Class", clas);
cmd.Parameters.AddWithValue("#Section", sec);
cmd.Parameters.AddWithValue("Age", age);
cmd.Parameters.AddWithValue("DateOfBirth", dob);
cmd.Parameters.AddWithValue("#Religion", religion);
cmd.Parameters.AddWithValue("Caste", caste);
cmd.Parameters.AddWithValue("Image", image);
cmd.Parameters.AddWithValue("Address", address);
cmd.Parameters.AddWithValue("#HomePhone", homeno);
cmd.Parameters.AddWithValue("#CellPhone", cell);
cmd.Parameters.AddWithValue("#Email", email);
cmd.Transaction = t;
int i = cmd.ExecuteNonQuery();
t.Commit();
con.Close();
return i;
}
private void btSave_Click(object sender, EventArgs e)
{
string title = cbTitle.SelectedItem.ToString();
string fname = txtfname.Text;
string lname = txtlname.Text;
string fathername = txtfatherName.Text;
string gender = cbGender.SelectedItem.ToString();
string clas = cbClass.SelectedItem.ToString();
string section = cbSection.SelectedItem.ToString();
int age = int.Parse(txtAge.Text);
string dob = txtdob.Text;
string religion = txtReligion.Text;
string caste = txtCaste.Text;
string imagepath = txtpath.Text;
string address = txtAddress.Text;
string homeno = txtHome.Text;
string cell = txtCell.Text;
string email = txtEMail.Text;
int i = Project.Student.AddStudent(title, fname, lname, fathername, gender, clas, section, age, dob, religion, caste, imagepath, address, homeno, cell, email);
if (i == 1)
{
MessageBox.Show("Student Added Succesfully, Thanq", "Inserted", MessageBoxButtons.OK, MessageBoxIcon.Information);
ClearAll();
}
else
{
MessageBox.Show("Couldnt enter the data", "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
add a bracket [ ] on some fields of your query because some of the are reserved words:
SqlCommand cmd = new SqlCommand("
INSERT INTO Student ([Title],FirstName,LastName,
FatherName,Gender,
[Class],Section,Age,DateOfBirth,
Religion,Caste,[Image],Address,
HomePhone,CellPhone,Email)
VALUES(#Title,#FirstName,#LastName,
#FatherName,#Gender,#Class,#Section,
#Age,#DateOFBirth,#Religion,#Caste,
#Image,#Address,#HomePhone,
#CellPhone,#Email)",con);
[Title]
[Image]
UPDATED 1
Instead of SqlTransaction t = con.BeginTransaction();
try this:
SqlTransaction t = con.BeginTransaction(IsolationLevel.ReadCommitted)
Source: Use database transactions
Some of your parameters contain the "#" symbol and some don't....
1.) don't pass so many parameters. You want to add a STUDENT, that should ring all your bells. Pass only one parameter - class Student populated with the values you want.
2.) I don't think a transaction is necessary here. You want to push only one object, so if it fails, the result is the same - no changes done.
3.) as Daren said, you don't have properly written parameters in your query
EDIT:
Just tried the simplified version and it works like a charm... Here's the code:
Page.aspx.cs
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
btn.Click += new EventHandler(btn_Click);
}
void btn_Click(object sender, EventArgs e)
{
Student student = new Student() { Id = 1, Name = "John" };
int rowsAffected = Student.AddStudent(student);
Response.Write(rowsAffected);
}
}
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public static int AddStudent(Student s)
{
string conString = System.Configuration.ConfigurationManager.ConnectionStrings["string1"].ConnectionString;
using (SqlConnection con = new SqlConnection(conString))
{
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO Students (Name) VALUES (#Name)", con);
cmd.Parameters.AddWithValue("#Name", s.Name);
return cmd.ExecuteNonQuery();
}
}
}
Please, try to modify it to suit your needs and let me know, if it finally works. It has some problems (like not putting the class Student in a separate file), but I hope you get the idea.
Related
This is my code in C#. I am just trying to add data to my table in the database. However, I have been having this issue for only ages. It says:
invalid column name.
Fotograf database is the only database I have and table ODEV1 is the only table I created. When I edit data through SQL Server there is not an issue, but when I try it by using Visual Studio C# I have issues.
Any help appreciated thank you!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
namespace SQL_ORNEK2
{
class Program
{
static void Main(string[] args)
{
SqlConnection baglanti = new SqlConnection();
baglanti.ConnectionString = "Server=LAPTOP-K3JLTUR0; database=Fotograf; integrated security=True";
SqlCommand komut = new SqlCommand();
komut.Connection = baglanti;
string name;
name = Console.ReadLine().ToString();
string surname;
surname = Console.ReadLine().ToString();
int age;
age = Convert.ToInt32(Console.ReadLine());
string job;
job = Console.ReadLine().ToString();
komut.CommandText = "INSERT INTO dbo.ODEV1 VALUES('name', 'surname', age, 'job')";
baglanti.Open();
int sonuc = komut.ExecuteNonQuery();
Console.WriteLine(sonuc);
Console.ReadKey();
baglanti.Close();
}
}
}
Your insert statement is incorrect. You're using the list of columns in place of the values to insert. It should look something like this:
insert into dbo.ODEV1 (name, surname, age, job) values ('Harold', 'Green', 25, 'nerd')
To insert the actual data from the variables you read from user input, you'll want to use SQL parameters:
komut.Parameters.AddWithValue("#name", name);
komut.Parameters.AddWithValue("#surname", surname);
komut.Parameters.AddWithValue("#age", age);
komut.Parameters.AddWithValue("#job", job);
komut.CommandText = "insert into dbo.ODEV1 (name, surname, age, job) values (#name, #surname, #age, #job)";
If you use SSMS (SQL-Server Management Studio which is free) to create your INSERT INTO statement by right clicking the desired table, select "script table as", select "INSERT To" to a new query window we get this (using a table named Customers).
INSERT INTO [dbo].[Customer]
([FirstName]
,[LastName]
,[Address]
,[City]
,[State]
,[ZipCode]
,[AccountNumber]
,[JoinDate])
VALUES
(<FirstName, nvarchar(max),>
,<LastName, nvarchar(max),>
,<Address, nvarchar(max),>
,<City, nvarchar(max),>
,<State, nvarchar(max),>
,<ZipCode, nvarchar(max),>
,<AccountNumber, nvarchar(max),>
,<JoinDate, datetime2(7),>)
Now change the VALUES section by using a DECLARE for each value.
DECLARE #FirstName nvarchar(max)
DECLARE #LastName nvarchar(max)
DECLARE #Address nvarchar(max)
DECLARE #City nvarchar(max)
DECLARE #State nvarchar(max)
DECLARE #ZipCode nvarchar(max)
INSERT INTO Customer (FirstName,LastName,[Address],City,[State],ZipCode) VALUES (#FirstName,#LastName,#Address,#City,#State,#ZipCode)
Next, create a class rather than placing data operations into Program.cs with a method specific to adding a new record (the following still uses Customers table).
Full source where the following code comes from.
An alternate to cmd.Parameters.AddWithValue is cmd.Parameters.Add which provides fine tuning the type of the parameter.
The alternate to getting the new primary key if needed is to add a semi-colon to the end of the INSERT INTO and adding SELECT CAST(scope_identity() AS int); then use Convert.ToInt32(cmd.ExecuteScalar()) to get the new key.
So after testing with SSMS simply paste the query into a string variable and if this does not work there is something else going on.
public bool AddCustomer(string FirstName, string LastName, string Address, string City, string State, string ZipCode, ref int NewPrimaryKeyValue)
{
bool success = false;
using (var cn = new SqlConnection { ConnectionString = ConnectionString })
{
using (var cmd = new SqlCommand { Connection = cn })
{
cmd.CommandText =
"INSERT INTO Customer (FirstName,LastName,[Address],City,[State],ZipCode) " +
"VALUES (#FirstName,#LastName,#Address,#City,#State,#ZipCode)";
try
{
cmd.Parameters.AddWithValue("#FirstName", FirstName);
cmd.Parameters.AddWithValue("#LastName", LastName);
cmd.Parameters.AddWithValue("#Address", Address);
cmd.Parameters.AddWithValue("#City", City);
cmd.Parameters.AddWithValue("#State", State);
cmd.Parameters.AddWithValue("#ZipCode", ZipCode);
cn.Open();
int result = cmd.ExecuteNonQuery();
if (result == 1)
{
cmd.CommandText = "Select ##Identity";
NewPrimaryKeyValue = Convert.ToInt32(cmd.ExecuteScalar());
success = true;
}
}
catch (Exception ex)
{
HasErrors = true;
ExceptionMessage = ex.Message;
NewPrimaryKeyValue = -1;
success = false;
}
}
}
return success;
}
Calling the above method.
You can also validate column names using the following (still keeping with Customer table)
SELECT ORDINAL_POSITION,
COLUMN_NAME,
DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'Customer'
AND TABLE_SCHEMA = 'dbo';
Results
1,id,int
2,FirstName,nvarchar
3,LastName,nvarchar
4,Address,nvarchar
5,City,nvarchar
6,State,nvarchar
7,ZipCode,nvarchar
8,AccountNumber,nvarchar
9,JoinDate,datetime2
Edit
Another option is to create a class which represents data to be inserted e.g.
public class Customer
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string State { get; set; }
public string ZipCode { get; set; }
public string AccountNumber { get; set; }
public DateTime? JoinDate { get; set; }
}
Then here we use the values passed. Note, in this version cmd.Parameters.AddWithValue is replaced with cmd.Parameters.Add and the query to get the new primary key is appended after the INSERT INTO separated by a semi-colon.
To call create an instance of the Customer class, populate properties and call the method.
public bool AddCustomer(Customer customer)
{
bool success = false;
using (var cn = new SqlConnection { ConnectionString = ConnectionString })
{
using (var cmd = new SqlCommand { Connection = cn })
{
cmd.CommandText =
"INSERT INTO Customer (FirstName,LastName,[Address],City,[State],ZipCode) " + // insert
"VALUES (#FirstName,#LastName,#Address,#City,#State,#ZipCode);" + // insert
"SELECT CAST(scope_identity() AS int);"; // get new primary key
try
{
cmd.Parameters.Add(new SqlParameter("#FirstName", SqlDbType.NVarChar))
.Value = customer.FirstName;
cmd.Parameters.Add(new SqlParameter("#LastName", SqlDbType.NVarChar))
.Value = customer.LastName;
cmd.Parameters.Add(new SqlParameter("#Address", SqlDbType.NVarChar))
.Value = customer.Address;
cmd.Parameters.Add(new SqlParameter("#City", SqlDbType.NVarChar))
.Value = customer.City;
cmd.Parameters.Add(new SqlParameter("#State", SqlDbType.NVarChar))
.Value = customer.State;
cmd.Parameters.Add(new SqlParameter("#ZipCode", SqlDbType.NVarChar))
.Value = customer.ZipCode;
cn.Open();
customer.Id = Convert.ToInt32(cmd.ExecuteScalar());
success = true;
}
catch (Exception ex)
{
HasErrors = true;
ExceptionMessage = ex.Message;
customer.Id = -1;
success = false;
}
}
}
return success;
}
Below these code I'm getting the wrong output in incrementing the string value in my Database column "SupplierID". I'm transferring the string value to my lbl_id in ADDSupplier Form and That's what i used to insert value to my "SupplierID".
Desired Output:
SPPL-0001
SPPL-0002
SPPL-0003
etc
Currently Output (Below these code):
SPPL-0001
SPPL-00012
SPPL-00013
etc
NOTE: When i repeat inserting data i get the currently output that i stated above but when i restart the program and the last inserted value, For example is SPPL-00013. When i open my adding form, lbl_id display the id as SPPL-0004. If i continue, it become SPPL-00045.
PS: SupplierID is varchar(50) in my database and also PRIMARY_KEY
These image shows the wrong output of mine
What i want to get help with is to correct my logic and get that desired output. Please help me. Thank you
public partial class SIMSSupplier : UserControl
{
ADDSupplier supply;
public SIMSSupplier()
{
InitializeComponent();
}
public string ID = "SPPL-000";
public void GenerateAutoID()
{
using (var con = SQLConnection.GetConnection())
{
using (var select = new SqlCommand("Select Count(SupplierID) from admin_supplier", con))
{
int i = Convert.ToInt32(select.ExecuteScalar());
i++;
supply.lbl_id.Text = ID + i.ToString();
}
}
}
private void btn_register_Click(object sender, EventArgs e)
{
supply = new ADDSupplier(this);
supply.Show();
GenerateAutoID();
}
}
public partial class ADDSupplier : MetroForm
{
SIMSSupplier _view;
public ADDSupplier(SIMSSupplier _view)
{
InitializeComponent();
this._view = _view;
}
string date = DateTime.Now.ToString("MMMM-dd-yyyy");
private void btn_ok_Click(object sender, EventArgs e)
{
_view.ID = lbl_id.Text;
using (var con = SQLConnection.GetConnection())
{
if (string.IsNullOrEmpty(txt_name.Text) || string.IsNullOrEmpty(txt_contact.Text) || string.IsNullOrEmpty(cbox_remark.Text) || string.IsNullOrEmpty(txt_address.Text))
{
CustomNotifcation.Show("Please input the required fields", CustomNotifcation.AlertType.warning);
}
else
{
using (var select = new SqlCommand("Insert into admin_supplier (SupplierID, Companyname, Contactnumber, Date, Remarks, Address) Values (#SupplierID, #Companyname, #Contactnumber, #Date, #Remarks, #Address)", con))
{
select.Parameters.Add("#SupplierID", SqlDbType.VarChar).Value = lbl_id.Text;
select.Parameters.Add("#Companyname", SqlDbType.VarChar).Value = txt_name.Text;
select.Parameters.Add("#Contactnumber", SqlDbType.VarChar).Value = txt_contact.Text;
select.Parameters.Add("#Date", SqlDbType.VarChar).Value = date;
select.Parameters.Add("#Remarks", SqlDbType.VarChar).Value = cbox_remark.Text;
select.Parameters.Add("#Address", SqlDbType.VarChar).Value = txt_address.Text;
select.ExecuteNonQuery();
CustomMessage.Show("Message: Supplier successfully added!", CustomMessage.Messagetype.Success2);
_view._Supplier();
}
}
}
}
}
You just need to use a format string instead:
string ID = "SPPL-"
supply.lbl_id.Text = ID + i.ToString("0000");
Which will result in the format being applied correctly. Right now you are appending the i variable to the ID, which is already SPPL-000, so the next one becomes SPPL-0001, etc.
using System.Windows.Forms;
using System.Configuration;
using System.Data.SqlClient;
namespace WindowsFormsApplication1
{
public partial class Form4 : Form
{
String connectionString;
SqlConnection connection;
public Form4()
{
InitializeComponent();
connectionString = ConfigurationManager.ConnectionStrings["WindowsFormsApplication1.Properties.Settings.Database1ConnectionString"].ConnectionString;
}
private void button1_Click(object sender, EventArgs e)
{
addStudent();
}
void addStudent()
{
using (connection = new SqlConnection(connectionString))
using (SqlCommand first = connection.CreateCommand())
{
string idNum = textBox1.Text;
string lname = textBox2.Text;
string fname = textBox3.Text;
string course = comboBox1.Text;
The query for inserting values from textbox didn't work
first.CommandText="INSERT INTO Students (idNo, fName, lName, course) VALUES (#idNum, #fname, #lname, #course)";
first.Parameters.AddWithValue("#idNum", idNum);
first.Parameters.AddWithValue("#fname", fname);
first.Parameters.AddWithValue("#lname", lname);
first.Parameters.AddWithValue("#course", course);
try
{
connection.Open();
first.ExecuteNonQuery();
}
catch (SqlException e)
{
MessageBox.Show(e.Message.ToString(), "Error Message");
}
There is no error when I click the button, but if I click it again, I get an error:
Violation of PRIMARY KEY constraint.... Cannot add duplicate key value
but there is no new value in my database
}
}
}
}
Your insert statement is incorrect. You have 5 parameters and passed only 4 values for them.
first.CommandText="INSERT INTO Students (idNo, fName, lName, course) VALUES (#idNum, #fname, #lname, #course)";
first.Parameters.AddWithValue("#idNum", idNum);
first.Parameters.AddWithValue("#fname", fname);
first.Parameters.AddWithValue("#lname", lname);
first.Parameters.AddWithValue("#course", course);
And idNum may be your primary key and set to auto increment in that case you don't require to pass idNo and if not auto incremented you should make sure you don't pass same idNo another time during insertion.
So, I have figured out that this code actually works but i didn't know because i thought that the table in my database would be updated but it would not, it was only the table in my dataset which was updated. Which means my code actually works in my dataset.
Here is the schema of my Society Table:
Society(SocietyName, Email, Password, Status)
So basically I'm creating a login page in which user enters Email and password. If there is an email which matches the one in database then it checks that whether status is equal to president or faculty member or Student Affairs Office. Based on that , it redirects to different pages.
Following is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication3 {
public partial class WebForm1 : System.Web.UI.Page {
MySql.Data.MySqlClient.MySqlConnection conn;
MySql.Data.MySqlClient.MySqlCommand cmd;
MySql.Data.MySqlClient.MySqlDataReader reader;
String QueryStr;
String name;
protected void Page_Load(object sender, EventArgs e) { }
protected void clicked(object sender, EventArgs e) {
String ConnString = System.Configuration.ConfigurationManager.ConnectionStrings["Webappconstring"].ToString();
conn = new MySql.Data.MySqlClient.MySqlConnection(ConnString);
conn.Open();
String QueryStr2 = "";
QueryStr = "";
QueryStr = "Select * from the_society_circle.society WHERE Email= '" + Emailtxt.Text + "' And Psswd=' " + passwordtxt.Text + "'";
cmd = new MySql.Data.MySqlClient.MySqlCommand(QueryStr, conn);
reader = cmd.ExecuteReader();
QueryStr2 = "Select Status from the_society_circle.society where Email = '" + QueryStr + "'";
name = "";
while (reader.HasRows && reader.Read()) {
name = reader["Email"].ToString();
}
if ((QueryStr2== "president" || QueryStr2 == "faculty member") && reader.HasRows ) {
Session["Email"] = name;
Response.BufferOutput = true;
Response.Redirect("WebForm2.aspx", true);
} else {
Emailtxt.Text = "invalid user";
}
conn.Close();
}
}
}
The problem is that if statement is never executed and it always prints invalid user.
PS: Im new to web development :D
You set QueryString2 to this value
QueryStr2 = "Select Status from the_society_circle.society where Email = '" + QueryStr + "'";
It can never be one of the values you check for.
As codemonkey already wrote, your condition will never come true.
You do the following: if ((QueryStr2== "president" || Quer... which evaluates to if (("Select Status from the_society_circle.society where Email = '" + QueryStr + "'"== "president" || Quer.... So you're comparing two different strings, which will never succeed.
I tried to refactor your code and came up with this (not tested, wrote from scratch):
First put your database-related code into a separate class (MySqlAccess) and dispose the database objects (put them into using-blocks which invokes Dispose() on leaving the block).
Don't use the user-inputs in your sql query directly. Remember "all input is evil". So better use parameterized-queries.
The reason your comparison failed was that you didn't execute your second query. Now the code executes just one query and returns the status of the user.
So to sum up:
Have SQL Injection and other malicious actions in mind. For example have a look at this article: http://msdn.microsoft.com/en-us/library/ms161953%28v=sql.105%29.aspx
And never store passwords as clear text in your database. That's the next thing you should care about. Edit your database to store the passwords as salted password hashes and just compare the hashes. For a starting point, have look at this article: http://www.codeproject.com/Articles/704865/Salted-Password-Hashing-Doing-it-Right
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MySql;
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
private string _connectionString;
protected void Page_Load(object sender, EventArgs e)
{
_connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["Webappconstring"].ToString();
}
protected void Clicked(object sender, EventArgs e)
{
string email = Emailtxt.Text;
string password = passwordtxt.Text;
var mysqlAccess = new MySqlAccess(_connectionString);
string status = mysqlAccess.GetStatus(email, password);
if (status == Constants.Status.PRESIDENT || status == Constants.Status.FACULTY_MEMBER)
{
Session["Email"] = email;
Response.Redirect("WebForm2.aspx", true);
}
else
{
Emailtxt.Text = "invalid user";
}
}
}
internal class MySqlAccess
{
private readonly string _connectionString;
public MySqlAccess(string connectionString)
{
_connectionString = connectionString;
}
public string GetStatus(string email, string password)
{
using (var conn = new MySqlConnection(_connectionString))
{
conn.Open();
string query = "SELECT Status FROM the_society_circle.society WHERE Email=#Email AND Psswd=#Password;";
using (var cmd = new MySqlCommand(query, conn))
{
cmd.Parameters.AddWithValue("#Email", email);
cmd.Parameters.AddWithValue("#Password", password);
using (var reader = cmd.ExecuteReader())
{
if (reader.HasRows && reader.Read())
{
return reader["Status"].ToString();
}
}
}
}
return string.Empty;
}
}
internal class Constants
{
internal class Status
{
public const string PRESIDENT = "president";
public const string FACULTY_MEMBER = "faculty member";
}
}
}
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.