Executing a SQL query with C# - c#

I would like to add some information to my database. I searched for some tutorials, but none of them work.
NonQuery can do what he needs to do, because the messagebox returns "Success" (1). But it does not update my database. If I put the same query to "Add New Query", directly to my database, it works.
Can someone help me?
My class code at the moment:
namespace BurnThatFat
{
class databaseconnection
{
//fields
SqlConnection connection;
string connectionstring;
public databaseconnection()
{
// fields waarde toewijzen
connectionstring = #"Data Source=(LocalDB)\MSSQLLocalDB;" +
#"AttachDbFilename=|DataDirectory|\Database2.mdf;Integrated Security=True";
connection = new SqlConnection(connectionstring);
OpenConnection();
CloseConnection();
}
public List<Object> getObjectsFromDatabase()
{
try
{
OpenConnection();
// sql query
// Datareader
// sqlcommand
// return list van objecten , objecten veranderd naar jouw wens van data.
CloseConnection();
}
catch (Exception)
{
throw;
}
return new List<object>();
}
private bool OpenConnection()
{
try
{
connection.Open();
return true;
}
catch (MySqlException ex)
{
switch (ex.Number)
{
case 0:
MessageBox.Show("Cannot connect to server. Contact administrator");
break;
case 1045:
MessageBox.Show("Invalid username/password, please try again");
break;
}
return false;
}
}
private bool CloseConnection()
{
try
{
connection.Close();
return true;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
public void AddGebruiker()
{
string query = "insert into Gebruiker VALUES(3, 'Cihan', 'Kurt', 18, 'Man', 85, 75, 'Admin1', 'Test123', 'testen');";
using (connection)
{
SqlCommand command = new SqlCommand(query, connection);
OpenConnection();
int resultaat = command.ExecuteNonQuery();
if (resultaat == 1)
{
MessageBox.Show("succes");
}
else
{
MessageBox.Show("fail");
}
}
}
}
}
Edit:
And this is the code for my buttons etc:
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;
// voor sql connectie.
using System.Data.SqlClient;
namespace BurnThatFat
{
public partial class SignUp : Form
{
databaseconnection db = new databaseconnection();
public SignUp()
{
InitializeComponent();
gb_login.Visible = false;
gb_Voornaam.Visible = false;
gb_Achternaam.Visible = false;
gb_leeftijdgeslacht.Visible = false;
gb_gewicht.Visible = false;
gb_email.Visible = false;
gb_Start.Visible = true;
}
private void btn_SignUp_Click(object sender, EventArgs e)
{
gb_Start.Visible = false;
gb_Voornaam.Visible = true;
}
private void btn_login_Click(object sender, EventArgs e)
{
gb_Start.Visible = false;
gb_login.Visible = true;
}
private void btn_loginvolgende_Click(object sender, EventArgs e)
{
gb_login.Visible = false;
// hier moet nog een GB!!!!!!
}
private void btn_voornaamvolgende_Click(object sender, EventArgs e)
{
gb_Voornaam.Visible = false;
gb_Achternaam.Visible = true;
}
private void btn_achternaamvolgende_Click(object sender, EventArgs e)
{
gb_Achternaam.Visible = false;
gb_leeftijdgeslacht.Visible = true;
}
private void btn_leeftijdvolgende_Click(object sender, EventArgs e)
{
gb_leeftijdgeslacht.Visible = false;
gb_gewicht.Visible = true;
}
// einde registratie
// opslaan van gegevens in database
private void btn_emailvolgende_Click(object sender, EventArgs e)
{
// gebruiker = new Gebruikerklasse();
// gebruiker.Naam = Convert.ToString(tb_voornaam.Text);
//// gebruiker.Achternaam = Convert.ToString(tb_achternaam.Text);
// gebruiker.Leeftijd = Convert.ToInt32(nud_leeftijd.Value);
/// gebruiker.Geslacht = Convert.ToString(cb_geslacht.Text);
// gebruiker.Huidig_gewicht = Convert.ToInt32(nud_huidiggewicht.Value);
// gebruiker.Streef_gewicht = Convert.ToInt32(nud_streefgewicht.Value);
/// gebruiker.Gebruikersnaam = Convert.ToString(tb_gebruikersnaam2.Text);
// gebruiker.Email = Convert.ToString(tb_email.Text);
// gebruiker.Wachtwoord = Convert.ToString(tb_wachtwoordsignup.Text);
db.AddGebruiker();
gb_email.Visible = false;
// hier moet nog een GB!!!!!
}
private void btn_gewichtvolgende_Click(object sender, EventArgs e)
{
gb_gewicht.Visible = false;
gb_email.Visible = true;
}
}
}

The simplest way to insert into a SQL Server database:
string connectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database2.mdf;Integrated Security=True";
string commandText = "INSERT INTO MyTable (ID, Name, Address) VALUES (10, 'Bob', '123 Main Street');";
using (SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand(commandText, conn))
{
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
As long as commandText is a working query, it should insert a row. It would be better to use parameters for your values instead of hard coding them like I did here - that avoids SQL injection attacks and other potential problems. You can search Google for that (or the question you are asking now) and find tons of resources to help you.
If you need more specific help, post details such as what is actually happening when you try to run your code - are you getting an exception?

I'd clean up a bunch of things before doing anything else.
First, get rid of the openconnection and closeconnection methods all together. And don't keep an instance property for the connection in your class. Create the connection ondemand with a using statement, because at the end of the using statement the compiler will insert a call to the Dispose method on the connection's IDisposable interface implementation and it will close the connection automatically for you.
So after cleaning up all the unnecessary code all you really should have in this class is an implementation of your Addgebrukier method which would look like this
public void AddGebruiker()
{
string query = "insert into Gebruiker VALUES(3, 'Cihan', 'Kurt', 18, 'Man', 85, 75, 'Admin1', 'Test123', 'testen');";
using (SqlConnection connection = new SqlConnection(connectionstring))
{
using (SqlCommand command = new SqlCommand(query, connection))
{
connection.Open();
int resultaat = command.ExecuteNonQuery();
if (resultaat == 1)
{
MessageBox.Show("succes");
}
else
{
MessageBox.Show("fail");
}
}
}
}
You should also load your connection string from the section in the app/web.config, but you can do that later after you get it running.

Here is a simple concept that should work perfectly fine for you. Just change the ServerName, DatabaseName, etc.
using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection connection ;
SqlDataAdapter adapter = new SqlDataAdapter();
string sql = null;
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
connection = new SqlConnection(connetionString);
sql = "insert into product (Product_id,Product_name,Product_price) values(6,'Product6',600)";
try
{
connection.Open();
adapter.InsertCommand = new SqlCommand(sql, connection);
adapter.InsertCommand.ExecuteNonQuery();
MessageBox.Show ("Row inserted !! ");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}

Related

Insert data into Npgsql/Postgresql database with C# windows forms

I am completely new to programming and I am trying to create a small app as a school project. I want it to be able to register and login users. I have already figured out how to create login part, but I am stuck on registration. I have created Insert function inside pgAdmin and it works but I cant make it work with my windows forms app.
This is my code so far:
using Npgsql;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ProjektV0._0._2
{
public partial class frmRegister : Form
{
public frmRegister()
{
InitializeComponent();
}
private NpgsqlConnection conn;
string connstring = String.Format("Server={0}; Port={1};" +
"User Id = {2}; Password={3};Database={4};",
"localhost", "5432", "postgres", "23112001", "demo2");
private NpgsqlCommand cmd;
private string sql = null;
private void frmRegister_Load(object sender, EventArgs e)
{
conn = new NpgsqlConnection(connstring);
}
private void Register_FormClosed(object sender, FormClosedEventArgs e)
{
Application.Exit();
}
private void btnRegister_Click(object sender, EventArgs e)
{
try
{
conn.Open();
sql = #"select * from u_insert(:_username,:_password)";
cmd = new NpgsqlCommand(sql, conn);
cmd.Parameters.AddWithValue("_username", txtEmail.Text);
cmd.Parameters.AddWithValue("_password", txtPswrd.Text);
if ((int)cmd.ExecuteScalar() == 1)
{
conn.Close();
MessageBox.Show("Registered successfuly", "Well done", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
txtEmail.Text = txtPswrd.Text = txtConPswrd.Text = null;
}
}
catch (Exception ex)
{
conn.Close();
MessageBox.Show("Error", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
pgAdmin part:
create function u_insert
(
_username character varying,
_password character varying
)returns int as
$$
begin
insert into tbl_users
(
username,
password
)values
(
_username,
_password
);
if found then
return 1;-----success-----
else
return 0;-----fail-----
end if;
end
$$
language plpgsql
As I said my login part work even through my program and all other functions (insert,update) work only inside pgAdmin.
To clarify my comment... why the function/procedure? It seems dramatic overkill for an insert. I would put something like this outside of my form (in a CRUD class somewhere):
public static int UpdateUser(string UserId, string Password, out string ErrorMessage)
{
int result = 0;
ErrorMessage = null;
NpgsqlConnectionStringBuilder sb = new NpgsqlConnectionStringBuilder();
sb.Host = "localhost";
sb.Port = 5432;
sb.Username = "postgres";
sb.Password = "23112001";
sb.Database = "demo2";
using (NpgsqlConnection conn = new NpgsqlConnection(sb.ToString()))
{
conn.Open();
string dml = "insert into tbl_users (username, password) values (:USER, :PW)";
using (NpgsqlCommand cmd = new NpgsqlCommand(dml, conn))
{
cmd.Parameters.AddWithValue("USER", UserId);
cmd.Parameters.AddWithValue("PW", Password);
try
{
result = cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
ErrorMessage = ex.Message;
}
}
}
return result;
}
And then within the Button Click event you can simplify it to this:
private void btnRegister_Click(object sender, EventArgs e)
{
string error;
int insertedRows = CrudClass.UpdateUser(txtEmail.Text, txtPassword.Text, out error);
if (insertedRows == 1)
{
MessageBox.Show("Registered successfuly", "Well done", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
txtEmail.Text = txtPswrd.Text = txtConPswrd.Text = null;
}
else
{
MessageBox.Show("Error", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
The connection string is invalid for Postgres. It should rather be "Host={0}; Port={1}; Username= {2}; Password={3};Database={4};"
Then the parameter placeholder should be #, not :
Tip 1: read the doc of the proper database
Note that the connection string is invalid, and opening the connection likely throws an error. In the catch section, you start by closing the connection then you display the error message. If closing the connection fails and throws an error, the code after it will never be executed.
Tip 2: don't do anything that can throw an error within a catch section. You can nest another try..catch though.

No value given for one or more required parameters - C#/Access

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";

Creating Windows authentication and SQL Server authentication in login form

I have a login form in Visual Studio C# and below is a screenshot of it.
https://i.stack.imgur.com/uziUD.png
My goal is to allow the user to choose whether to log in using Windows authentication, in a workplace as we are using LAN network or using SQL Server authentication (username and password are stored in server -> security -> login).
Below is the code 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.SqlClient;
using System.Data.Sql;
using System.Data.OleDb;
namespace Login_HouseKeeping_
{
public partial class Form1: Form
{
public Form1()
{
InitializeComponent();
}
// Connection string
string cs = #"Data Source = 172.28.40.19\CASINO2008R2; Initial catalog =GCVS2_DEV_GHR; Integrated Security = True;";
// Login click event
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text == "" || textBox2.Text == "")
{
MessageBox.Show("Please provide Username and Password");
return;
}
else
try
{
//Create sqlconnection
SqlConnection con = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand(#"SELECT * FROM Logins WHERE Username = #username AND Password = #Password", con);
cmd.Parameters.AddWithValue("#username", textBox1.Text);
cmd.Parameters.AddWithValue("#Password", textBox2.Text);
con.Open();
SqlDataAdapter adapt = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapt.Fill(ds);
con.Close();
int count = ds.Tables[0].Rows.Count;
// if count equals to 1, then show frmMain form
if (count == 1)
{
MessageBox.Show("Login successful");
this.Hide();
frmMain fm = new frmMain();
fm.Show();
}
else
{
MessageBox.Show("Login failed");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
textBox2.PasswordChar = '*';
}
private void btn_Exit_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
I can't seem to find many resources on implementing these two authentication into my login. How do I achieve this?
EDIT:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void label2_Click(object sender, EventArgs e)
{
}
private void btn_Exit_Click(object sender, EventArgs e)
{
this.Close();
}
private void btn_Login_Click(object sender, EventArgs e)
{
var connStrBldr = new System.Data.SqlClient.SqlConnectionStringBuilder();
connStrBldr.DataSource = "172.28.40.19\CASINO2008R2";
connStrBldr.InitialCatalog = "GCVS2_DEV_GHR";
if (WindowsAuth)
{
connStrBldr.IntegratedSecurity = true;
}
else
{
connStrBldr.IntegratedSecurity = false;
connStrBldr.UserID = textBox1.Text;
connStrBldr.Password = textBox2.Text;
}
using (SqlConnection con = new SqlConnection(connStrBldr.ToString()))
{
con.Open();
//do your lookup on login here
}
}
private void WindowsAuth_CheckedChanged(object sender, EventArgs e)
{
}
private void SqlAuth_CheckedChanged(object sender, EventArgs e)
{
}
}
}
I'm only posting this answer since OP can't seem to make #Tim's answer work. Credits to #Tim.
Just simply use:
EDIT: Changed since username and password is not mandatory for windows authentication.
private void btn_Login_Click(object sender, EventArgs e)
{
bool useWindowsAuth = WindowsAuth.Checked; // Assuming that WindowsAuth is your radio button
string userName = string.Empty;
string password = string.Empty;
if(!useWindowsAuth)
{
userName = textBox1.Text;
password = textBox2.Text;
if (string.IsNullOrWhiteSpace(userName) || string.IsNullOrWhiteSpace(password))
{
MessageBox.Show("Please provide Username and Password");
return;
}
}
var connStrBldr = new System.Data.SqlClient.SqlConnectionStringBuilder();
connStrBldr.DataSource = #"172.28.40.19\CASINO2008R2";
connStrBldr.InitialCatalog = "GCVS2_DEV_GHR";
if (useWindowsAuth)
{
connStrBldr.IntegratedSecurity = true;
}
else
{
connStrBldr.IntegratedSecurity = false;
connStrBldr.UserID = userName;
connStrBldr.Password = password;
}
bool validUser = true;
try
{
using (SqlConnection con = new SqlConnection(connStrBldr.ToString()))
{
con.Open();
//do your lookup on login here
}
}
catch(SqlException) // An exception will be caught if invalid credentials were used.
{
validUser = false;
}
if(validUser)
MessageBox.Show("Login successful!");
else
MessageBox.Show("Login failed!");
}
}
I have verified that the code works using a sample project. You just have to make sure of the following:
Username and Password is correct (Server > Security).
User has access to GCVS2_DEV_GHR table. This can be configured under (Server > Security > User)
Also, this way of coding is not a good way to do it but since you seem new to C# just make sure to study more about good practices.
Authentication is controlled by your connection string. Your best bet is to use System.Data.SqlClient.SqlConnectionStringBuilder to build the connection string dynamically based on whether you want SQL Server auth or Windows auth:
var connStrBldr = new System.Data.SqlClient.SqlConnectionStringBuilder();
connStrBldr.DataSource = "172.28.40.19\CASINO2008R2";
connStrBldr.InitialCatalog = "GCVS2_DEV_GHR";
if (useWindowsAuth) {
connStrBldr.IntegratedSecurity = true;
} else {
connStrBldr.IntegratedSecurity = false;
connStrBldr.UserID = textBox1.Text;
connStrBldr.Password = textBox2.Text;
}
using (SqlConnection con = new SqlConnection(connStrBldr.ToString())) {
con.Open();
//do your lookup on login here
}

make a label static error : cannot access a non-static member of outer type 'windowsForm8.Form1' via nested Type 'windowsForm8.Form1.DBConnect'

Yo this is my first post here and i wanna know how to fix this problem in C#
so im tryin to connect to database and select information from it and those information will be displayed as a label ! easy,
so this is the error i get :
cannot access a non-static member of outer type 'windowsForm8.Form1'
via nested Type 'windowsForm8.Form1.DBConnect'
and this is the Code :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace WindowsFormsApplication8
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public class DBConnect
{
private MySqlConnection connection;
private string server;
private string database;
private string uid;
private string password;
//Constructor
public DBConnect()
{
Initialize();
}
//Initialize values
private void Initialize()
{
server = "net";
database = "rainbow";
uid = "ok";
password = "passwd!";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
}
//open connection to database
private bool OpenConnection()
{
try
{
connection.Open();
return true;
}
catch (MySqlException ex)
{
//When handling errors, you can your application's response based
//on the error number.
//The two most common error numbers when connecting are as follows:
//0: Cannot connect to server.
//1045: Invalid user name and/or password.
switch (ex.Number)
{
case 0:
MessageBox.Show("Cannot connect to server. Contact administrator");
break;
case 1045:
MessageBox.Show("Invalid username/password, please try again");
break;
default :
MessageBox.Show("Connected Successfuly!!");
break;
}
return false;
}
}
//Close connection
private bool CloseConnection()
{
try
{
connection.Close();
return true;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
//Insert statement
public void Insert()
{
string query = "INSERT INTO mytable (username, password) VALUES('shryder', 'nopassword')";
//open connection
if (this.OpenConnection() == true)
{
//create command and assign the query and connection from the constructor
MySqlCommand cmd = new MySqlCommand(query, connection);
//Execute command
cmd.ExecuteNonQuery();
//close connection
this.CloseConnection();
}
}
//Update statement
public void Update()
{
}
//Delete statement
public void Delete()
{
}
//Select statement
public List<string>[] Select()
{
string query = "SELECT * FROM mytable";
//Create a list to store the result
List<string>[] list = new List<string>[3];
list[0] = new List<string>();
list[1] = new List<string>();
list[2] = new List<string>();
//Open connection
if (this.OpenConnection() == true)
{
//Create Command
MySqlCommand cmd = new MySqlCommand(query, connection);
//Create a data reader and Execute the command
MySqlDataReader dataReader = cmd.ExecuteReader();
//Read the data and store them in the list
if (dataReader.Read())
{
/*list[0].Add(dataReader["username"] + "");
list[1].Add(dataReader["password"] + "");
list[2].Add(dataReader["email"] + "");*/
newscontent.Text = dataReader["username"]; //this is the error
}
//close Data Reader
dataReader.Close();
//close Connection
this.CloseConnection();
//return list to be displayed
return list;
}
else
{
return list;
}
}
//Count statement
//Backup
public void Backup()
{
}
//Restore
public void Restore()
{
}
}
}
}
please help me
,thanks :)
Move all your code from the class DbConnect yo your Form1 class. Then all of your methods have access to your form controls.
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 WindowsFormsApplication8
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private MySqlConnection connection;
private string server;
private string database;
private string uid;
private string password;
//Initialize values
private void Initialize()
{
server = "net";
database = "rainbow";
uid = "ok";
password = "passwd!";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
}
//open connection to database
private bool OpenConnection()
{
try
{
connection.Open();
return true;
}
catch (MySqlException ex)
{
//When handling errors, you can your application's response based
//on the error number.
//The two most common error numbers when connecting are as follows:
//0: Cannot connect to server.
//1045: Invalid user name and/or password.
switch (ex.Number)
{
case 0:
MessageBox.Show("Cannot connect to server. Contact administrator");
break;
case 1045:
MessageBox.Show("Invalid username/password, please try again");
break;
default :
MessageBox.Show("Connected Successfuly!!");
break;
}
return false;
}
}
//Close connection
private bool CloseConnection()
{
try
{
connection.Close();
return true;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
//Insert statement
public void Insert()
{
string query = "INSERT INTO mytable (username, password) VALUES('shryder', 'nopassword')";
//open connection
if (this.OpenConnection() == true)
{
//create command and assign the query and connection from the constructor
MySqlCommand cmd = new MySqlCommand(query, connection);
//Execute command
cmd.ExecuteNonQuery();
//close connection
this.CloseConnection();
}
}
//Update statement
public void Update()
{
}
//Delete statement
public void Delete()
{
}
//Select statement
public List<string>[] Select()
{
string query = "SELECT * FROM mytable";
//Create a list to store the result
List<string>[] list = new List<string>[3];
list[0] = new List<string>();
list[1] = new List<string>();
list[2] = new List<string>();
//Open connection
if (this.OpenConnection() == true)
{
//Create Command
MySqlCommand cmd = new MySqlCommand(query, connection);
//Create a data reader and Execute the command
MySqlDataReader dataReader = cmd.ExecuteReader();
//Read the data and store them in the list
if (dataReader.Read())
{
/*list[0].Add(dataReader["username"] + "");
list[1].Add(dataReader["password"] + "");
list[2].Add(dataReader["email"] + "");*/
newscontent.Text = dataReader["username"]; //this is the error
}
//close Data Reader
dataReader.Close();
//close Connection
this.CloseConnection();
//return list to be displayed
return list;
}
else
{
return list;
}
}
//Count statement
//Backup
public void Backup()
{
}
//Restore
public void Restore()
{
}
}
}
}
Like this your code ahould be able to access the labels, so it should compile. It still doesn't do anything since none of the methods are called.
Edited this on my phone, so couldn't test the code.

Datagridview cell value change update database

I have retrieved data from Mysql database into a DataGridView1. Let us suppose I am in Row 0. When I change the contents of Row 0, Cell 1 and press enter key or a button, the Update query should modify that row, but I am unable to modify the value of the cell. The cell maintains its previous value when i reload data and the database is not modified. For example, if I change the contents of a cell under column Client_Name from "Acs" to "Gmt", how can I change the value of the cell from "Acs" to "Gmt"? and to have it updated into Mysql database, I am using c# in Vs 2012. below is my code that retrieves my database into datagridview1 any help is welcomed thanks.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data;
using MySql.Data.MySqlClient;
using System.Configuration;
using System.Data.SqlClient;
namespace PI.Gen
{
public partial class frmMain : Form
{
MySqlConnection Conn;
public frmMain()
{
InitializeComponent();
btnDisconnect.Enabled = true;
btnLoadData.Enabled = false;
btnLoadClients.Enabled = false;
}
private void btnConnect_Click(object sender, EventArgs e)
{
string strConnect = "server=" + txtServer.Text + ";uid=" + txtUsername.Text + ";pwd=" + txtPassword.Text + ";database=" + txtDatabase.Text;
try
{
if (txtServer.TextLength <= 0 || txtUsername.TextLength <= 0 || txtDatabase.TextLength <= 0)
{
MessageBox.Show("You have an empty database connection field. Please supply a valid value.");
return;
}
Conn = new MySqlConnection(strConnect);
Conn.Open();
if (Conn.State.ToString() != "Open")
{
MessageBox.Show("Could not open database connection");
return;
}
btnDisconnect.Enabled = true;
btnConnect.Enabled = false;
btnLoadData.Enabled = true;
btnLoadClients.Enabled = true;
// btnSubmitClient.Enabled = true;
}
catch (Exception ex) // catch on general exceptions, not specific
{
MessageBox.Show(ex.Message);
return;
}
}
private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
{
if (Conn != null)
{
Conn.Close();
}
}
private void btnDisconnect_Click(object sender, EventArgs e)
{
try
{
Conn.Close();
Conn = null;
btnDisconnect.Enabled = false;
btnConnect.Enabled = true;
btnLoadData.Enabled = false;
btnLoadClients.Enabled = false;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
}
private void btnLoadData_Click(object sender, EventArgs e)
{
try
{
string CmdString = "SELECT * FROM t_receipients";
MySqlDataAdapter sda = new MySqlDataAdapter(CmdString, Conn);
DataSet ds = new DataSet();
sda.Fill(ds);
dataGridView1.DataSource = ds.Tables[0].DefaultView;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
}
private void btnLoadClients_Click(object sender, EventArgs e)
{
try
{
string CmdString = "SELECT * FROM t_clients";
MySqlDataAdapter sda = new MySqlDataAdapter(CmdString, Conn);
DataSet ds = new DataSet();
sda.Fill(ds);
dataGridView1.DataSource = ds.Tables[0].DefaultView;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
}
After series of trials and error, i finally found what i was looking for, thus being able to update database from datagridview below is my worked around code which works 100% hope it helps someone in future, and thanks #RageComplex for helping out, but one more thing does anyone know how to implement that i mean instead of hitting the enter button to take changes in the datagridview you rather click on a button ty
private void dataGridView1_RowValidated(object sender, DataGridViewCellEventArgs e)
{
try
{
DataTable changes = ((DataTable)dataGridView1.DataSource).GetChanges();
if (changes != null)
{
MySqlCommandBuilder mcb = new MySqlCommandBuilder(mySqlDataAdapter);
mySqlDataAdapter.UpdateCommand = mcb.GetUpdateCommand();
mySqlDataAdapter.Update(changes);
((DataTable)dataGridView1.DataSource).AcceptChanges();
MessageBox.Show("Cell Updated");
return;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
You are not updateing your changes to the database. While you keep your connection open doesn't mean that this will automatically update your data.
First of all, don't keep your connection open. In your app you have a connect button which is good for testing but not for really keeping the connection open, not with databases in my opinion.
The way you load data is correct.
You give the datagridview an DataSource which is a table from your DataSet. So changes made in the datagridview ARE saved to your DataSet but not to your database.
This is how you update your database
public void UpdateTable(DataSet ds)
{
using (MySqlConnection connect = new MySqlConnection(ConnString))
{
connect.Open();
MySqlDataAdapter adapt = new MySqlDataAdapter();
MySqlCommandBuilder commbuilder = new MySqlCommandBuilder(adapt);
adapt.SelectCommand = new MySqlCommand("SELECT * FROM t_receipients", connect);
adapt.Update(ds.Tables[0]);
}
}
Make sure, before you Update your database, you use datagridview1.EndEdit()
Also, you using, this will ensure a connection is closed again after completing that code, best is to always have it in a try-except.
You had struggles with connecting the database as it appears to be in the commends.
I've also forgot to include MySqlDataAdapter above, I used an adapter globally in that case.
I didn't want to report this question as duplicated, but now it kinda does look like this answer.
I would like to give code which I have tested in my application.I used it for button click event.
private void button3_Click(object sender, EventArgs e)
{
string StrQuery;
try
{
string MyConnection2 = "server=localhost;user id=root;password=;database=k";
using (MySqlConnection conn = new MySqlConnection(MyConnection2))
{
using (MySqlCommand comm = new MySqlCommand())
{
comm.Connection = conn;
conn.Open();
for (int i = 0; i < dataGridView3.Rows.Count; i++)
{
StrQuery = #"update s set Quantity='" + dataGridView3.Rows[i].Cells["Quantity"].Value.ToString() + "' where No='" + dataGridView3.Rows[i].Cells["Item No"].Value.ToString() + "';";
comm.CommandText = StrQuery;
comm.ExecuteNonQuery();
}
}
}
}
catch
{
}
}
I think it may help you

Categories

Resources