I am trying to have c# look to see if the database table equals what i am asking it to equal to open a specific form here is one way i am try doing it
void getsformat()
{
string constring = #"server=host;userid=user;password=pass";
string Query = "select colum from table where callsign= '" + listBox1.SelectedItem + "'";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
while (myReader.Read())
{
string sfName = myReader.GetString("sformat");
}
if (sfName == "stworld")
{
sendtext = textBox1.Text;
Form3 f3 = new Form3();
f3.Location = new Point(this.Top);
f3.ShowDialog();
}
else if (sfName == "seperate")
{
sendtext = textBox1.Text;
Form3 f4 = new Form3();
f4.Location = new Point(this.Top);
f4.ShowDialog();
}
conDataBase.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
and the othere way with the "while myreader "end quote after the "if" statement
void getsformat()
{
string constring = #"server=host;userid=user;password=pass";
string Query = "select colum from table where callsign= '" + listBox1.SelectedItem + "'";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
while (myReader.Read())
{
string sfName = myReader.GetString("sformat");
if (sfName == "stworld")
{
sendtext = textBox1.Text;
Form3 f3 = new Form3();
f3.Location = new Point(this.Top);
f3.ShowDialog();
}
else if (sfName == "seperate")
{
sendtext = textBox1.Text;
Form3 f4 = new Form3();
f4.Location = new Point(this.Top);
f4.ShowDialog();
}
}
conDataBase.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
i cannot get either of them to work . Any help would be apreciated
thank you in advanced
It doesn't look like you have the connection string setup properly.
This:
string constring = #"server=host;userid=user;password=pass";
Should have the relevant info
string constring = #"server=localhost\SQL2008;userid=myusername;password=mypass";
In your select statement change it to
listbox1.selecteditem.tostring();
Related
I am getting error:
Connection must be valid and Open c# Winform.
Here is my code, can anyone please help what is wrong in the below code?
public void NameSearch()
{
listBox1.Visible = true;
try
{
String constring = "datasource=localhost;port=3306;Initial Catalog = 'svms'; username = svms; password =svms2016CPU";
string query = "select * from studentinformation where StudLname='" + metroTextBox1.Text + "'";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(query, conDataBase);
MySqlDataReader myReader = cmdDataBase.ExecuteReader();
while (myReader.Read())
{
string Lname = myReader.GetString(myReader.GetOrdinal("StudLname"));
string Fname = myReader.GetString(myReader.GetOrdinal("StudFname"));
string Mname = myReader.GetString(myReader.GetOrdinal("StudMname"));
string nameResult = Lname + ", " + Fname + " " + Mname;
listBox1.Items.Add(nameResult);
}
conDataBase.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
You haven't open connection before use it, Open connection
conDataBase.Open();
Open the conn before read:
conDataBase.Open();
Like:
String constring = "datasource=localhost;port=3306;Initial Catalog = 'svms'; username = svms; password =svms2016CPU";
string query = "select * from studentinformation where StudLname='" + metroTextBox1.Text + "'";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(query, conDataBase);
//
conDataBase.Open();
//
MySqlDataReader myReader = cmdDataBase.ExecuteReader();
I've created a database using mysql, on my form1 there are two textboxes username and password and a login button. My program retrieves information from database and if the data s matches it logs in else an messagebox should pop up telling that username of password is wrong ( which it doesn't show)
before posting the code:
I've declared: the following
public int logid;
public int loginid(strign name) // to set logid the id of the user
public void loginfun(); // checks the data and logs in if id and password matches, else should give an error message.
and my code is as follows:
public int loginid(string name)
{
string conString = "Server=localhost;Database=ozturk;Uid=_____;pwd=_____";
MySqlConnection mcon = new MySqlConnection(conString);
string getid = "SELECT username,id from ozturk.admin WHERE username='" + name + "'";
MySqlCommand cmd = new MySqlCommand(getid, mcon);
MySqlDataReader myReader;
mcon.Open();
myReader = cmd.ExecuteReader();
while (myReader.Read())
{
if (myReader["username"].ToString() == name)
{
return Convert.ToInt32(myReader["id"].ToString());
}
}
return 0;
}
public void loginfun()
{
string conString ="Server=localhost;Database=ozturk;Uid=_____;pwd=_____";
MySqlConnection mcon = new MySqlConnection(conString);
string selectCommand = "SELECT * FROM ozturk.admin";
MySqlCommand cmd = new MySqlCommand(selectCommand,mcon);
MySqlDataReader myReader;
mcon.Open();
myReader = cmd.ExecuteReader();
while (myReader.Read())
{
try
{
if (myReader["username"].ToString() == txtuserid.Text && myReader["password"].ToString() == txtpassword.Text)
{
// set logid to userid
logid = loginid(myReader["username"].ToString());
string updateCommand = "UPDATE ozturk.admin SET status = 'on' WHERE id='" + logid + "' ";
MySqlConnection newcon = new MySqlConnection(conString);
MySqlCommand cmd2 = new MySqlCommand(updateCommand, newcon);
MySqlDataReader myReader2;
newcon.Open();
myReader2 = cmd2.ExecuteReader();
Anasayfa anasayf = new Anasayfa();
anasayf.Show();
this.Hide();
}
}
catch (Exception)
{
MessageBox.Show("Username or Password is incorrect");
throw;
}
}
}
The problem is: My program logs in and opens the other form if the username and the password is correct however it doesn't do anything if the username or password is wrong, What am I missing here? any help is appreciated
Thanks
I've solved the problem, here is what I've done: I've changed my login function from void to bool: here is the latest code:
public bool loginfun()
{
string conString ="Server=localhost;Database=ozturk;Uid=_____;pwd=_____";
MySqlConnection mcon = new MySqlConnection(conString);
string selectCommand = "SELECT * FROM ozturk.admin";
MySqlCommand cmd = new MySqlCommand(selectCommand,mcon);
MySqlDataReader myReader;
mcon.Open();
myReader = cmd.ExecuteReader();
while (myReader.Read())
{
try
{
if (myReader["username"].ToString() == txtuserid.Text && myReader["password"].ToString() == txtpassword.Text)
{
// giriş yapan kişinin id si
logid = loginid(myReader["username"].ToString());
string updateCommand = "UPDATE ozturk.admin SET status = 'on' WHERE id='" + logid + "' ";
MySqlConnection newcon = new MySqlConnection(conString);
MySqlCommand cmd2 = new MySqlCommand(updateCommand, newcon);
MySqlDataReader myReader2;
newcon.Open();
myReader2 = cmd2.ExecuteReader();
return true;
}
}
catch (Exception ee)
{
MessageBox.Show(ee.Message);
throw;
}
}
return false;
}
and inside the login button the code is as follows:
if (loginfun() == true)
{
Anasayfa anasayf = new Anasayfa();
anasayf.Show();
this.Hide();
}
else
{
MessageBox.Show("Username or Password is incorrect");
}
Thank you everyone for the tips
This is your code:
bool flag = false;
while (myReader.Read())
{
try
{
if (myReader["username"].ToString() == txtuserid.Text && myReader["password"].ToString() == txtpassword.Text)
{
// set the flag to true, is credentials match and break from the loop
flag = true;
break;
// set logid to userid
logid = loginid(myReader["username"].ToString());
string updateCommand = "UPDATE ozturk.admin SET status = 'on' WHERE id='" + logid + "' ";
MySqlConnection newcon = new MySqlConnection(conString);
MySqlCommand cmd2 = new MySqlCommand(updateCommand, newcon);
MySqlDataReader myReader2;
newcon.Open();
myReader2 = cmd2.ExecuteReader();
Anasayfa anasayf = new Anasayfa();
anasayf.Show();
this.Hide();
}
}
catch (Exception)
{
MessageBox.Show("Username or Password is incorrect");
throw;
}
}
if(!flag)
{
MessageBox.Show("Username or Password is incorrect");
}
I have created comboBox and filled with one column, after I choose item from the combobox I would like to show other column in the textboxs so I wrote code to make it happen but what if I want to choose column from another table I mean I would like to show couple of columns from two different table in the textbox when I hit the combobox
Here is my code:
private void comboLname_SelectedIndexChanged(object sender, EventArgs e)
{
string conn = "Data Source=srv-db-02;Initial Catalog=rmsmasterdbtest;Persist Security Info=True;User ID=test;Password=*******";
string Query = "select * from rmsmasterdbtest.dbo.customer where LastName= '" + comboLname.Text + "' ;";
SqlConnection Myconn = new SqlConnection(conn);
SqlCommand cmdDataBase = new SqlCommand(Query, Myconn);
SqlDataReader Reader;
try
{
Myconn.Open();
Reader = cmdDataBase.ExecuteReader();
while (Reader.Read())
{
string ID = Reader.GetInt32(Reader.GetOrdinal("ID")).ToString();
string AccountNuber = Reader.GetString(Reader.GetOrdinal("AccountNumber"));
//string Time = Reader.GetString(Reader.GetOrdinal("Time"));
// string Deposit = Reader.GetString(Reader.GetOrdinal("Deposit"));
string sstatus = Reader.GetString(Reader.GetOrdinal("status"));
string slastname = Reader.GetString(Reader.GetOrdinal("lastname"));
txtid.Text = ID;
txtacnum.Text = AccountNuber;
//txttime.Text = Time;
//txtdeposit.Text = Deposit;
txtstatus.Text = sstatus;
txtlname.Text = slastname;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
Myconn.Close();
}
}
I have a dropdownlist item named IsAuthor. It do not fill my textboxes by retrieving value from tblnewgroup table. Where is the problem I can not understand and it do not show any error please help me
protected void lstAuthor_SelectedIndexChanged(object sender, EventArgs e)
{
string selectSQL;
selectSQL = "SELECT * FROM tblnewgroup ";
selectSQL += "WHERE Groupno='" + lstAuthor.SelectedItem.Value + "'";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataReader reader;
try
{
con.Open();
reader = cmd.ExecuteReader();
reader.Read();
txtGn.Text = reader["Groupno"].ToString();
txtgname.Text=reader["Groupname"].ToString();
txtsl.Text=reader["Slno"].ToString();
txtsn.Text = reader["Subname"].ToString();
reader.Close();
lblResults.Text = "";
}
catch (Exception err)
{
lblResults.Text = "Error getting author. ";
lblResults.Text += err.Message;
}
finally
{
con.Close();
}
}
I filled my drop down list by these codes..
private void FillAuthorList()
{
lstAuthor.Items.Clear();
string selectSQL = "SELECT Groupname, Groupno FROM tblnewgroup";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataReader reader;
try
{
con.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
ListItem newItem = new ListItem();
newItem.Text = reader["Groupname"].ToString();
newItem.Value = reader["Groupno"].ToString();
lstAuthor.Items.Add(newItem);
}
reader.Close();
}
catch (Exception err)
{
lblResults.Text = "Error reading list of names. ";
lblResults.Text += err.Message;
}
finally
{
con.Close();
}
}
Problem : you are assigning single quotes to number feild Groupno.
Solution : you need to assign single quotes to VARCHAR Types only.
Suggestion: you are just assigning the values from SqlDataReader object without checking for rows.if the rows are not found then it will throw the Exeption. So i would suggest to Ceck the SqlDataReader object for any rows before assigning the values to TextBox Controls.
Try This:
protected void lstAuthor_SelectedIndexChanged(object sender, EventArgs e)
{
string selectSQL;
selectSQL = "SELECT * FROM tblnewgroup ";
selectSQL += "WHERE Groupno=" + lstAuthor.SelectedValue;
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataReader reader;
try
{
con.Open();
reader = cmd.ExecuteReader();
if(reader.Read())
{
txtGn.Text = reader["Groupno"].ToString();
txtgname.Text=reader["Groupname"].ToString();
txtsl.Text=reader["Slno"].ToString();
txtsn.Text = reader["Subname"].ToString();
lblResults.Text = "Data Updated Successfully!";
}
else
{
lblResults.Text = "No Records found!";
}
reader.Close();
}
catch (Exception err)
{
lblResults.Text = "Error getting author. ";
lblResults.Text += err.Message;
}
finally
{
con.Close();
}
}
It looks like you're selecting on a number field, but treating it like a text field. Modify your query to remove the single quotes:
selectSQL = "SELECT * FROM tblnewgroup ";
selectSQL += "WHERE Groupno=" + lstAuthor.SelectedItem.Value;
Also check the return value of reader.read() to see if there are any records:
using(var reader = cmd.ExecuteReader())
{
if(reader.Read())
{
txtGn.Text = reader["Groupno"].ToString();
txtgname.Text=reader["Groupname"].ToString();
txtsl.Text=reader["Slno"].ToString();
txtsn.Text = reader["Subname"].ToString();
}
else
{
lblResults.Text = "Author not found";
}
}
Note that I've put the reader in a using block to ensure it is closed, even if an exception occurs.
I assume SqlDataReader.Read method returns boolean value and you can use it like;
while(reader.Read())
{
txtGn.Text = reader["Groupno"].ToString();
txtgname.Text=reader["Groupname"].ToString();
txtsl.Text=reader["Slno"].ToString();
txtsn.Text = reader["Subname"].ToString();
}
Also I suspect lstAuthor.SelectedItem.Value is a number instead of a string. You might need to use it without using "".
Also using parameterized queries always a good choice.
selectSQL = "SELECT * FROM tblnewgroup WHERE Groupno = #Groupno";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
cmd.Parameters.AddWithValue("#Groupno", lstAuthor.SelectedItem.Value);
....
Use following:
while (reader.Read())
{
txtGn.Text = reader["Groupno"].ToString();
txtgname.Text=reader["Groupname"].ToString();
txtsl.Text=reader["Slno"].ToString();
txtsn.Text = reader["Subname"].ToString();
}
I need to populate a combobox in page1 with the address details of a selected name contained in another combobox held in the MainWindow page. I have tried the code below, but combobox name in MainWindow is not recognised.
MainWindow:
private void displayParts()
{
try
{
sc.Open();
string Query = "select * from Parts";
SqlCommand createCommand = new SqlCommand(Query, sc);
SqlDataReader dr = createCommand.ExecuteReader();
while (dr.Read())
{
string Name = dr.GetString(1);
cbParts.Items.Add(Name);//Displaying a list in the Combo Box
}
sc.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Page1:
private void ComboBox_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
{
string constring = "Data Source=.;Initial Catalog=**.MDF;Integrated Security=True";
DataContext=MainWindow.
string Query = "select * from Partners where Name='" + cbParts.SelectedItem.ToString() + "' ;";
SqlConnection conDataBase = new SqlConnection(constring);
SqlCommand cmdDataBase = new SqlCommand(Query, conDataBase);
SqlDataReader myReader;
try
{
sc.Open();
myReader = cmdDataBase.ExecuteReader();
if (myReader.Read())
{
txtPartner.Text = myReader["Name"].ToString();
}
myReader.Close();
sc.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
// may need to cast this to your MainWindow's type
var mainWindow = Application.Current.MainWindow;
//...
mainWindow.cbParts.Items.Add(Name);
Additionally, you could bind your combobox to an ObservableCollection property, and add the items to the collection.