use connection with different forms c# - c#

I have a form say form1 in C# the user has to put database name username password in the textboxes of form1. Once the connection is established form2 will open which will display data with predefined sqls. Also additional forms are needed to use the same connection string.How can i achieve this.
I am using ODAC to connect to oracle database.
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 Oracle.DataAccess.Client;
using Oracle.DataAccess.Types;
namespace Sparrow1
{
public partial class connectform : Form
{
public connectform()
{
InitializeComponent();
}
private OracleConnection conn = new OracleConnection();
private void button1_Click(object sender, EventArgs e)
{
conn.ConnectionString = "User Id=" + username.Text +
";Password=" + password.Text +
";Data Source=" + dataSource.Text + ";";
try
{
conn.Open();
button1.Enabled = false;
statuslabel.Text = "Success";
this.Hide();
overviewform oviewform = new overviewform();
oviewform.Show();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
statuslabel.Text = "Failed";
}
finally
{
conn.Dispose();
}
}
}
}

create a public static string variable named connectionString in Form1.cs
public static string connectionString
get its value from other forms by Form1.connectionString;
Form1.connectionString;

Related

i have created a login page on c# and i need to print welcome to my page when i enter username and password. How is it possible?

i have created a login page on c# and i need to print welcome to my page when i enter username and password. How is it possible?
This is the code currently
I want when a user is authorized I want to display a welcome message on main page
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 WindowsFormsApp2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
}
private void button2_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\NETCOM\OneDrive\Documents\Data.mdf;Integrated Security=True;Connect Timeout=30");
SqlDataAdapter sda = new SqlDataAdapter("Select Count (*) From Login where Username ='" + textBox1.Text + "' and Password ='" + textBox2.Text + "'", con);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows[0][0].ToString() == "1")
{
this.Hide();
Main ss = new Main();
ss.("Welcome to my page");
ss.Show();
}
else
{
MessageBox.Show(" Please check your username and password ");
}
}
}
}
You need to have create a constructor over load in your main page. By which you can send welcome message in main page
Main ss = new Main("Welcome to my page");
ss.Show();
public partial class Main: Form
{
public Main(string msg="")
{
//declare a label in main from to show message
Label label1=new Label();
label1.Text=msg;
}
}

Search value in dataGridview1, Form1 by entering the value in

I am trying to search a value located on dataGridView1, Form1 by entering the value in textbox in Form2.DataGridView1 is set to load data from a .xls file.
I know there is some code missing in Form1 and Form2 in order to perform this task, that is because i am new to Visual Studio and C# code.
Thank you very much for your help :)
This is code located in Form1:
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 Plan_de_lucru
{
public partial class frPlanDeLucru : Form
{
public frPlanDeLucru()
{
InitializeComponent();
}
private void TextBox1_TextChanged(object sender, EventArgs e)
{
}
private void ctrlLoad_Click(object sender, EventArgs e)
{
string constr = "Provider = MicroSoft.Jet.OLEDB.4.0; Data Source=" + TextBox1.Text + "; Extended Properties =\"Excel 8.0; HDR=Yes;\";";
OleDbConnection con = new OleDbConnection(constr);
OleDbDataAdapter sda = new OleDbDataAdapter("Select * From [" + textBox2.Text + "$]", con);
DataTable dt = new DataTable();
sda.Fill(dt);
dataGridView1.DataSource = dt;
new Form2().Show();
this.Show();
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
}
}
This is the code located in Form2:
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 Plan_de_lucru
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void search_button_Click(object sender, EventArgs e)
{
String str = "select * from searchBox where ( Name like '%' + #search + '%')";
BindingSource bs = new BindingSource();
bs.DataSource = dataGridView1.DataSource;
bs.Parameters.Add("#search",)
}
}
}

How can i create MySqlCommand when i put my MySqlConnection in other class and call it from my other form

Good Programmers. Can anyone help me in c#. How can i call this class from my other form whenever i want to insert or execute any queries.
Here is my Class named DBConnection:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
namespace WindowsFormsApplication2
{
class DBConnector
{
private MySqlConnection con;
private String server;
private String db;
private String uid;
private String password;
public DBConnector()
{
Initialize();
}
private void Initialize()
{
server = "localhost";
db = "test";
uid = "root";
password = "";
String connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" +
db + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
con = new MySqlConnection(connectionString);
}
public void DatabaseConnector()
{
server = "localhost";
db = "test";
uid = "root";
password = "";
String connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" +
db + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
con = new MySqlConnection(connectionString);
}
public void OpenCon()
{
con.Open();
}
public void CloseCon()
{
con.Close();
}
}
}
Here is my Form Button Class whenever i press the button . Then it will query. My Problem is how can i call the con = new MySqlConnection(connectionString); to create MySqlCommand. Please help. i was being confused.
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 WindowsFormsApplication2
{
public partial class FrmAdd : Form
{
public FrmAdd()
{
InitializeComponent();
}
private void FrmAdd_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
var mycon = new DBConnector();
try
{
mycon.OpenCon();
MessageBox.Show("Well done!");
}
catch (MySqlException ex)
{
MessageBox.Show("You failed!" + ex.Message);
}
string query = "INSERT INTO info values (1,'John','Mac','P',21)";
}
}
}
In order to access the MySqlConnection object in another class, you need to mark the DbConnector class as internal or public, i.e. it should become:
public class DbConnector{
...
}
You also need to set the access modifier on the property itself and add a getter like so:
public MySqlConnection con { get; }
Then, in FrmAdd after you instantiate DbConnector you can use the database object like mycon.con.SomeMethod().
Also, why do you have two methods DatabaseConnector() and Initialize() if they do the same thing?

