First of all I'm new with C# and Visual Studio.
I followed a tutorial on how to populate DataGridView from MySql table.
I checked multiple times for copying mistakes but I didn't find any.
The code is this:
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 DataGridMain
{
public partial class Form1 : Form
{
private string server;
private string database;
private string uid;
private string password;
private MySqlConnection connection;
private MySqlDataAdapter mySqlDataAdapter;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
server = "localhost";
database = "elphoapp";
uid = "username";
password = "password";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
if (this.OpenConnection() == true)
{
mySqlDataAdapter = new MySqlDataAdapter("select * from users", connection);
DataSet DS = new DataSet();
mySqlDataAdapter.Fill(DS);
dataGridView1.DataSource = DS.Tables[0];
this.CloseConnection();
}
}
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;
default:
MessageBox.Show(ex.Message);
break;
}
return false;
}
}
private bool CloseConnection()
{
try
{
connection.Close();
return true;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
}
}
I can't seem to find a problem and no error is displaying.
As you are new to Visual Studio, my advice is the first thing you must learn is debugging. It will save you a lot of times. In this case, put a breakpoint in your form_load and run the code step by step. You can that way see what is happening, and inspect all the variables. I'm saying this because i can't see any error in your code, so probably you are not even connecting to the database. Debugging your code you may see why
Ok i figured it out!
All i had to do was to call Form1_Load from inside the Form1() function.
Everything seems to be working fine at the moment.
Thanks, C# is full of damn surprises....
Related
I am trying to add an ADO.net Entity Data Model in my project. I am having accdb file. When I am trying to add this in the data source, unable to get the OLEDB provider on the list.
I am already having Microsoft Access engine provider. What I am missing on my system. Please help me. Any help would be greatly appreciated.
I am not sure if this will give you the connection as a drop down item, but these code samples show you a couple ways to connect to MS Access.
using System;
using System.Windows.Forms;
using System.Data;
using System.Data.OleDb;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
OleDbConnection oledbCnn ;
OleDbDataAdapter oledbAdapter ;
DataSet ds = new DataSet();
string sql = null;
int i = 0;
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;";
sql = "Your SQL Statement Here like Select * from product";
oledbCnn = new OleDbConnection(connetionString);
try
{
oledbCnn.Open();
oledbAdapter = new OleDbDataAdapter(sql, oledbCnn);
oledbAdapter.Fill(ds);
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
MessageBox.Show(ds.Tables[0].Rows[i].ItemArray[0] + " -- " + ds.Tables[0].Rows[i].ItemArray[1]);
}
oledbAdapter.Dispose();
oledbCnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
}
}
OR
using System;
using System.Windows.Forms;
using System.Data.OleDb;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
OleDbConnection oledbCnn ;
OleDbCommand oledbCmd ;
string sql = null;
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;";
sql = "Your SQL Statement Here like Select * from product";
oledbCnn = new OleDbConnection(connetionString);
try
{
oledbCnn.Open();
oledbCmd = new OleDbCommand(sql, oledbCnn);
OleDbDataReader oledbReader = oledbCmd.ExecuteReader();
while (oledbReader.Read ())
{
MessageBox.Show(oledbReader.GetValue(0) + " - " + oledbReader.GetValue(1) + " - " + oledbReader.GetValue(2));
}
oledbReader.Close();
oledbCmd.Dispose();
oledbCnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
pwnew.PasswordChar = '*';
pwtxt.PasswordChar = '*';
signup.Visible = false;
}
private void signupbtn_Click(object sender, EventArgs e)
{
signup.Visible = true;
}
private void button1_Click(object sender, EventArgs e)
{
if (unnew.Text != null && pwnew.Text != null)
{
try
{
Connect obj = new Connect();
obj.conn.ConnectionString = obj.locate;
obj.conn.Open();
string insertuser = "insert into userTable('" + unnew.Text + "', '" + pwnew.Text + "')";
obj.cmd.Connection = obj.conn;
obj.cmd.CommandText = insertuser;
obj.conn.Close();
MessageBox.Show("Signup has been completed");
signup.Visible = false;
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
}
else
{
MessageBox.Show("Error");
}
}
private void loginbtn_Click(object sender, EventArgs e)
{
if (untxt.Text != null && pwtxt.Text != null)
{
try
{
Connect obj = new Connect();
obj.conn.ConnectionString = obj.locate;
obj.conn.Open();
SqlDataAdapter adapter = new SqlDataAdapter("SELECT COUNT (*) FROM userTable where username = '" + untxt.Text + "' and password '" + pwtxt.Text + "'", obj.conn);
DataTable dt = new DataTable();
adapter.Fill(dt);
if (dt.Rows[0][0].ToString() == "1")
{
Form2 meLoad = new Form2();
meLoad.Visible = true;
this.Hide();
MessageBox.Show("Success");
}
else
{
MessageBox.Show("Username or Password is incorrect");
}
obj.conn.Close();
MessageBox.Show("Successfully Login");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
else
{
MessageBox.Show("No empty fields are allowed");
}
{
}
}
}
}
Hi, I am completely new to c#, im having this error whenever i click sign up. It tells me to check the line 44 which is
try
{
Connect obj = new Connect();
obj.conn.ConnectionString = obj.locate;
obj.conn.Open();
string insertuser = "insert into userTable('" + unnew.Text + "', '" + pwnew.Text + "')";
obj.cmd.Connection = obj.conn;
obj.cmd.CommandText = insertuser;
obj.conn.Close();
MessageBox.Show("Signup has been completed");
signup.Visible = false;
}
Im a student, adn dont have enough background in programming, i'd appreciate someone's help. I really want to learn this programming language, and im currentlty having troubles.enter image description here Thank u so much.
I use this for Connection
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
namespace WindowsFormsApp1
{
class Connect
{
public SqlConnection conn = new SqlConnection();
public SqlCommand cmd = new SqlCommand();
public string locate = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename='C:\Users\hp\source\repos\WindowsFormsApp1\WindowsFormsApp1\UserDB.mdf;'Integrated Security=True";
}
}
It seems something is breaking to connect your database.
Please double check your connection string,If you need help for connection string, you may visit https://www.connectionstrings.com/
This tutorial may be helpful for you to connect database using c#.
https://www.guru99.com/c-sharp-access-database.html
i want to create a class that handles all my Database-Stuff so i started with this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
namespace Server
{
class Database
{
private MySqlConnection connection;
private string server;
private string database;
private string uid;
private string password;
public Database()
{
server = "localhost";
database = "mydb";
uid = "root";
password = string.Empty;
string connectionString = "SERVER=" + server + ";" + "DATABASE = " + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
}
public bool OpenConnection()
{
try
{
connection.Open();
return true;
} catch(MySqlException e)
{
switch (e.Number)
{
case 0:
// Cannot connect to server
break;
case 1045:
// Invalid username / password
break;
}
return false;
}
}
private bool CloseConnection()
{
try
{
connection.Close();
return true;
} catch(MySqlException e)
{
// ex.message
return false;
}
}
}
}
But i don't know how i should handle inserts, updates and selects that they are dynamic to usw. I want to insert strings, dates and integers.. what is the best solution to create an insert, update and select function that can be used from everywhere?
You have two options.
A) Make methods for every possible Select/Insert/Update/Delete within the Database class
or
B) Make a generic Select and Insert/Update/Delete method which takes an sql query (string) and array/list of SqlParameter and then this data is passed to the functions from another class
The Select method should return a DataTable and the Insert/Update/Delete method could return a value to determine success
Personally I much prefer option B.
I have got some code: THE FULL
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using MySql.Data.MySqlClient;
namespace mysql
{
/// <summary>
/// Interaction logic for LoginPage.xaml
/// </summary>
public partial class LoginPage : Page
{
private string conn;
private MySqlConnection connect;
AdminPage ap = new AdminPage();
public LoginPage()
{
InitializeComponent();
}
private void db_connection()
{
try
{
conn = "Server=localhost;Database=student;Uid=root;Pwd=admin;";
connect = new MySqlConnection(conn);
connect.Open();
}
catch (MySqlException e)
{
throw;
}
}
private bool validate_login(string user, string pass)
{
db_connection();
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = "Select * from student.admins where username=#user and password=#pass";
cmd.Parameters.AddWithValue("#user", user);
cmd.Parameters.AddWithValue("#pass", pass);
cmd.Connection = connect;
MySqlDataReader login = cmd.ExecuteReader();
if (login.Read())
{
connect.Close();
return true;
}
else
{
connect.Close();
return false;
}
}
private void btn_login_Click(object sender, RoutedEventArgs e)
{
string user = txt_admin_name.Text;
string pass = txt_admin_passwd.Password;
if (user == "" || pass == "")
{
//MessageBox.Show("Empty Fields Detected ! Please fill up all the fields");
txt_errormessage.Text = "Empty Fields Detected! Please fill up all the fields!";
return;
}
bool r = validate_login(user, pass);
if (r)
{
//MessageBox.Show("Correct Login Credentials.\n You will be taken the Admin Page!");
this.NavigationService.Navigate(ap);
}
else
//MessageBox.Show("Incorrect Login Credentials");
txt_errormessage.Text = "Incorrect Login Credentials!";
}
}
}
So i need to some error handling: Check the server connection, and check existence of database. I would like to write MessageBox.
I tried but...
"Additional information: Connection must be valid and open."
Thanks in advance!
As soon as you validate the login, you are closing the connection:
if (login.Read())
{
connect.Close();
return true;
}
else
{
connect.Close();
return false;
}
Either leave the connection open, or reopen it. Most people leave it open for speed and simplicity.
When you need to use a connection to a database for every kind of task it is always a good practice to follow the pattern CREATE/OPEN/USE/CLOSE/DISPOSE
So your db_connection code should return the connection created and opened and never use a global variable to keep the connection instance.
private MySqlConnection db_connection()
{
try
{
conn = "Server=localhost;Database=student;Uid=root;Pwd=admin;";
MySqlConnection cnn = new MySqlConnection(conn);
cnn.Open();
return cnn;
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
switch (ex.Number)
{
case 0: MessageBox.Show("Cannot connect to server!"); break;
}
retur null;
}
}
Now the code that want to use your method could be written in a more resource friendly way
private bool validate_login(string user, string pass)
{
using(MySqlConnection cnn = db_connection())
using(MySqlCommand cmd = new cnn.CreateCommand())
{
cmd.CommandText = ".....";
cmd.Parameters.AddWithValue("#user", user);
cmd.Parameters.AddWithValue("#pass", pass);
using(MySqlDataReader login = cmd.ExecuteReader())
return login.HasRows;
}
}
No need to close explicitly the connection because the exit from the using block automatically closes the connection and disposes the instance freeing the resources kept by the connection both locally and on the server.
Of course, when you need to query again the database the same pattern should be used.
You need to tell your command about your connection object. Add the connection parameter to command
MySqlCommand cmd = new MySqlCommand(connect );
I am working with C# (visual studio 2012 professional) and Mysql . I trying to create a login form, where a user needs to insert the username and password:
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 Login_Menu : Form
{
private MySqlConnection connection = new MySqlConnection();
public Login_Menu()
{
InitializeComponent();
TextPassword.PasswordChar = '*';
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void btn_Login_Click(object sender, EventArgs e)
{
try
{
string connectionString = "datasource = localhost; port = 3306; username = root; password = Mypass;";
using(MySqlConnection myConn = new MySqlConnection(connectionString))
using(MySqlCommand selectCommand = new MySqlCommand())
{
selectCommand.CommandText = ("SELECT COUNT(1) FROM dark_heresy.users WHERE users_=#User and password_=#Password;");
selectCommand.Connection = myConn;
selectCommand.Parameters.Add(new MySqlParameter("User", MySqlDbType.VarChar).Value = TextUserName.Text);
selectCommand.Parameters.Add(new MySqlParameter("Password", MySqlDbType.VarChar).Value = TextPassword.Text);
myConn.Open();
var ret = selectCommand.ExecuteScalar();
var count = Convert.ToInt32(ret);
if (count == 1)
{
this.Hide();
Menu mn = new Menu();
mn.ShowDialog();
}
else if (count > 1)
{
MessageBox.Show("Duplication of Username and Password... Access Denied");
}
else
{
MessageBox.Show("Incorrect Username and/or Password");
}
}
}
catch (Exception exp)
{
MessageBox.Show("Error: \r\n" + exp);
}
}
}
}
I don't get any syntax errors, but when i run this code i recieve this error:
MySql.Data.MySqlClient.MySqlException(0x80004005):
Only MySqlParameter objects may be stored at MySql.Data.MySqlClient.MySqlParameterCollection.Add(Object value)
at Dark_Heresy.Login_Menu.btn_Login_Click(Object sender, EventArgs e)
I know for security reason is it a better idea to use mysql.user table instead of dark_heresy.users table for user check, but right now is for testing purpose.
What is wrong with the code?
it says there is an error in line 39
I think your parameter syntax is wrong.
= operator returns the right side value also instead of just assigning. That's why;
new MySqlParameter("User", MySqlDbType.VarChar).Value = TextUserName.Text;
expression returns TextUserName.Text as a value and your parameter part will be like;
selectCommand.Parameters.Add(TextUserName.Text);
The right syntax seems;
selectCommand.Parameters.Add("#User", MySqlDbType.VarChar).Value = TextUserName.Text;
selectCommand.Parameters.Add("#Password", MySqlDbType.VarChar).Value = TextPassword.Text;
And please, don't store your passwords as a plain text.
Read: Best way to store password in database