ComboBox don't update - c#

I got a comboBox in FORM1 that gets the value from the database
FORM1 Code:
public void fillComboBox()
{
using (SqlConnection myDatabaseConnection = new SqlConnection(myConnectionString.ConnectionString))
{
myDatabaseConnection.Open();
using (SqlCommand mySqlCommand = new SqlCommand("Select LastName, FirstName, MiddleName from EMP", myDatabaseConnection))
using (SqlDataReader sqlreader = mySqlCommand.ExecuteReader())
{
while (sqlreader.Read())
{
string Lname = sqlreader.GetString(sqlreader.GetOrdinal("LastName"));
string Fname = sqlreader.GetString(sqlreader.GetOrdinal("FirstName"));
string Mname = sqlreader.GetString(sqlreader.GetOrdinal("MiddleName"));
string fullName = Lname + ", " + Fname + " " + Mname;
comboBox3.Items.Add(fullName);
}
}
}
}
From the FORM1 I have a button that opens the FORM2 where I could add data in the database.
FORM2 Code:
public void addData()
{
string a = "INSERT INTO Emp(LastName, FirstName, MiddleName) Values('"+textBox1.Text+"', '"+textBox2.Text+"', '"+textBox3.Text+"')";
using (SqlConnection myDatabaseConnection1 = new SqlConnection(myConnectionString.ConnectionString))
{
myDatabaseConnection1.Open();
using (SqlCommand mySqlCommand = new SqlCommand(" " + a + " ", myDatabaseConnection1))
mySqlCommand.ExecuteReader();
}
}
private void button1_Click(object sender, EventArgs e)
{
addData();
Form1 nf = new Form1();
nf.fillComboBox();
this.close
}
I check the database and verified the data is added.
The problem is when I add data in the datatabase the comboBox don't update the data it loads. It only updates after I run the program again.

With this code:
Form1 nf = new Form1();
nf.fillComboBox();
You are creating a new Form1 after db update (and not showing it). You are not refreshing the original Form1.
To see this, add: nf.Show(); after the fillComboBox() call.
You have to refresh the original Form1 after closing Form2.
example:
if(form2.ShowDialog() == DialogResult.OK)
fillComboBox();
and in fillComboBox, you should clear comboBox3.Items before adding new entries.

Related

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;
}
....

C# I can't print variable text in other Form

