I have retrieved data from Mysql database into a DataGridView1. Let us suppose I am in Row 0. When I change the contents of Row 0, Cell 1 and press enter key or a button, the Update query should modify that row, but I am unable to modify the value of the cell. The cell maintains its previous value when i reload data and the database is not modified. For example, if I change the contents of a cell under column Client_Name from "Acs" to "Gmt", how can I change the value of the cell from "Acs" to "Gmt"? and to have it updated into Mysql database, I am using c# in Vs 2012. below is my code that retrieves my database into datagridview1 any help is welcomed thanks.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data;
using MySql.Data.MySqlClient;
using System.Configuration;
using System.Data.SqlClient;
namespace PI.Gen
{
public partial class frmMain : Form
{
MySqlConnection Conn;
public frmMain()
{
InitializeComponent();
btnDisconnect.Enabled = true;
btnLoadData.Enabled = false;
btnLoadClients.Enabled = false;
}
private void btnConnect_Click(object sender, EventArgs e)
{
string strConnect = "server=" + txtServer.Text + ";uid=" + txtUsername.Text + ";pwd=" + txtPassword.Text + ";database=" + txtDatabase.Text;
try
{
if (txtServer.TextLength <= 0 || txtUsername.TextLength <= 0 || txtDatabase.TextLength <= 0)
{
MessageBox.Show("You have an empty database connection field. Please supply a valid value.");
return;
}
Conn = new MySqlConnection(strConnect);
Conn.Open();
if (Conn.State.ToString() != "Open")
{
MessageBox.Show("Could not open database connection");
return;
}
btnDisconnect.Enabled = true;
btnConnect.Enabled = false;
btnLoadData.Enabled = true;
btnLoadClients.Enabled = true;
// btnSubmitClient.Enabled = true;
}
catch (Exception ex) // catch on general exceptions, not specific
{
MessageBox.Show(ex.Message);
return;
}
}
private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
{
if (Conn != null)
{
Conn.Close();
}
}
private void btnDisconnect_Click(object sender, EventArgs e)
{
try
{
Conn.Close();
Conn = null;
btnDisconnect.Enabled = false;
btnConnect.Enabled = true;
btnLoadData.Enabled = false;
btnLoadClients.Enabled = false;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
}
private void btnLoadData_Click(object sender, EventArgs e)
{
try
{
string CmdString = "SELECT * FROM t_receipients";
MySqlDataAdapter sda = new MySqlDataAdapter(CmdString, Conn);
DataSet ds = new DataSet();
sda.Fill(ds);
dataGridView1.DataSource = ds.Tables[0].DefaultView;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
}
private void btnLoadClients_Click(object sender, EventArgs e)
{
try
{
string CmdString = "SELECT * FROM t_clients";
MySqlDataAdapter sda = new MySqlDataAdapter(CmdString, Conn);
DataSet ds = new DataSet();
sda.Fill(ds);
dataGridView1.DataSource = ds.Tables[0].DefaultView;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
}
After series of trials and error, i finally found what i was looking for, thus being able to update database from datagridview below is my worked around code which works 100% hope it helps someone in future, and thanks #RageComplex for helping out, but one more thing does anyone know how to implement that i mean instead of hitting the enter button to take changes in the datagridview you rather click on a button ty
private void dataGridView1_RowValidated(object sender, DataGridViewCellEventArgs e)
{
try
{
DataTable changes = ((DataTable)dataGridView1.DataSource).GetChanges();
if (changes != null)
{
MySqlCommandBuilder mcb = new MySqlCommandBuilder(mySqlDataAdapter);
mySqlDataAdapter.UpdateCommand = mcb.GetUpdateCommand();
mySqlDataAdapter.Update(changes);
((DataTable)dataGridView1.DataSource).AcceptChanges();
MessageBox.Show("Cell Updated");
return;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
You are not updateing your changes to the database. While you keep your connection open doesn't mean that this will automatically update your data.
First of all, don't keep your connection open. In your app you have a connect button which is good for testing but not for really keeping the connection open, not with databases in my opinion.
The way you load data is correct.
You give the datagridview an DataSource which is a table from your DataSet. So changes made in the datagridview ARE saved to your DataSet but not to your database.
This is how you update your database
public void UpdateTable(DataSet ds)
{
using (MySqlConnection connect = new MySqlConnection(ConnString))
{
connect.Open();
MySqlDataAdapter adapt = new MySqlDataAdapter();
MySqlCommandBuilder commbuilder = new MySqlCommandBuilder(adapt);
adapt.SelectCommand = new MySqlCommand("SELECT * FROM t_receipients", connect);
adapt.Update(ds.Tables[0]);
}
}
Make sure, before you Update your database, you use datagridview1.EndEdit()
Also, you using, this will ensure a connection is closed again after completing that code, best is to always have it in a try-except.
You had struggles with connecting the database as it appears to be in the commends.
I've also forgot to include MySqlDataAdapter above, I used an adapter globally in that case.
I didn't want to report this question as duplicated, but now it kinda does look like this answer.
I would like to give code which I have tested in my application.I used it for button click event.
private void button3_Click(object sender, EventArgs e)
{
string StrQuery;
try
{
string MyConnection2 = "server=localhost;user id=root;password=;database=k";
using (MySqlConnection conn = new MySqlConnection(MyConnection2))
{
using (MySqlCommand comm = new MySqlCommand())
{
comm.Connection = conn;
conn.Open();
for (int i = 0; i < dataGridView3.Rows.Count; i++)
{
StrQuery = #"update s set Quantity='" + dataGridView3.Rows[i].Cells["Quantity"].Value.ToString() + "' where No='" + dataGridView3.Rows[i].Cells["Item No"].Value.ToString() + "';";
comm.CommandText = StrQuery;
comm.ExecuteNonQuery();
}
}
}
}
catch
{
}
}
I think it may help you
Related
This is my first time attempting to read an Access database and write each row to the console. When I execute the application I get thrown an exception that says, "No value given for one or more required parameters" on the following statement:
OleDbDataReader reader = cmd.ExecuteReader();
I'm relatively new to c# programming and after hours of research, I can't figure out what I'm doing wrong. Here's my code:
private void maintenanceToolStripMenuItem_Click(object sender, EventArgs e)
{
//Use a variable to hold the SQL statement.
string inputString = "SELECT Full_Name, First_Name, Last_Name, Company FROM CONTACTS";
try
{
//Create an OleDbCommand object and pass in the SQL statement and OleDbConnection object
OleDbCommand cmd = new OleDbCommand(inputString, conn);
//Send the CommandText to the connection, and then build an OleDbDataReader.
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine("\t{0}\t{1}", reader.GetString(1));
reader.NextResult();
}
}
reader.Close();
}
catch (Exception ex)
{
error_message = ex.Message;
MessageBox.Show(error_message);
}
In response to the commenters, I'm posting a larger piece of code to eliminate any assumptions and give a better overall picture of what I'm trying to do:
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;
using System.IO;
namespace AzFloodSquad
{
public partial class frm1DefaultScreen : Form
{
//Initialize the application
String conn_string = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source = C:\\Databases\\AzFloodSquad\\AzFloodSquad.accdb;Persist Security Info=False;";
OleDbConnection conn = null;
String error_message = "";
String q = "";
string varReportId = "";
public frm1DefaultScreen()
{
InitializeComponent();
}
//Load the default form
private void frm1DefaultScreen_Load(object sender, EventArgs e)
{
connectToolStripMenuItem.PerformClick();
contactsToolStripMenuItem.PerformClick();
}
//Exit the application
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
//Start the database
private void connectToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
conn = new OleDbConnection(conn_string);
conn.Open();
disconnectToolStripMenuItem.Enabled = true;
connectToolStripMenuItem.Enabled = false;
}
catch (Exception ex) { MessageBox.Show(ex.Message); }
}
//Stop the database
private void disconnectToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
conn.Close();
disconnectToolStripMenuItem.Enabled = false;
connectToolStripMenuItem.Enabled = true;
}
catch (Exception ex) { MessageBox.Show(ex.Message); }
}
//Clean up database whem form close button clicked
private void frm1DefaultScreen_FormClosing(object sender, FormClosingEventArgs e)
{
disconnectToolStripMenuItem.PerformClick();
}
private void contactsToolStripMenuItem_Click(object sender, EventArgs e)
{
varReportId = "Contacts";
q = "SELECT * " +
"FROM CONTACTS WHERE CONTACTS.CONTACT_TYPE = 'CUSTOMER' " +
"OR CONTACTS.CONTACT_TYPE = 'HOMEOWNER' OR CONTACTS.CONTACT_TYPE = 'HOME OWNER' " +
"OR CONTACTS.CONTACT_TYPE = 'TENANT'" +
"ORDER BY FULL_NAME";
this.Cursor = Cursors.WaitCursor;
run_Query_Parm(q);
this.Cursor = Cursors.Default;
}
//Pull data from the database using the parameter field
private void run_Query_Parm(String q)
{
error_message = "";
try
{
OleDbCommand cmd = new OleDbCommand(q, conn);
OleDbDataAdapter a = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
a.SelectCommand = cmd;
a.Fill(dt);
results.DataSource = dt;
results.AutoResizeColumns();
}
catch (Exception ex)
{
error_message = ex.Message;
MessageBox.Show(error_message);
}
}
//Clear all data from the screen
private void clearFormToolStripMenuItem_Click(object sender, EventArgs e)
{
varReportId = "";
if (this.results.DataSource != null)
{
this.results.DataSource = null;
}
else
{
this.results.Rows.Clear();
}
}
private void maintenanceToolStripMenuItem_Click(object sender, EventArgs e)
{
//Use a variable to hold the SQL statement.
string inputString = "SELECT Full_Name, First_Name, Last_Name, Company FROM CONTACTS";
try
{
//Create an OleDbCommand object and pass in the SQL statement and OleDbConnection object
OleDbCommand cmd = new OleDbCommand(inputString, conn);
//Send the CommandText to the connection, and then build an OleDbDataReader.
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine("\t{0}\t{1}", reader.GetString(1));
reader.NextResult();
}
}
reader.Close();
}
catch (Exception ex)
{
error_message = ex.Message;
MessageBox.Show(error_message);
}
}
Any help provided would be greatly appreciated. Thanks in advance.
I found the problem. Apparently, I had improper syntax on my SELECT statement. When I replaced my SELECT, (shown in the first code example I posted), with the following, it worked fine:
string inputString = "SELECT Contacts.[Account_Number], " +
"Contacts.[Full_Name], Contacts.[ID], Contacts.[Street], " +
"Contacts.[City], Contacts.[State], Contacts.[Zip] FROM Contacts";
I'm creating a windows application using C# whereby I'm accessing an empty Access database which contains two tables: Provinces and Locations. I'm working on the form that just deals with the Provinces table which looks like this:
This is a subform. When it is open, I can insert/update records etc. Whenever I make a change, I click on the Load Table button to display the changes in the DataGridView object.
If I close this subform and show it again, I can click on the Load Table button and recall all the data for display in the DataGridView object. However, if I close down the application altogether, then I lose all my data. I prove this by double clicking the database file to launch it in Access where I can see that the data is definitely gone. This has become a mystery as I can't figure out why the data doesn't persist in the file. Please advise.
Below is the code for the form. You can see from my methods that I'm careful to close the connection object each and every time I perform a function. So I'm at a loss as to why I keep losing the data on application close?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace GTI_Taxi_Pricing
{
public partial class frmProv : Form
{
private OleDbConnection connection = new OleDbConnection();
public frmProv()
{
InitializeComponent();
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=TaxiDB.accdb;Persist Security Info=False;";
}
private void btnLoad_Click(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
String query = "SELECT * FROM Provinces;";
command.CommandText = query;
OleDbDataAdapter da = new OleDbDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
connection.Close();
}
catch(Exception ex)
{
MessageBox.Show("Error: " + ex);
}
}
private void btnSave_Click(object sender, EventArgs e)
{
if (txtName.Text == "")
{
MessageBox.Show("The name field must have a value.");
return;
}
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "INSERT INTO Provinces (name) VALUES ('" + txtName.Text + "')";
command.ExecuteNonQuery();
MessageBox.Show("Data Saved");
connection.Close();
}
catch(Exception ex)
{
MessageBox.Show("Error: " + ex);
}
}
private void btnNewRecord_Click(object sender, EventArgs e)
{
txtID.Text = "";
txtName.Text = "";
}
private void btnEdit_Click(object sender, EventArgs e)
{
if (txtID.Text == "")
{
MessageBox.Show("The id field must have a value.");
return;
}
if(txtName.Text == "")
{
MessageBox.Show("The name field must have a value.");
return;
}
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "UPDATE Provinces SET name='" + txtName.Text + "' WHERE id=" + txtID.Text + ";";
command.ExecuteNonQuery();
MessageBox.Show("Data Update Successful.");
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex);
}
}
private void btnDelete_Click(object sender, EventArgs e)
{
if (txtID.Text == "")
{
MessageBox.Show("The id field must have a value.");
return;
}
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "DELETE FROM Provinces WHERE id=" + txtID.Text + ";";
command.ExecuteNonQuery();
MessageBox.Show("Record Deleted Successfully.");
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex);
}
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if(e.RowIndex >= 0)
{
DataGridViewRow row = dataGridView1.Rows[e.RowIndex];
txtID.Text = row.Cells[0].Value.ToString();
txtName.Text = row.Cells[1].Value.ToString();
}
}
}
}
This is a common scenario with file based database (or attached database files)
Your connection string refers to the database without using any path.
This means that your database is located in the same directory where your application runs.
You don't have any problem inserting, modifying or deleting data but you loose everything when you restart the app from INSIDE a Visual Studio Debug Session.
Now, if you look at your project files you probably have the database file listed between the other files. Between the properties of this database file you will notice the property Copy to the Output directory and its value set to Copy Always.
This means that every time you restart your application from inside the Visual Studio environment that file is copied from the project folder to the output directory (usually BIN\DEBUG or BIN\x86\DEBUG) but this destroys the database used in the previous run removing the data inserted modified or deleted
Change the property Copy to Output Directory to Copy Never or Copy if Newer
However Copy If Newer presents another problem with MS-Access. If you open the database file located in your project directory using Access o using the Server Connection window of Visual Studio the file is immediately modified also if you don't change anything and thus the Copy If Newer will execute the copy to the output directory
I would like to add some information to my database. I searched for some tutorials, but none of them work.
NonQuery can do what he needs to do, because the messagebox returns "Success" (1). But it does not update my database. If I put the same query to "Add New Query", directly to my database, it works.
Can someone help me?
My class code at the moment:
namespace BurnThatFat
{
class databaseconnection
{
//fields
SqlConnection connection;
string connectionstring;
public databaseconnection()
{
// fields waarde toewijzen
connectionstring = #"Data Source=(LocalDB)\MSSQLLocalDB;" +
#"AttachDbFilename=|DataDirectory|\Database2.mdf;Integrated Security=True";
connection = new SqlConnection(connectionstring);
OpenConnection();
CloseConnection();
}
public List<Object> getObjectsFromDatabase()
{
try
{
OpenConnection();
// sql query
// Datareader
// sqlcommand
// return list van objecten , objecten veranderd naar jouw wens van data.
CloseConnection();
}
catch (Exception)
{
throw;
}
return new List<object>();
}
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;
}
return false;
}
}
private bool CloseConnection()
{
try
{
connection.Close();
return true;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
public void AddGebruiker()
{
string query = "insert into Gebruiker VALUES(3, 'Cihan', 'Kurt', 18, 'Man', 85, 75, 'Admin1', 'Test123', 'testen');";
using (connection)
{
SqlCommand command = new SqlCommand(query, connection);
OpenConnection();
int resultaat = command.ExecuteNonQuery();
if (resultaat == 1)
{
MessageBox.Show("succes");
}
else
{
MessageBox.Show("fail");
}
}
}
}
}
Edit:
And this is the code for my buttons etc:
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;
// voor sql connectie.
using System.Data.SqlClient;
namespace BurnThatFat
{
public partial class SignUp : Form
{
databaseconnection db = new databaseconnection();
public SignUp()
{
InitializeComponent();
gb_login.Visible = false;
gb_Voornaam.Visible = false;
gb_Achternaam.Visible = false;
gb_leeftijdgeslacht.Visible = false;
gb_gewicht.Visible = false;
gb_email.Visible = false;
gb_Start.Visible = true;
}
private void btn_SignUp_Click(object sender, EventArgs e)
{
gb_Start.Visible = false;
gb_Voornaam.Visible = true;
}
private void btn_login_Click(object sender, EventArgs e)
{
gb_Start.Visible = false;
gb_login.Visible = true;
}
private void btn_loginvolgende_Click(object sender, EventArgs e)
{
gb_login.Visible = false;
// hier moet nog een GB!!!!!!
}
private void btn_voornaamvolgende_Click(object sender, EventArgs e)
{
gb_Voornaam.Visible = false;
gb_Achternaam.Visible = true;
}
private void btn_achternaamvolgende_Click(object sender, EventArgs e)
{
gb_Achternaam.Visible = false;
gb_leeftijdgeslacht.Visible = true;
}
private void btn_leeftijdvolgende_Click(object sender, EventArgs e)
{
gb_leeftijdgeslacht.Visible = false;
gb_gewicht.Visible = true;
}
// einde registratie
// opslaan van gegevens in database
private void btn_emailvolgende_Click(object sender, EventArgs e)
{
// gebruiker = new Gebruikerklasse();
// gebruiker.Naam = Convert.ToString(tb_voornaam.Text);
//// gebruiker.Achternaam = Convert.ToString(tb_achternaam.Text);
// gebruiker.Leeftijd = Convert.ToInt32(nud_leeftijd.Value);
/// gebruiker.Geslacht = Convert.ToString(cb_geslacht.Text);
// gebruiker.Huidig_gewicht = Convert.ToInt32(nud_huidiggewicht.Value);
// gebruiker.Streef_gewicht = Convert.ToInt32(nud_streefgewicht.Value);
/// gebruiker.Gebruikersnaam = Convert.ToString(tb_gebruikersnaam2.Text);
// gebruiker.Email = Convert.ToString(tb_email.Text);
// gebruiker.Wachtwoord = Convert.ToString(tb_wachtwoordsignup.Text);
db.AddGebruiker();
gb_email.Visible = false;
// hier moet nog een GB!!!!!
}
private void btn_gewichtvolgende_Click(object sender, EventArgs e)
{
gb_gewicht.Visible = false;
gb_email.Visible = true;
}
}
}
The simplest way to insert into a SQL Server database:
string connectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database2.mdf;Integrated Security=True";
string commandText = "INSERT INTO MyTable (ID, Name, Address) VALUES (10, 'Bob', '123 Main Street');";
using (SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand(commandText, conn))
{
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
As long as commandText is a working query, it should insert a row. It would be better to use parameters for your values instead of hard coding them like I did here - that avoids SQL injection attacks and other potential problems. You can search Google for that (or the question you are asking now) and find tons of resources to help you.
If you need more specific help, post details such as what is actually happening when you try to run your code - are you getting an exception?
I'd clean up a bunch of things before doing anything else.
First, get rid of the openconnection and closeconnection methods all together. And don't keep an instance property for the connection in your class. Create the connection ondemand with a using statement, because at the end of the using statement the compiler will insert a call to the Dispose method on the connection's IDisposable interface implementation and it will close the connection automatically for you.
So after cleaning up all the unnecessary code all you really should have in this class is an implementation of your Addgebrukier method which would look like this
public void AddGebruiker()
{
string query = "insert into Gebruiker VALUES(3, 'Cihan', 'Kurt', 18, 'Man', 85, 75, 'Admin1', 'Test123', 'testen');";
using (SqlConnection connection = new SqlConnection(connectionstring))
{
using (SqlCommand command = new SqlCommand(query, connection))
{
connection.Open();
int resultaat = command.ExecuteNonQuery();
if (resultaat == 1)
{
MessageBox.Show("succes");
}
else
{
MessageBox.Show("fail");
}
}
}
}
You should also load your connection string from the section in the app/web.config, but you can do that later after you get it running.
Here is a simple concept that should work perfectly fine for you. Just change the ServerName, DatabaseName, etc.
using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection connection ;
SqlDataAdapter adapter = new SqlDataAdapter();
string sql = null;
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
connection = new SqlConnection(connetionString);
sql = "insert into product (Product_id,Product_name,Product_price) values(6,'Product6',600)";
try
{
connection.Open();
adapter.InsertCommand = new SqlCommand(sql, connection);
adapter.InsertCommand.ExecuteNonQuery();
MessageBox.Show ("Row inserted !! ");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}
I need your help with something I am working on.
It's very simple, but it has been bugging me.
I am creating a ComboBox[DropDown Menu] in a WPF application and I want to fill it with all the current Tables I have in my DB.
This is what I'm struggling to do:
When I click on the ComboBox it will show all the available tables in the DataBase. Then when I click on one of them it will show the information that is contained within the selected table in a DataGrid I've placed below the menu.
And here Is the code I am using when the ComboBox opens:
private void tableComboBox_DropDownOpened(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE';", db.connection);
SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd);
DataSet dataSet = new DataSet();
dataAdapter.Fill(dataSet);
foreach(DataRow row in dataSet.Tables)
{
tableComboBox.Items.Add(row);
}
}
I've already looked and tried some different approaches but non of them work.
And I've tried to show the Content of a Table in the DataGrid but I got stuck again.
Please fellow coders. Help this newbie over here! :)
So this is what I quickly came up with.
remove the tableComboBox_DropDownOpened event.
add the event comboBox_SelectionChange
Change your db connection string, names of the combobox and dataGrid to match yours.
Here is the code below, I moved the loadCombo() below your initialize to make it simple.
public partial class MainWindow : Window
{
SqlConnection db = new SqlConnection("Your Connection String Here");
public MainWindow()
{
InitializeComponent();
loadCombo();
}
private void loadCombo()
{
SqlCommand cmd = new SqlCommand("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE';", db);
SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd);
DataSet dataSet = new DataSet();
dataAdapter.Fill(dataSet);
foreach (DataRow row in dataSet.Tables[0].Rows)
{
comboBox.Items.Add(row[0]);
}
}
private DataTable loadDataGrid(String inTableName )
{
SqlCommand cmd = new SqlCommand("SELECT COLUMN_NAME,* FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '"+ inTableName + "';", db);
SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd);
DataSet dataSet = new DataSet();
dataAdapter.Fill(dataSet);
return dataSet.Tables[0];
}
private void comboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
string text = e.AddedItems[0].ToString(); ;
dataGrid.ItemsSource = loadDataGrid(text).DefaultView;
}
}
Hope this helps
I have updated your code below. Paste this in a give it a shot. I am not sure what is happening with the create buttons but lets see if we can fix the combobox and datagrid. I added some comments in the code to help explain my rational.
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
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;
namespace DatabaseManagement
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
Database db = new Database();
public MainWindow()
{
InitializeComponent();
// Add the loadCombo back
loadCombo();
// comment this out until you get the desired functionality
//TableCreateGrid.Visibility = Visibility.Hidden;
}
private void createButton_Click(object sender, RoutedEventArgs e)
{
try
{
// I am not sure what you are doing here -
if (string.IsNullOrEmpty(column3TextBox.Text) && string.IsNullOrEmpty(column4TextBox.Text))
{
db.CreateTable(tableTextBox.Text, column1TextBox.Text, column2TextBox.Text);
informationBlock.Text = db.infoBoxString;
}
else if (string.IsNullOrEmpty(column4TextBox.Text))
{
db.CreateTable(tableTextBox.Text, column1TextBox.Text, column2TextBox.Text, column3TextBox.Text);
informationBlock.Text = db.infoBoxString;
}
else if (!string.IsNullOrEmpty(column3TextBox.Text) && !string.IsNullOrEmpty(column4TextBox.Text))
{
db.CreateTable(tableTextBox.Text, column1TextBox.Text, column2TextBox.Text, column3TextBox.Text, column4TextBox.Text);
informationBlock.Text = db.infoBoxString;
}
}
catch (Exception ex)
{
informationBlock.Text = ex.Message;
}
}
private void button_Click(object sender, RoutedEventArgs e)
{
db.Connect();
informationBlock.Text = db.infoBoxString;
}
private void button1_Click(object sender, RoutedEventArgs e)
{
db.Close();
informationBlock.Text = db.infoBoxString;
}
private void loadCombo()
{
SqlCommand cmd = new SqlCommand("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE';", db.connection);
SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd);
DataSet dataSet = new DataSet();
dataAdapter.Fill(dataSet);
foreach (DataRow row in dataSet.Tables[0].Rows)
{
tableComboBox.Items.Add(row[0]);
}
}
private DataTable loadDataGrid(String inTableName)
{
// Here you need to specify the columns you want in the TableCreateGrid
// example this just will show the COLUMN NAME,DATA TYPE, CHARACTER MAXIMUM LENGTH and so on
// SqlCommand cmd = new SqlCommand("SELECT COLUMN_NAME,DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, TABLE_SCHEMA FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '" + inTableName + "';", db.connection);
SqlCommand cmd = new SqlCommand("SELECT COLUMN_NAME,* FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '" + inTableName + "';", db.connection);
SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd);
DataSet dataSet = new DataSet();
dataAdapter.Fill(dataSet);
return dataSet.Tables[0];
}
private void tableComboBox_DropDownOpened(object sender, EventArgs e)
{
//loadCombo();
// dont need since this is loaded on Initialize
}
private void tableComboBox_DropDownClosed(object sender, EventArgs e)
{
// tableComboBox.Items.Clear();
// dont need since this will clear all the items in the tableComboBox
}
private void tableComboBox_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
{
try
{
string text = e.AddedItems[0].ToString(); ;
dataGrid.ItemsSource = loadDataGrid(e.AddedItems[0].ToString()).DefaultView;
}
catch (Exception ex)
{
informationBlock.Text = ex.Message;
}
}
}
}
This is a code to store disply name and value in combobox
private void Form1_Load(object sender, EventArgs e)
{
var Header = new BindingList<KeyValuePair<string, string>>();
List<string> LV = ListHeader();
foreach (var listOut in LV)
{
Header.Add(new KeyValuePair<string, string>(listOut, "val"+listOut));
}
tableComboBox.DataSource = Header;
tableComboBox.DisplayMember = "Key";
tableComboBox.ValueMember = "Value";
}
public List<string> ListHeader()
{
List<string> list = new List<String>();
try
{
cmd.Connection = db.connection;
cmd.CommandText = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE';";
var reader = cmd.ExecuteReader();
for(int i=0;i<reader.FieldCount;i++)
{
list.Add(reader.GetName(i));
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Get Header",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
con.Close();
}
return list;
}
You can get the combobox value like this :
Console.WriteLine(((KeyValuePair)tableComboBox.SelectedItem).Value.ToString());
Or you only want to get a display name :
tableComboBox.SelectedItem.ToString()
I have a simple form which connects to a access database and displays records, this code shows whats going on, why is the button im trying to code not working? Im guessing its something to do with the variable which i've not decleared correctly?
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 MediaPlayer
{
public partial class Media : Form
{
// Use this connection string if your database has the extension .accdb
private const String access7ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\MediaDatabase.accdb";
// Use this connection string if your database has the extension .mdb
private const String access2003ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\MediaDatabase.mdb";
// Data components
private OleDbConnection myConnection;
private DataTable myDataTable;
private OleDbDataAdapter myAdapter;
private OleDbCommandBuilder myCommandBuilder;
// Index of the current record
private int currentRecord = 0;
private void FillDataTable(String selectCommand)
{
try
{
myConnection.Open();
myAdapter.SelectCommand.CommandText = selectCommand;
// Fill the datatable with the rows reurned by the select command
myAdapter.Fill(myDataTable);
myConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error in FillDataTable : \r\n" + ex.Message);
}
}
private void DisplayRow(int rowIndex)
{
// Check that we can retrieve the given row
if (myDataTable.Rows.Count == 0)
return; // nothing to display
if (rowIndex >= myDataTable.Rows.Count)
return; // the index is out of range
// If we get this far then we can retrieve the data
try
{
DataRow row = myDataTable.Rows[rowIndex];
textBox1.Text = row["FilePath"].ToString();
textBox2.Text = row["Subject"].ToString();
textBox3.Text = row["Title"].ToString();
textBox4.Text = row["Keywords"].ToString();
textBox5.Text = row["MediaType"].ToString();
}
catch (Exception ex)
{
MessageBox.Show("Error in DisplayRow : \r\n" + ex.Message);
}
}
public Media()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
{
String command = "SELECT * FROM Media";
try
{
myConnection = new OleDbConnection(access7ConnectionString);
myAdapter = new OleDbDataAdapter(access7ConnectionString, myConnection);
myCommandBuilder = new OleDbCommandBuilder(myAdapter);
myDataTable = new DataTable();
FillDataTable(command);
DisplayRow(currentRecord);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
int m_rowPosition = 0;
private void label2_Click(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
//if not at the first row, go back one row and show the record.
if (m_rowPosition !=0)
{
m_rowPosition---;
this.DisplayRow();
}
}
private void button6_Click(object sender, EventArgs e)
{
//move to first row of data and show data
m_rowPosition = 0;
this.DisplayRow();
}
}
}
If i understood you want to do this when calling DisplayRow method:
DisplayRow(m_rowPosition);
or you can change your method to this:
private void DisplayRow()
{
// Check that we can retrieve the given row
if (myDataTable.Rows.Count == 0)
return; // nothing to display
if (rowIndex >= myDataTable.Rows.Count)
return; // the index is out of range
// If we get this far then we can retrieve the data
try
{
DataRow row = myDataTable.Rows[m_rowPosition];//<- here you using index which value is changed on button click
textBox1.Text = row["FilePath"].ToString();
textBox2.Text = row["Subject"].ToString();
textBox3.Text = row["Title"].ToString();
textBox4.Text = row["Keywords"].ToString();
textBox5.Text = row["MediaType"].ToString();
}
catch (Exception ex)
{
MessageBox.Show("Error in DisplayRow : \r\n" + ex.Message);
}
}
This is being discussed in
why aren't my buttons working in c# application