Connecting to a Database through a separate form C# - c#

I'm creating a program that links to a database. On the main form when the user clicks a button 'Connect to Database', another form loads for the user to input the log-in details (server to connect to, username, and password). However, the connection isn't working for some reason. The error given is "Fill: SelectCommand.Connection property has not been initialized."
Here is my code so far:
public void connectDB_Click(object sender, EventArgs e)
{
DatabaseConnection dbConn = new DatabaseConnection();
if (dbConn.ShowDialog() == DialogResult.OK)
{
SqlConnectionStringBuilder connection = new SqlConnectionStringBuilder();
connection.DataSource = DatabaseConnection.dbNameText;
connection.UserID = DatabaseConnection.usernameText;
connection.Password = DatabaseConnection.passwordText;
SqlConnection con = new SqlConnection(connection.ToString());
using (SqlCommand command = new SqlCommand("Select name FROM sys.databases;"))
{
try
{
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = command;
DataTable table = new DataTable();
sda.Fill(table);
BindingSource source = new BindingSource();
source.DataSource = table;
dataGridDataBase.DataSource = source;
sda.Update(table);
this.dataGridDataBase.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; //showing data onto the data grid view
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
Above is the code in the master class; the main form. Below is the code in the log-in form.
public partial class DatabaseConnection : Form
{
public static string dbNameText;
public static string usernameText;
public static string passwordText;
public bool buttonClicked = false;
public DatabaseConnection()
{
InitializeComponent();
password.PasswordChar = '•';
}
public void connectButton_Click(object sender, EventArgs e)
{
buttonClicked = true;
dbNameText = dbName.Text;
usernameText = username.Text;
passwordText = password.Text;
}
}
Any ideas, help, or solutions please?

You have to give connection to the command:
using (SqlCommand command = new SqlCommand("Select name FROM sys.databases;", con))
{
...
}

Related

Why I can't show datas

When I run the code, the required information does not appear in the gridbox.
{
public partial class fatura : Form
{
SqlConnection baglanti = new SqlConnection("Server=localhost;Database=master; Trusted_Connection=True");
DataTable tablo;
araba_ekleme araba_ekleme = new araba_ekleme();
public fatura()
{
InitializeComponent();
}
public DataTable listele(SqlDataAdapter adtr, string sorgu)
{
tablo = new DataTable();
adtr = new SqlDataAdapter(sorgu, baglanti);
adtr.Fill(tablo);
baglanti.Close();
return tablo;
}
private void onay_bekleyen()
{
string cumle = "declare #tc_no bigint select tc_no,car_plate,total,date,tax from [invoice] WHERE (status=0) AND tc_no=#tc_no";
SqlDataAdapter adtr2 = new SqlDataAdapter();
dg_pending.DataSource = listele(adtr2, cumle);
}
private void onaylanan()
{
string cumle = "declare #tc_no bigint select tc_no,car_plate,total,date,tax from [invoice] WHERE (status=1) AND tc_no=#tc_no";
SqlDataAdapter adtr2 = new SqlDataAdapter();
dg_done.DataSource = listele(adtr2, cumle);
}
private void fatura_Load(object sender, EventArgs e)
{
onay_bekleyen();
onaylanan();
}
}
}
When I run this code it gives an error. string cumle = "select tc_no,car_plate,total,date,tax from [invoice] WHERE (status=0) AND tc_no=#tc_no";
So i used this code block string cumle = "declare #tc_no bigint select tc_no,car_plate,total,date,tax from [invoice] WHERE (status=0) AND tc_no=#tc_no"; and when I run the code, the required information does not appear in the gridbox.
edit (SqlDataAdapter adtr, string sorgu) function like the code below:
1- You don't need to send SqlDataAdapter as input and define it inside the function.
2- You must open the connection.
3- Use using for SqlDataAdapter and SqlConnection so that there is no need to dispose.
4- Use try- catch to catch the error (In the following function, if there is an error, it will be displayed as a meesageBox. You can write error in file, console or anywhere else)
public DataTable listele(string sorgu)
{
DataTable tablo = new DataTable();
using (SqlConnection MyConnnection = new SqlConnection(conString ))
{
using (SqlDataAdapter dataAdapter = new SqlDataAdapter(sorgu, MyConnnection))
{
try
{
MyConnnection.Open();
dataAdapter.Fill(tablo);
}catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
return tablo;
}
define connection string:
public partial class fatura : Form
{
public string conString = "Server=localhost;Database=master; Trusted_Connection=True";
SqlConnection baglanti = new SqlConnection("Server=localhost;Database=master; Trusted_Connection=True");
DataTable tablo;
araba_ekleme araba_ekleme = new araba_ekleme();
...
Call the function as below:
dg_pending.DataSource = listele(cumle);

Sending data after login to other form C#

I just started coding with C# and SQL this week to create a desktop application; after login I want to put the user data who logged in other form # dashboard, but I couldn't find a way to do this. I found a way to create a class and put that user data in it so you can grab; but I am really stuck here.
public void bunifuFlatButton1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=DESKTOP-R3ILNJ7;Initial Catalog=Project2;Integrated Security=True");
String query = "SELECT * FROM USERDB WHERE PRENOM='" + alphaBlendTextBox1.Text + "'AND PASS='" + alphaBlendTextBox2.Text + "'";
SqlDataAdapter sda = new SqlDataAdapter(query, con);
DataTable dtbl = new DataTable();
sda.Fill(dtbl);
if(dtbl.Rows.Count == 1)
{
string name = dtbl.Rows[0]["Nom"].ToString();
this.Hide();
Form1 f1 = new Form1();
f1.ShowDialog();
}
else
MessageBox.Show("mauvais password try again");
}
Modify the constructor of Form1 and when creating object of Form1 also pass the value which you can use in your Form1. Below is sample code of your Form1:
namespace YourNameSpace
{
public partial class Form1 : Form
{
DataTable MyDataTable = new DataTable();
public Form1(DataTable _MyDataTable)
{
InitializeComponent();
MyDataTable = _MyDataTable;
}
}
}
Then change your code to pass your values to this form like below:
if(dtbl.Rows.Count == 1)
{
string name = dtbl.Rows[0]["Nom"].ToString();
this.Hide();
Form1 f1 = new Form1(dtbl);
f1.ShowDialog();
}
else
MessageBox.Show("mauvais password try again");
One way of doing this is to create an Object which contains the data you read from your DB and then pass this into the constructor of your new form.
//This class will store the data from the DB
public class MyClass
{
Public string Name { get; set; }
//Repeat for all fields retrieved from the DB that you require.
public MyClass()
{
}
}
//I changed below to have Using clauses. The way you had it you were not correctly disposing your objects and disconnecting from the DB,
//and you would have memory leaks and other problems later
DataTable dtbl = new DataTable();
using (SqlConnection con = new SqlConnection("Data Source=DESKTOP-R3ILNJ7;Initial Catalog=Project2;Integrated Security=True"))
{
//I Changed this to use Parameters!
//See https://www.dreamincode.net/forums/topic/268104-the-right-way-to-query-a-database-parameterizing-your-sql-queries/
String query = "SELECT * FROM USERDB WHERE PRENOM= #PRENOM AND PASS= #PASS";
using (SqlCommand command = new SqlCommand(query, con))
{
using (SqlDataAdapter sda = new SqlDataAdapter(command))
{
//Check the SQLDbType below is correct for you DB schema!
sda.SelectCommand.Parameters.Add("#PRENOM", SqlDbType.NVarChar).Value = alphaBlendTextBox1.Text;
sda.SelectCommand.Parameters.Add("#PASS", SqlDbType.NVarChar).Value = alphaBlendTextBox2.Text;
sda.Fill(dtbl);
}
}
}
//Declare your class here
MyClass mc = new MyClass();
if(dtbl.Rows.Count == 1)
{
mc.Name = dtbl.Rows[0]["Nom"].ToString();
Form1 f1 = new Form1(mc);
this.Hide();
f1.ShowDialog();
}
else
MessageBox.Show("mauvais password try again");
dtbl = null;
//Now update your Form code and create a new constructor
public partial class Form1 : Form
{
//This is where you will store the incoming data
private MyClass IncomingMyClass { get; set; }
//Change the existing constructor to Private
private Form1()
{
InitializeComponent();
}
//Create a new constructor, which calls the empty (now private) constructor above
public Form1(MyClass myclass): this()
{
this.IncomingMyClass = myclass;
}
....

Close a form from another project when a button was clicked

private void _btnAccept_Click(object sender, EventArgs e)
{
LogInForm.UserOntrip _pnl = new LogInForm.UserOntrip(_FNAME);
_pnl.Show();
_btnAccept.Hide();
_btnCancel.Hide();
button1.Show();
string _query2 = "select DContactno from DriverTbl where DUsername = #USERNAME";
string _query3 = "select VehicleRegitrationNumber from DriverTbl where DUsername = #USERNAME";
SqlConnection _sqlcnn = new SqlConnection("Data Source=MELIODAS;Initial Catalog=WeGo;Integrated Security=True; MultipleActiveResultSets=True ");
_sqlcnn.Open();
try
{
SqlDataReader _reader = null;
SqlCommand _cmd = new SqlCommand("select DFname from DriverTbl where DUsername=#USERNAME", _sqlcnn);
SqlParameter _param = new SqlParameter();
_param.ParameterName = "#USERNAME";
_param.Value = _FNAME;
_cmd.Parameters.Add(_param);
_reader = _cmd.ExecuteReader();
while (_reader.Read())
{
_pnl._txtboxDriverName.Text = _reader.GetString(0);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
using (SqlCommand _sqlcmd = new SqlCommand(_query2, _sqlcnn))
{
try
{
SqlDataReader _reader = null;
SqlParameter _param1 = new SqlParameter();
_param1.ParameterName = "#USERNAME";
_param1.Value = _FNAME;
_sqlcmd.Parameters.Add(_param1);
_reader = _sqlcmd.ExecuteReader();
while (_reader.Read())
{
_pnl._txtboxDContact.Text = _reader.GetString(0);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
_pnl._txtboxOrigin.Text = _txtboxOrigin.Text;
_pnl._txtboxDestination.Text = _txtboxDestination.Text;
using (SqlCommand _sqlcmd = new SqlCommand(_query3, _sqlcnn))
{
try
{
SqlDataReader _reader = null;
SqlParameter _param1 = new SqlParameter();
_param1.ParameterName = "#USERNAME";
_param1.Value = _FNAME;
_sqlcmd.Parameters.Add(_param1);
_reader = _sqlcmd.ExecuteReader();
while (_reader.Read())
{
_pnl._txtboxBodyNum.Text = _reader.GetString(0);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
_pnl._lblPrice.Text = _lblPrice.Text;
_pnl._lblVechType.Text = _lblTransType.Text;
}
private void button1_Click(object sender, EventArgs e)
{
LogInForm.UserOntrip _user = new LogInForm.UserOntrip(_FNAME);
_user.Hide();
Form2 _form2 = new Form2(_FNAME);
_form2.Show();
this.Hide();
}
I want to hide or close the LogInForm.UserOntrip form. The UserOntrip form came form the LogInForm Project and Im running it in the driver side project.
1st: when a form from driverside opens there is an accept and close button if that will be accepted a finish button will appear and the 2 buttons that i refer will be hide.
2nd: if i click the finish button the form that has been opened in the 1st will be closed the same as the current form that is opened in the driverside
what should i add on the code so that if I click the button 2 forms will be closed.
My System is a like an uber.
Thank You

Cannot find table at position 1 error

I have a main form which has an Add Teacher button and an Add subject button which directs them to their respective forms.The add teacher button works perfectly fine but when i click the add subject button it shows error: Cannot find table at position 1.I have been following the same procedure in add subject button as i did in add teacher button .Also I first added tbl_teachers table and then tbl_subjects table in my database ,so technically tbl_teachers should have index 0 right?Also when i click the Data Source section I only see it has only tbl_teachers.How do I update the data source? Thanks in advance.
try
{
SubjectConnect = new DatabaseConnection();
conString = Properties.Settings.Default.teachersConnectionString;
SubjectConnect.connection_string = conString;
SubjectConnect.sql = Properties.Settings.Default.SQL2;
ds = SubjectConnect.GetConnection;
Maxrows = ds.Tables[1].Rows.Count;
}
catch (Exception err)
{
MessageBox.Show(err.Message,"error");
}
class DatabaseConnection
{
private string sql_string;
private string strCon;
SqlDataAdapter da_1;
public string sql
{
set { sql_string = value; }
}
public string connection_string
{
set { strCon = value; }
}
public DataSet GetConnection
{
get { return MyDataset(); }
}
private DataSet MyDataset()
{
SqlConnection con = new SqlConnection(strCon);
con.Open();
da_1 = new SqlDataAdapter(sql_string, con);
DataSet dat_set = new DataSet();
da_1.Fill(dat_set,"Table_data_1");
con.Close();
return dat_set;
}
public void UpdateDatabase(DataSet ds)
{
SqlCommandBuilder cb = new SqlCommandBuilder(da_1);
cb.DataAdapter.Update(ds.Tables[0]);
}
}

Use ContentEditable to Save Into DB With ASP.NET?

I'm trying to create a web page where a user can edit the text and when they are done, they hit save and the new text entered is saved into the database.
I'm not getting any errors in my code, but for some reason, the old text is just being rewritten into the db instead of the new text.
Here is my code-behind:
protected void saveBtn_Click(object sender, EventArgs e)
{
string newName;
string newIntro;
string newEduc;
string newWork;
h1New.Text = h1.Text;
newName = h1New.Text;
newIntro = intro.Text;
newEduc = educ.Text;
newWork = employ.Text;
string connectionInfo = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionInfo))
{
connection.Open();
SqlCommand myCommand = new SqlCommand("UPDATE simpleContent SET userName = #newName, infoContent = #newIntro, educContent = #newEduc, workContent = #newWork WHERE userID = #userName", connection);
try
{
string username = HttpContext.Current.User.Identity.Name;
myCommand.Parameters.AddWithValue("#userName", username.ToString());
myCommand.Parameters.AddWithValue("#newName", newName.ToString());
myCommand.Parameters.AddWithValue("#newIntro", newIntro.ToString());
myCommand.Parameters.AddWithValue("#newEduc", newEduc.ToString());
myCommand.Parameters.AddWithValue("#newWork", newWork.ToString());
myCommand.ExecuteNonQuery();
connection.Close();
}
catch
{
Response.Redirect("http://www.google.co.uk");
}
}
}
I would appreciate any pointers that you may have.
try to put you code in format:
protected void saveBtn_Click(object sender, EventArgs e)
{
// add variables
string connectionInfo = (...)
string commandText = (...)
using (...){
SqlCommand myCommand = (...)
// add parameters
try
{
connection.Open();
myCommand.ExecuteNonQuery();
connection.Close();
}
catch (Exception ex)
{
(...)
}
}

Categories

Resources