I trying to code program and I have two forms (Form1 is for loging and Form2 is empty for now, but I would like to print Logged: 'Name' + 'Surename' from DB).
I created class User which has Name and Surename (both public static strings) and method GetUserInfo() to get Name and Surename by user's Login. If I print User.Name + User.Surename in MsgBox after program checks login and password everything is ok, but after Form2 loads then
label1.Text = "User: " + User.name + " " + User.surename;
in method public Form2() shows just User: and nothing more.
Form1:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
string login = textBox1.Text;
string pass = textBox2.Text;
SqlConnection connection = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\xxx\Documents\Visual Studio 2015\Projects\*\*\Database1.mdf;Integrated Security=True;Connect Timeout=30");
SqlCommand query = new SqlCommand("Select * from Users where login='" + login + "' AND password ='" + pass + "'", connection);
connection.Open();
SqlDataReader Reader = query.ExecuteReader();
int count = 0;
Form1 form1 = new Form1();
Form2 form2 = new Form2();
while (Reader.Read())
{
count += 1;
}
if (count == 1)
{
this.Hide();
form2.Show();
User.GetUserInfo(login);
MessageBox.Show(User.name + " " + User.surename);
}
else
MessageBox.Show("Bad Login");
}
}
Form2
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
label1.Text = "User: " + User.name + " " + User.surename;
}
private void label1_Click(object sender, EventArgs e)
{
}
private void label1_Click_1(object sender, EventArgs e)
{
}
}
and User class:
public class User
{
public static string name { get; set; }
public static string surename { get; set; }
public static void GetUserInfo(string login)
{
using (SqlConnection connection = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\xxx\Documents\Visual Studio 2015\Projects\*\*\Database1.mdf;Integrated Security=True;Connect Timeout=30"))
using (SqlCommand query = new SqlCommand("Select FirstName, LastName from Users where login='" + login + "'", connection))
{
connection.Open();
SqlDataReader Reader = query.ExecuteReader();
while (Reader.Read())
{
User.name = Reader["FirstName"].ToString();
User.surename = Reader["LastName"].ToString();
}
}
}
}
Thank you!
Use this code:
User.GetUserInfo(login);
this.Hide();
Form2 form2 = new Form2();
form2.Show();
because you need first set values for name and surename and then use it.
In your case, you first show Form2 and then set values
Add public variables or properties to Form1 so that you can access them:
in Form1:
public User user;
....
user.name = Textbox1.Text;
user.surname = Textbox2.Text;
In your Form2:
Form frm = new Form1();
frm.ShowDialog();
label1.Text = "User: " + frm.user.name + " " + frm.user.surename;
frm.Dispose();
So the problem you have is that you are creating Form2 before the properties in the User class are filled.
This is why :
label1.Text = "User: " + User.name + " " + User.surename;
This is called inside the constructor of Form2. This means whenever you initialize this form with
Form2 form2 = new Form2();
all code in the constructor executes.
So the label text will be set when creating the form.
User.GetUserInfo(login); is called after this, the data will be empty for Form2 since the form is already created.
A possible solution would be
To set the label in the form2 loading event and call User.GetUserInfo(login); before form2.Show();
or
Calling Form2 form2 = new Form2(); after User.GetUserInfo(login);
You are setting the label text in the constructor of Form2. At that point they don't have a value as you haven't read the data from the database yet, so the label will simply read:
User:
It won't change until you update it's value again. You need to call a method on Form2 to update the label text once the call to User.GetUserInfo has completed successfully.
if (count == 1)
{
this.Hide();
form2.Show();
User.GetUserInfo(login);
// Update the label text here
MessageBox.Show(User.name + " " + User.surename);
or swap the order of getting the user information and constructing Form2:
if (count == 1)
{
this.Hide();
User.GetUserInfo(login);
form2 = new Form2();
form2.Show();
Either way will work, the one you choose depends on what else you need to do with your forms.

How to fill a combobox from a MS Access text field then insert combobox selection into another table

I am trying to insert an Access table record with information from a combobox. I am using a winform and C#. I have simplified my project to just include the problem area. I am showing three methods with 4 controls (2 buttons and 2 comboboxes. The first method is connecting to an Access database and then showing a list of the tables and views in the first combobox. this method will also call the last method, SelectName() and fill the second combobox with field contents from a predetermined table from the selected database. The second method (buttonInsert_Click()) is where my problem lies. I would like the method to insert into one of the selected tables from combobox1 the selected item from combobox2 when the insert button is clicked. The only content I can get to insert into the selected table is
System.Data.DataRowView
The C# section of my project is below. Any suggestions are appreciated. Thank You.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
namespace DbApp
{
public partial class Form1 : Form
{
private char ch = '"';
private OleDbConnection dbConn;
private string sql = "";
public Form1()
{
InitializeComponent();
}
private void buttonConnect_Click(object sender, EventArgs e)
{
string connectionString = "";
string stringData = "";
openFileDialog1.Filter = "";
openFileDialog1.ShowDialog();
Text = openFileDialog1.FileName;
stringData = openFileDialog1.FileName;
connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + ch + Text + ch;
if (dbConn != null)
dbConn.Close();
dbConn = new OleDbConnection(connectionString);
dbConn.Open();
comboBox1.Items.Clear();
DataTable info = dbConn.GetSchema("Tables");
for (int x = 0; x < info.Rows.Count; ++x)
{
if ((info.Rows[x][3].ToString() == "TABLE") || (info.Rows[x][3].ToString() == "VIEW"))
{
comboBox1.Items.Add((object)info.Rows[x][2].ToString());
}
}
SelectName();
}
private void buttonInsert_Click(object sender, EventArgs e)
{
string name = this.comboBox2.SelectedItem.ToString();
try
{
dbConn = new OleDbConnection();
dbConn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + ch + openFileDialog1.FileName + ch;
dbConn.Open();
sql = "INSERT INTO " + this.comboBox1.SelectedItem.ToString() + " (Names)" +
"Values (#name)";
OleDbCommand myCommand = new OleDbCommand(sql, dbConn);
myCommand.Parameters.Add("#name", OleDbType.VarChar).Value = name;
myCommand.ExecuteNonQuery();
myCommand.Connection.Close();
}
catch (Exception err)
{
MessageBox.Show("Error: " + err.Message.ToString());
}
}
private void SelectName()
{
string strCon = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + ch + openFileDialog1.FileName + ch;
try
{
using (dbConn = new OleDbConnection(strCon))
{
dbConn.Open();
sql = "SELECT Name FROM Names";
OleDbDataAdapter adapter = new OleDbDataAdapter(new OleDbCommand(sql, dbConn));
DataSet ds = new DataSet();
adapter.Fill(ds, "Names");
comboBox2.Items.Clear();
this.comboBox2.DataSource = ds.Tables["Names"];
this.comboBox2.DisplayMember = "Name";
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message.ToString());
}
}
}
}
Try this:
string name = this.comboBox2.Text;

Find a specific record in Access and display the records into textboxes

Hey Im new to stacoverflow and would like to ask some help. I need to type a ID into a textbox and when searched is clicked it will find the record and display each of the colum values to text boxes. Im using a access database. I have found solution on this but they dont seem to work. I have found and ajusted the following code but give an error op conn.open() and is coded in C#. Please help me.
source Code:
public partial class FamilyTree : UserControl
{
private OleDbConnection conn;
public FamilyTree()
{
InitializeComponent();
}
private void FamilyTree_Load(object sender, System.EventArgs e)
{
}
private void ConnectToDatabase()
{
conn = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Hannes\Documents\Visual Studio 2013\Projects\fam\fam\Prog.mdb");
conn.Open();
}
private void DisconnectDatabase()
{
conn.Close();
}
private void btnSearch_Click(object sender, System.EventArgs e)
{
string title = txtID.Text.ToString();
string queryString = "SELECT * FROM FamilyTree" + txtID ;
OleDbCommand command = new OleDbCommand();
command.CommandText = queryString;
command.Connection = conn;
conn.Open();
OleDbDataReader dr = command.ExecuteReader();
while (dr.Read())
{
txtSex.Text += dr["gendre"].ToString();
txtColour.Text += dr["name"].ToString();
txtDOB.Text += dr["DOB"].ToString();
txtStatus.Text += dr["city"].ToString();
txtCock.Text += dr["mom"].ToString();
txtHen.Text += dr["dad"].ToString();
}
conn.Close();
}
Ensure that the 'ConnectToDatabase()' method is called somewhere before using 'conn' in btnSearch_Click.
Next, decide whether you are using the Id or Title to filter the result.
When creating the queryString, ensure you use the 'WHERE Id = ' or 'WHERE Title = ' clause to filter - but also ensure that you have a space between the end of the queryString and the value added at the end - the example you have given would produce 'SELECT * FROM FamilyTree23' if the Id was 23. This would error because there is no table with this name in the database.
Finally, as mentioned in other answers, 'using' a database connection, and using query parameters are a better practice. The 'using' statement will release the connection automatically after use, and a parameterised query prevent will SQL Injection issues and ensure correct data types are passed to the query.
Example:
public partial class FamilyTree : UserControl
{
string connectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Hannes\Documents\Visual Studio 2013\Projects\fam\fam\Prog.mdb";
public FamilyTree()
{
InitializeComponent();
}
private void FamilyTree_Load(object sender, System.EventArgs e)
{
}
private void btnSearch_Click(object sender, System.EventArgs e)
{
string title = txtID.Text.ToString();
sqlQuery = "SELECT * FROM FamilyTree WHERE Title = ?";
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
using (OleDbCommand cmd = new OleDbCommand(sqlQuery, conn))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("Title", title);
conn.Open();
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
txtSex.Text += dr["gendre"].ToString();
txtColour.Text += dr["name"].ToString();
txtDOB.Text += dr["DOB"].ToString();
txtStatus.Text += dr["city"].ToString();
txtCock.Text += dr["mom"].ToString();
txtHen.Text += dr["dad"].ToString();
}
}
}
}
}

How do I read data from a database and display it in a TextBox?

I try to get one data column from a MS-Access table and display it in a TextBox like this
public partial class Form1 : Form
{
public OleDbConnection database;
public Form1()
{
InitializeComponent();
}
private OleDbConnection Database_Connection;
private void Open_Database_button_Click(object sender, EventArgs e)
{
Database_Connection = new OleDbConnection(
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="test.mdb");
OleDbCommand Command = new OleDbCommand(
" SELECT top 1 * from test", Database_Connection);
Database_Connection.Open();
OleDbDataReader DB_Reader = Command.ExecuteReader();
// How can I display the column in TextBox?
}
...
}
Try to change your Open_Database_button_Click in this way:
private void Open_Database_button_Click(object sender, EventArgs e)
{
using(OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=test.mdb" ))
using(OleDbCommand Command = new OleDbCommand(" SELECT top 1 * from test", con))
{
con.Open();
OleDbDataReader DB_Reader = Command.ExecuteReader();
if(DB_Reader.HasRows)
{
DB_Reader.Read();
textbox1.Text = DB_Reader.GetString("your_column_name");
}
}
}
What I have changed/added:
Removed the global var DataBase_Connection
Added using to the Disposable objects, so they will automatically
closed when no more needed
Added check on DB_Reader.HasRows to exclude empty results from the
query
Added setting of the text property of the textbox with the value of
one of your columns

Categories

Resources