Connecting c#.net To phpmyadmin database(MysqL)

I have .NET program written in C# that connects to my website's phpmyadmin which is in cpanel. My problem is that when I'm at the office I can connect to my phpmyadmin server, but when i'm, for example in my house, I can not connect to the server.
I've already included my ISP (www.whatismyip.com/www.speedtest.net) IP in my remoteMySQL in cpanel, but for some reason it only works at the office. Do you think that maybe it is because they are the one hosting the website that I'm connecting to?
My Connection is something like this:
string connection = "SERVER=MyWebsite.com; Database=databse_pcc; Uid=mywebuser; Pwd=password;";
con9.Open();
MySqlCommand cmd9 = new MySqlCommand("Select * from biometrics_tbl LIMIT 1", con9);
cmd9.CommandType = CommandType.Text;
cmd9.Connection = con9;
MySqlDataReader rdr9 = cmd9.ExecuteReader();
while (rdr9.Read())
{
MessageBox.Show(rdr9.GetString(2));
}
con9.Close();
Note this style of connection is working only at the office :(
First off, you're connecting to a database server, namely MySQL not PHPMyAdmin which is a web client for MySQL.
Second assuming what you've said is correct and you have in fact allowed your IP to login to the MySQL database using the login provided, you'll still need to make sure your company allows remote MySQL connections (not likely if they value security).
using MySql.Data.MySqlClient;
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 WindowsFormsApp3
{
public partial class Form1: Form
{
MySqlConnection conn = new MySqlConnection(#"Data Source = localhost;port=3306;Initial Catalog=loginandregister; User Id=root;password=''");
public Form1()
{
InitializeComponent();
}
bool _regiter()
{
int retval = 0;
try
{
string SQLS = string.Empty;
SQLS += "INSERT tb_user SET ";
SQLS += "fullname='" + textBox1.Text + "'";
SQLS += ",user='" + textBox2.Text + "'";
SQLS += ",password='" + textBox3.Text + "'";
conn.Open();
using (MySqlCommand com = new MySqlCommand(SQLS, conn))
{
retval = com.ExecuteNonQuery();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally { conn.Close(); }
return retval > 0;
}
private void button1_Click(object sender, EventArgs e)
{
_regiter();
MessageBox.Show("Register Success");
Form2 oRegisterrr = new Form2();
oRegisterrr.ShowDialog();
this.Close();
}
}
}
using MySql.Data.MySqlClient;
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 WindowsFormsApp3
{
public partial class Form2 : Form
{
MySqlConnection conn = new MySqlConnection(#"Data Source = localhost;port=3306;Initial Catalog=loginandregister; User Id=root;password=''");
public Form2()
{
InitializeComponent();
}
private void LoginProcess()
{
if (login(textBox1.Text, textBox2.Text))
{
MessageBox.Show("Welcome " + textBox1.Text);
this.Hide();
//Form_Menu oFormMenu = new Form_Menu();
// oFormMenu.ShowDialog();
this.Close();
}
else
{
MessageBox.Show("Login Fail");
}
}
private Boolean login(string sUsername, string sPassword)
{
string SQL = "SELECT user,password FROM tb_user";
conn.Open();
MySqlCommand cmd = new MySqlCommand(SQL, conn);
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
if ((sUsername == reader.GetString(0)) && (sPassword == reader.GetString(1)))
{
conn.Close();
return true;
}
}
conn.Close();
return false;
}
private void button1_Click(object sender, EventArgs e)
{
LoginProcess();
}
}
}

Arithmetic operation resulted in an overflow error c#

Hello i'm using c# to build an application to connect to remote mysql server.
Here 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 login
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (tryLogin(textBox1.Text, textBox2.Text) == true)
{
MessageBox.Show("Authed!");
}
else
{
MessageBox.Show("Auth Failure.");
}
}
public bool tryLogin(string username, string password)
{
MySqlConnection con = new MySqlConnection("host=myhostname;user=myusername;password=mypassword;database=mydatabase;");
MySqlCommand cmd = new MySqlCommand("SELECT * FROM test WHERE username = '" + username + "' AND password = '" + password + "';");
cmd.Connection = con;
con.Open();
MySqlDataReader reader = cmd.ExecuteReader();
if (reader.Read() != false)
{
if (reader.IsDBNull(0) == true)
{
cmd.Connection.Close();
reader.Dispose();
cmd.Dispose();
return false;
}
else
{
cmd.Connection.Close();
reader.Dispose();
cmd.Dispose();
return true;
}
}
else
{
return false;
}
}
}
}
It shows the following error:
"OverflowException was unhandled
Arithmetic operation resulted in an overflow "
I'm not using any arithmetic operations here. Any help ???
Check the test table in mysql server.
Make sure that all fields have valid values in the username and password columns.
UPDATE
try to include the option "Use Pipe=false;",with your connection string.Then it will opens the connection just fine.
I hope this will help to you.

Categories

Resources