I have a form that has a ComboBox that has to display names and the when the name is select is has to show the different values from my mysql database in different textboxes.
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 MySql.Data.MySqlClient;
namespace Dark_Heresy
{
public partial class Required_Attributes : Form
{
public Required_Attributes()
{
InitializeComponent();
}
private void cb_Talents_SelectedIndexChanged(object sender, EventArgs e)
{
string constring = "datasource = localhost; port = 3306; username = root; password = Mypass;";
string Query = "SELECT * FROM dark_heresy.talents WHERE TalentName='" + cb_Talents.Text + "' ;";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
while (myReader.Read())
{
string description = myReader.GetString("Description");
string strength = myReader.GetInt32("R_Str").ToString();
string weaponskill = myReader.GetInt32("R_WS").ToString();
string ballisticskill = myReader.GetInt32("R_BS").ToString();
string fellowship = myReader.GetInt32("R_Fel").ToString();
string perception = myReader.GetInt32("R_Per").ToString();
string intelligence = myReader.GetInt32("R_Int").ToString();
string agility = myReader.GetInt32("R_Agi").ToString();
string willpower = myReader.GetInt32("R_WP").ToString();
string toughness = myReader.GetInt32("R_Tough").ToString();
string talentrequired = myReader.GetString("Talent_required");
string skillrequired = myReader.GetString("Skill_required");
string classrequired = myReader.GetString("Class_required");
TextDescription.Text = description;
TextStrengh.Text = strength;
TextWeaponskill.Text = weaponskill;
TextBallisticskill.Text = ballisticskill;
TextFellowship.Text = fellowship;
TextPerception.Text = perception;
TextIntelligence.Text = intelligence;
TextAgility.Text = agility;
TextWillpower.Text = willpower;
TextToughness.Text = toughness;
TextTalent.Text = talentrequired;
TextSkill.Text = skillrequired;
TextClass.Text = classrequired;
}
}
catch (Exception ex)
{
MessageBox.Show("Error: \r\n" + ex);
}
}
}
}
However when i open the form and press the ComboBox, nothing happens, and nothing is shown, no syntax error occurs, what is wrong with the code?
UPDATE even if i change the code to:
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 MySql.Data.MySqlClient;
namespace Dark_Heresy
{
public partial class Talents : Form
{
public Talents()
{
InitializeComponent();
}
private void cb_Talents_SelectedIndexChanged(object sender, EventArgs e)
{
MessageBox.Show("Test");
//string constring = "datasource = localhost; port = 3306; username = root; password = Lorena89;";
//string Query = "SELECT * FROM dark_heresy.talents WHERE TalentName='" + cb_Talents.Text + "' ;";
//MySqlConnection conDataBase = new MySqlConnection(constring);
//MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
//MySqlDataReader myReader;
//try
//{
// conDataBase.Open();
// myReader = cmdDataBase.ExecuteReader();
// while (myReader.Read())
// {
// string description = myReader.GetString("Description");
// string strength = myReader.GetInt32("R_Str").ToString();
// string weaponskill = myReader.GetInt32("R_WS").ToString();
// string ballisticskill = myReader.GetInt32("R_BS").ToString();
// string fellowship = myReader.GetInt32("R_Fel").ToString();
// string perception = myReader.GetInt32("R_Per").ToString();
// string intelligence = myReader.GetInt32("R_Int").ToString();
// string agility = myReader.GetInt32("R_Agi").ToString();
// string willpower = myReader.GetInt32("R_WP").ToString();
// string toughness = myReader.GetInt32("R_Tough").ToString();
// string talentrequired = myReader.GetString("Talent_required");
// string skillrequired = myReader.GetString("Skill_required");
// string classrequired = myReader.GetString("Class_required");
// TextDescription.Text = description;
// TextStrengh.Text = strength;
// TextWeaponskill.Text = weaponskill;
// TextBallisticskill.Text = ballisticskill;
// TextFellowship.Text = fellowship;
// TextPerception.Text = perception;
// TextIntelligence.Text = intelligence;
// TextAgility.Text = agility;
// TextWillpower.Text = willpower;
// TextToughness.Text = toughness;
// TextTalent.Text = talentrequired;
// TextSkill.Text = skillrequired;
// TextClass.Text = classrequired;
// }
//}
// catch (Exception ex)
// {
// MessageBox.Show("Error: \r\n" + ex);
// }
}
private void Talents_Load(object sender, EventArgs e)
{
}
}
}
Nothing happens, the combobox is never fired up, how can i make it work.
I would set a static value that you know exists in the database inside the query and see if it returns anything. This will tell you if your query is incorrect.
string Query = "SELECT * FROM dark_heresy.talents WHERE TalentName='This.Guy';";
As per your second question, you can create static global variables inside your Required_Attributes form like:
public static string username;
public static string password;
And on the closing event of your login page, set the variables' values like:
private void Authenticate_Closing(object sender, FormClosingEventArgs e)
{
Required_Attributes.username = username.text;
Required_Attributes.password = password.text;
}
Your connection string would look like this:
string constring = "datasource = localhost; port = 3306; username =" + username + "; password = " + password + ";";
Related
I'm trying to post a List from my Model so that within the Controller I can view all the contacts that are within the List.
I have tried many different ways, but for some reason I get the same error that the List is null, even though there is data within my Microsoft Access Database. Also, when I try to edit the data, I can do so, but I'm not able to view the data that was previously present within the text boxes of the Controller/View.
If some could please help me.
MODEL:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.OleDb;
using System.Drawing;
using System.Windows.Forms;
using System.Collections;
namespace CW2_Enterprise
{
public class Contact
{
OleDbConnection connection = new OleDbConnection();
public List<Contact> contacts = new List<Contact>();
String id;
String firstName;
String lastName;
String postcode;
String email;
String phone;
public Contact(string id, string firstName, string lastName, string postcode, string email, string phone)
{
this.ID = id;
this.FirstName = firstName;
this.LastName = lastName;
this.Postcode = postcode;
this.Email = email;
this.Phone = phone;
}
public void addContacts(Contact contact)
{
string id = contact.ID;
string firstName = contact.FirstName;
string lastName = contact.LastName;
string postcode = contact.Postcode;
string email = contact.Email;
string phone = contact.Phone;
try
{
connection.ConnectionString = #"Provider = Microsoft.Jet.OLEDB.4.0; Data Source = D:\Database_2.mdb";
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "INSERT INTO Contact VALUES ('" + id + "','" + firstName + "','" + lastName + "','" + postcode + "','" + email + "','" + phone + "')";
command.ExecuteNonQuery();
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
public void viewContacts(Contact contact)
{
try
{
connection.ConnectionString = #"Provider = Microsoft.Jet.OLEDB.4.0; Data Source = D:\Database_2.mdb";
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "SELECT * FROM Contact";
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
contact.ID = reader["ID"].ToString();
contact.FirstName = reader["FirstName"].ToString();
contact.LastName = reader["LastName"].ToString();
contact.Postcode = reader["Postcode"].ToString();
contact.Email = reader["Email"].ToString();
contact.Phone = reader["Phone"].ToString();
contact.contacts.Add(contact);
}
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
public void find(Contact contact)
{
string id = contact.ID;
try
{
connection.ConnectionString = #"Provider = Microsoft.Jet.OLEDB.4.0; Data Source = D:\Database_2.mdb";
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "SELECT * FROM Contact WHERE ID='" + contact.ID + "'";
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
public void editContacts(Contact contact)
{
string id = contact.ID;
string firstName = contact.FirstName;
string lastName = contact.LastName;
string postcode = contact.Postcode;
string email = contact.Email;
string phone = contact.Phone;
try
{
connection.ConnectionString = #"Provider = Microsoft.Jet.OLEDB.4.0; Data Source = D:\Database_2.mdb";
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string see = "UPDATE Contact SET FirstName='" + firstName + "', LastName='" + lastName + "', Postcode='" + postcode + "', Email='" + email + "', Phone='" + phone + "' WHERE ID='" + id + "'";
command.CommandText = see;
OleDbDataReader reader = command.ExecuteReader();
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
public string ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Postcode { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public List<Contact> ContactsView { get; set; }
}
}
View/Controller (Partial Class)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CW2_Enterprise
{
public partial class viewContacts : Form
{
Contact contact = new Contact();
ComboBox comboBox = new ComboBox();
public viewContacts()
{
InitializeComponent();
}
private void viewContacts_Load(object sender, EventArgs e)
{
comboBox.Location = new System.Drawing.Point(10, 10);
comboBox.DropDownStyle = ComboBoxStyle.DropDownList;
comboBox.Size = new System.Drawing.Size(136, 81);
this.Controls.Add(comboBox);
comboBox.Items.Add(contact.FirstName);
contact.viewContacts(contact);
}
}
}
Edit Contacts View/Controller (Partial Class)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CW2_Enterprise
{
public partial class editContacts : Form
{
TextBox idBox = new TextBox();
TextBox firstNameBox = new TextBox();
TextBox lastNameBox = new TextBox();
TextBox postcodeBox = new TextBox();
TextBox emailBox = new TextBox();
TextBox phoneBox = new TextBox();
public editContacts()
{
InitializeComponent();
}
private void editContacts_Load(object sender, EventArgs e)
{
Contact contact = new Contact();
contact.ID = idBox.Text;
Label idLabel = new Label();
idLabel.Text = "ID: ";
idLabel.Size = new Size(80, 30);
System.Drawing.Point idLabelLocation = new System.Drawing.Point(10, 15);
idLabel.Location = idLabelLocation;
this.Controls.Add(idLabel);
idBox.Name = "ID";
idBox.Size = new Size(250, 200);
System.Drawing.Point idBoxLocation = new System.Drawing.Point(100, 15);
idBox.Location = idBoxLocation;
this.Controls.Add(idBox);
Button show = new Button();
show.Text = "SHOW";
show.Size = new Size(75, 23);
System.Drawing.Point showLocation = new System.Drawing.Point(380, 13);
showButton.Location = showLocation;
this.Controls.Add(show);
show.Click += new System.EventHandler(this.show_Click);
contact.find(contact);
}
private void show_Click(object sender, EventArgs e)
{
Contact contact = new Contact();
contact.FirstName = firstNameBox.Text;
contact.LastName = lastNameBox.Text;
contact.Postcode = postcodeBox.Text;
contact.Email = emailBox.Text;
contact.Phone = phoneBox.Text;
Console.WriteLine("Contact: " + contact);
Label firstNameLabel = new Label();
firstNameLabel.Text = "First Name: ";
firstNameLabel.Size = new Size(80, 30);
System.Drawing.Point firstNameLabelLocation = new System.Drawing.Point(10, 45);
firstNameLabel.Location = firstNameLabelLocation;
this.Controls.Add(firstNameLabel);
firstNameBox.Text = contact.FirstName;
firstNameBox.Size = new Size(250, 200);
System.Drawing.Point firstNameBoxLocation = new System.Drawing.Point(100, 45);
firstNameBox.Location = firstNameBoxLocation;
this.Controls.Add(firstNameBox);
Button edit = new Button();
edit.Text = "Edit";
edit.Size = new Size(250, 50);
System.Drawing.Point editLocation = new System.Drawing.Point(40, 200);
edit.Location = editLocation;
this.Controls.Add(edit);
edit.Click += new System.EventHandler(this.edit_Click);
}
private void edit_Click(object sender, EventArgs e)
{
Contact contact = new Contact();
contact.ID = idBox.Text;
contact.FirstName = firstNameBox.Text;
contact.LastName = lastNameBox.Text;
contact.Postcode = postcodeBox.Text;
contact.Email = emailBox.Text;
contact.Phone = phoneBox.Text;
contact.editContacts(contact);
}
}
}
I'd like to know if my Update SQL statement is correct, because I have a form where I wanna edit some data. But, for any reason, the form doesn't save the updates and nothing happens in db.
This is my code-behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
public partial class edit : System.Web.UI.Page
{
SqlConnection con = new SqlConnection("Data Source=CASSIA-PC\\SQLEXPRESS;Initial Catalog=clientes;Integrated Security=True");
protected void Page_Load(object sender, EventArgs e)
{
string v = Request.QueryString["id"];
SqlCommand cmd = new SqlCommand("SELECT idCliente, nmCliente, fantasia, cpf, cep, logradouro, numero, complemento, bairro, cidade, estado, telefone, celular, insEstadual, insMunicipal, email, homePage, tbClientes.tpCliente, tbTipoClientes.idTipoCliente, tbTipoClientes.nmTipoCliente FROM tbClientes INNER JOIN tbTipoClientes ON tbClientes.tpCliente = tbTipoClientes.idTipoCliente WHERE idCliente = '" + v + "'", con);
try
{
con.Open();
using (var reader = cmd.ExecuteReader())
{
while (reader.Read()) {
txtId.Text = reader["idCliente"].ToString();
txtNome.Text = reader["nmCliente"].ToString();
txtFantasia.Text = reader["fantasia"].ToString();
txtCPF.Text = reader["cpf"].ToString();
txtCEP.Text = reader["cep"].ToString();
txtLogradouro.Text = reader["logradouro"].ToString();
txtNumero.Text = reader["numero"].ToString();
txtComplemento.Text = reader["complemento"].ToString();
txtBairro.Text = reader["bairro"].ToString();
txtCidade.Text = reader["cidade"].ToString();
txtEstado.Text = reader["estado"].ToString();
txtTelefone.Text = reader["telefone"].ToString();
txtCelular.Text = reader["celular"].ToString();
txtInscEstadual.Text = reader["insEstadual"].ToString();
txtInscMunicipal.Text = reader["insMunicipal"].ToString();
txtEmail.Text = reader["email"].ToString();
txtSite.Text = reader["homePage"].ToString();
}
}
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
con.Close();
}
}
protected void btnEditar_Click(object sender, EventArgs e)
{
string v = Request.QueryString["id"];
con.Open();
SqlCommand cmd = new SqlCommand("UPDATE tbClientes SET nmCliente = '"+txtNome.Text+"', fantasia = '"+txtFantasia.Text+"', cpf = '"+txtCPF.Text+"', cep = '"+txtCEP.Text+"', logradouro = '"+txtLogradouro.Text+"', numero = '"+txtNumero.Text+"', complemento = '"+txtComplemento.Text+"', bairro = '"+txtBairro.Text+"', cidade = '"+txtCidade.Text+"', estado = '"+txtEstado.Text+"', telefone = '"+txtTelefone.Text+"', celular = '"+txtCelular.Text+ "', insEstadual = '"+txtInscEstadual.Text+"', insMunicipal = '"+txtInscMunicipal.Text+"', email = '"+txtEmail.Text+"', homePage = '"+txtSite.Text+"' WHERE idCliente = '" + v + "'", con);
try
{
cmd.ExecuteNonQuery();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
con.Close();
}
}
}
I'm pretty sure your problem is:
WHERE idCliente = '" + v + "'"
Because the Client ID is most likely a numeric field in the database you want to treat it as such:
WHERE idCliente = " + v
As Blorgbeard mentions you need to use Parameterised commands to protect against an SQL Injection attack. This will also solve issues such as textboxes containing apostrophes and etc that would also cause your UPDATE to fail.
I agree with Jeremy, also better if you change to parameterized query OR set your query with a label, copy query and test it directly in SQL Server.
string query = "Update..."
Copy query text and test it directly in SQL Server.
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";
}
}
}
I'm having a problem with C# and sql connection. when it comes to C# I'm a noobie and have pretty much no idea what I'm doing :/ I am trying to follow a tutorial which explaines how to do everything step by step and for some reason it doesn't work when I try to do it on my database and application.
This is my Form1.cs
using System;
using System.Collections;
using System.Windows.Forms;
namespace Praca_Inzynierska
{
public partial class Form1 : Form
{
private Connection sqlCon = new Connection();
private ArrayList list = new ArrayList();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'restaurantDataSet2.Employees' table. You can move, or remove it, as needed.
this.employeesTableAdapter.Fill(this.restaurantDataSet2.Employees);
FillTextFieldsEmployees(1);
}
public void FillTextFieldsEmployees(int EmployeeID)
{
list = sqlCon.GetAllEmployees(EmployeeID);
textFirstName.Text = list[0].ToString();
textLastName.Text = list[1].ToString();
textAdress.Text = list[2].ToString();
textCity.Text = list[3].ToString();
textPhoneNumber.Text = list[4].ToString();
textEmail.Text = list[5].ToString();
textBirthDate.Text = list[6].ToString();
textAge.Text = list[7].ToString();
textGender.Text = list[8].ToString();
textTitle.Text = list[9].ToString();
textSalary.Text = list[10].ToString();
}
private void dataGridViewEmployees_CellClick(object sender, DataGridViewCellEventArgs e)
{
var currentRowIndex = dataGridViewEmployees.SelectedCells[0].RowIndex;
int currentIndex = (int) dataGridViewEmployees.Rows[currentRowIndex].Cells[0].Value;
FillTextFieldsEmployees(currentIndex);
}
}
}
This is my class Connection
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
namespace Praca_Inzynierska
{
public class Connection
{
private String connectionString = "Data Source = MAKSKOMP\\SQL2012EXP; Initial Catalog = Restaurant;Integrated Security = True";
public ArrayList GetAllEmployees(int EmployeeID)
{
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
String query = "SELECT * FROM Employees WHERE EmployeeID = '" + EmployeeID +"'";
using (var command = new SqlCommand(query, connection))
{
var reader = command.ExecuteReader();
var list = new ArrayList();
while (reader.Read())
{
String FirstName = reader.GetString(1);
String LastName = reader.GetString(2);
String Adress = reader.GetString(3);
String City = reader.GetString(4);
String PhoneNumber = reader.GetString(5);
String Email = reader.GetString(6);
DateTime BirthDate = reader.GetDateTime(7);
Int16 Age = reader.GetInt16(8);
String Gender = reader.GetString(9);
String Title = reader.GetString(10);
int Salary = reader.GetInt32(11);
list.Add(FirstName);
list.Add(LastName);
list.Add(Adress);
list.Add(City);
list.Add(PhoneNumber);
list.Add(Email);
list.Add(BirthDate);
list.Add(Age);
list.Add(Gender);
list.Add(Title);
list.Add(Salary);
}
connection.Close();
reader.Close();
return list;
}
}
}
}
}
and for some reason it breaks in this particular place
int currentIndex = (int) dataGridViewEmployees.Rows[currentRowIndex].Cells[0].Value;
I have tried to debug it step by step and also it doesn't finish this loop
while (reader.Read())
{
String FirstName = reader.GetString(1);
String LastName = reader.GetString(2);
String Adress = reader.GetString(3);
String City = reader.GetString(4);
String PhoneNumber = reader.GetString(5);
String Email = reader.GetString(6);
DateTime BirthDate = reader.GetDateTime(7);
Int16 Age = reader.GetInt16(8);
String Gender = reader.GetString(9);
String Title = reader.GetString(10);
int Salary = reader.GetInt32(11);
list.Add(FirstName);
list.Add(LastName);
list.Add(Adress);
list.Add(City);
list.Add(PhoneNumber);
list.Add(Email);
list.Add(BirthDate);
list.Add(Age);
list.Add(Gender);
list.Add(Title);
list.Add(Salary);
}
it ends on
Int16 Age = reader.GetInt16(8);
Since your code already uses a Data Bound grid, try binding the TextBox controls to the same binding source as well. It doesn't make much sense to fetch the data from the database when the data is already loaded into the grid...
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.