button click to search multiple Access tables - c#

I have a simple feature to search an Access table for a given serial number by button click.
Is there a way to add to what I have below to search multiple tables for the serial number and display in datagridview?
private void searchItembtn_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(serialSearch.Text))
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.Parameters.Add("#searchSerial", OleDbType.VarWChar).Value = serialSearch.Text;
string searchFB = "SELECT * FROM Inventory WHERE SerialNumber = #searchSerial";
command.CommandText = searchFB;
connection.Close();
OleDbDataAdapter db = new OleDbDataAdapter(command);
DataTable dt = new DataTable();
db.Fill(dt);
dataGridFB.DataSource = dt;
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Message);
connection.Close();
}
searchHide();
connection.Close();
}
}

Related

Sort data by date, time, and name from Mysql database in c#

I have been really struggling to sort this data by date and time. As you can see, I have got this data. In addition, the data table is not taking the same space as the dataGridView space. How do I resolve that problem?
I am trying to sort out this data in c#. I have generated the above table by writing the below code:
private void ViewAppointment_Load(object sender, EventArgs e)
{
try
{
MySqlConnection connection = new MySqlConnection("server=localhost;port=****;username=root;password=****;database=appointment; pooling = false; convert zero datetime = True");
string Query = "SELECT * FROM `appointmentdetails`";
MySqlCommand myCommand = new MySqlCommand(Query, connection);
MySqlDataAdapter myAdapater = new MySqlDataAdapter();
myAdapater.SelectCommand = myCommand;
DataTable dTable = new DataTable();
myAdapater.Fill(dTable);
dataGridView1.DataSource = dTable;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Thanks for your time
You can either sort directly on the DataGrid:
dataGridView1.Sort(dataGridView1.Columns["Date"], ListSortDirection.Ascending);
Or get the data sorted from sql:
string Query = "SELECT * FROM `appointmentdetails` order by Date";
You need to add your sorting to the Query
private void ViewAppointment_Load(object sender, EventArgs e)
{
try
{
MySqlConnection connection = new MySqlConnection("server=localhost;port=****;username=root;password=****;database=appointment; pooling = false; convert zero datetime = True");
string Query = "SELECT * FROM `appointmentdetails ORDER BY date DESC`";
MySqlCommand myCommand = new MySqlCommand(Query, connection);
MySqlDataAdapter myAdapater = new MySqlDataAdapter();
myAdapater.SelectCommand = myCommand;
DataTable dTable = new DataTable();
myAdapater.Fill(dTable);
dataGridView1.DataSource = dTable;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

refresh datagridview after insert or update or delete without selecting new sql query

I just want to clarify, can i refresh datagridview after insert or update or delete without selecting new sql query again ?
i have googled it, and still have no idea to do it.
here's my code
private void button4_Click(object sender, EventArgs e)
{
employee();
}
public void employee()
{
DataTable dtclubroom = new DataTable();
SqlCommand command = new SqlCommand();
SqlDataAdapter adapter = new SqlDataAdapter(command.CommandText, myConnection);
try
{
myConnection.Open();
dtclubroom.Clear();
command.Connection = myConnection;
command.CommandText = "Select * from employee ";
adapter.SelectCommand = command;
adapter.Fill(dtclubroom);
dataGridView2.DataSource = dtclubroom;
}
catch (Exception ex)
{
MessageBox.Show("error" + ex);
}
finally
{
myConnection.Close();
}
}
private void button5_Click(object sender, EventArgs e)
{
SqlCommand command2 = new SqlCommand();
try
{
myConnection.Open();
command2.CommandText = "insert into employee (name,id) values (#name,#id)";
command2.Connection = myConnection;
command2.Parameters.AddWithValue("#name","Leon");
command2.Parameters.AddWithValue("#id", "002");
command2.ExecuteNonQuery();
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
finally
{
myConnection.Close();
}
employee() //<- refresh datagridview
}
Button 4 is to load data, and button 5 inserting data also load data. is there a way refresh datagridview without calling employee() method again ?
You can do it in couple of ways.
Add the newly inserted record to your datatable (you need to use a global datatable variable for this) and refresh your Grid View using this datatable.
You can add the newly inserted record directly to the Grid View
You can follow these techniques also for DELETE and UPDATE
Here is the implementation of idea #1 for your existing code :
DataTable dtclubroom = new DataTable();
private void button4_Click(object sender, EventArgs e)
{
employee();
}
public void employee()
{
SqlCommand command = new SqlCommand();
SqlDataAdapter adapter = new SqlDataAdapter(command.CommandText, myConnection);
try
{
myConnection.Open();
dtclubroom.Clear();
command.Connection = myConnection;
command.CommandText = "Select * from employee ";
adapter.SelectCommand = command;
adapter.Fill(dtclubroom);
dataGridView2.DataSource = dtclubroom;
}
catch (Exception ex)
{
MessageBox.Show("error" + ex);
}
finally
{
myConnection.Close();
}
}
private void button5_Click(object sender, EventArgs e)
{
SqlCommand command2 = new SqlCommand();
try
{
myConnection.Open();
command2.CommandText = "insert into employee (name,id) values (#name,#id)";
command2.Connection = myConnection;
command2.Parameters.AddWithValue("#name","Leon");
command2.Parameters.AddWithValue("#id", "002");
command2.ExecuteNonQuery();
DataRow dr = dtclubroom.NewRow();
dr["name"] = "Leon";
dr["id"] = "002";
dtclubroom.Rows.Add(dr);
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
finally
{
myConnection.Close();
}
dataGridView2.DataSource = dtclubroom; //<- refresh datagridview
}
Look that the datatable declaration is moved up and you need to place it in top of your class :
DataTable dtclubroom = new DataTable();
Nothing else need to be global.

How to search data in gridview using a TextBox value with an Oracle Database

I am trying to show Oracle Data in a DataGridView in my Windows Form Application but it just returns a grey blank view. My code for this currently is:
string insertquery = "select * from Candidate where CandidateName like '"+ txtBoxSearchData.Text +"%'";
OracleConnection con = new OracleConnection(oradb);
con.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = con;
cmd.CommandText = insertquery;
try
{
OracleDataReader reader = cmd.ExecuteReader();
OracleDataAdapter orada = new OracleDataAdapter(cmd);
DataTable dataTable = new DataTable();
orada.Fill(dataTable);
dataTable.Load(reader);
BindingSource bSource = new BindingSource();
bSource.DataSource = dataTable;
dataGridViewSearch.DataSource = bSource;
orada.Update(dataTable);
}
catch(ArgumentException ex)
{
MessageBox.Show("Error: " + ex.Message);
}
catch(OracleException ex1)
{
MessageBox.Show("Error: " + ex1.Message);
}
finally
{
cmd.Dispose();
con.Dispose();
}
}
I am positive I do not require all those functions in my Try statement but I have come across many different methods to do this - I just included all of those into my code to experiment. The connection string is correct too as I have succeeded in adding data into the tables through queries in another part of my application.
Doing something like the following should be enough. There should be no need for an OracleDataAdapter or BindingSource. Just can't test it here, as I do not have an Oracle database around.
public void fillDataGrid()
{
try
{
using(OracleConnection connection = new OracleConnection("connectstring"))
using(OracleCommand cmd = new OracleCommand("select * from my super table", connection ))
{
connection .Open();
using(OracleDataReader oracleDataReader = cmd.ExecuteReader())
{
DataTable dataTable = new DataTable();
dataTable.Load(oracleDataReader );
myDataGrid.DataSource = dataTable;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}

How to update data from DataGridView to database? ERROR - Cannot insert value NULL

I'm trying to update data from DataGridView to my database. While I was looking for the solution of this problem on google, I noticed that all of the solutions are managed by using class variables (for DataTable,SqlDataAdapter,...). I'm trying to do this just by using function variables.
This is how I loaded data to DataGridView:
private void LoadDataGridView(int ID)
{
try
{
SqlConnection connection = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand("SELECT SENTENCE FROM Sentences WHERE CategoryID = #ID",connection);
cmd.Parameters.Add("#ID",SqlDbType.Int).Value = ID;
DataTable dataTable = new DataTable();
SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd);
dataAdapter.Fill(dataTable);
DataGridView.DataSource = dataTable;
}
catch (Exception)
{
MessageBox.Show("ERROR WHILE CONNECTING TO DATABASE!");
}
}
DataGridView is showing just those sentences that match particular ID.
This is what I have tried so far:
private void RefreshBtn_Click(object sender, EventArgs e)
{
try
{
SqlConnection connection = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand("SELECT SENTENCE FROM Sentences WHERE CategoryID IN(#CategoryID)", connection);
cmd.Parameters.Add("#CategoryID",SqlDbType.Int).Value = CategoryID;
SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd);
SqlCommandBuilder cmdBuilder = new SqlCommandBuilder(dataAdapter);
dataAdapter.Update(dataTable);
}
catch (Exception)
{
MessageBox.Show("ERROR WHILE CONNECTING WITH DATABASE!");
}
}
This is the error that comes up:
Cannot insert value NULL into column CategoryID, table ...;column does not allow nulls.Insert fails. The statement has been terminated.
if your Id data type is int ,you don't need put it inside "".
private void RefreshBtn_Click(object sender, EventArgs e)
{
try
{
string connString;//WHAT EVER IT IS
string Query=string.Format(#"SELECT QUESTION FROM Questions WHERE CategoryID = '{0}'",CategoryID);
SqlConnection connection = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(Query, connection);
connection.Open();
cmd.ExecuteNonQuery();
SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd,connString);
DataTable DataTable=new DataTable();
dataAdapter.Fill(DataTable);
datagridview1.DataSource=DataTable;
}
catch (Exception)
{
MessageBox.Show("ERROR WHILE CONNECTING WITH DATABASE!");
}
catch (SqlException)
{
MessageBox.Show("SqL Error!");
}
}
SOLUTION of my problem:
Firstly, I have shown all columns of database table in DataGridView and then I have hided Primary Key column and CategoryID column. That is shown in the following code:
private void LoadDataGridView(int ID)
{
try
{
SqlConnection connection = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "SELECT * FROM Sentences WHERE CategoryID = #ID";
cmd.Connection = connection;
cmd.Parameters.Add("#ID",SqlDbType.Int).Value = ID;
dataTable = new DataTable();
SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd);
dataAdapter.Fill(dataTable);
dataGridView.DataSource = dataTable;
dataGridView.Columns[0].Visible = false;
dataGridView.Columns[2].Visible = false;
}
catch (Exception)
{
MessageBox.Show("ERROR WHILE CONNECTING WITH DATABASE!");
}
}
Then, I have set default value only for CategoryID column, because Primary Key column has an option of Auto - Increment. That is show in the following code:
private void dataGridView_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
{
e.Row.Cells["CategoryID"].Value = CategoryID;
}
The last thing I have done is implement the code for RefreshBtn (the following code is practically the same as the code in question):
private void RefreshBtn_Click(object sender, EventArgs e)
{
try
{
SqlConnection connection = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "SELECT * FROM Questions WHERE CategoryID = #CategoryID";
cmd.Connection = connection;
cmd.Parameters.Add("#CategoryID", SqlDbType.Int).Value = CategoryID;
SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd);
SqlCommandBuilder cmdBuilder = new SqlCommandBuilder(dataAdapter);
dataAdapter.Update(dataTable);
}
catch (Exception)
{
MessageBox.Show("ERROR WHILE CONNECTING WITH DATABASE !");
}
}

Populating ComboBox with Data

I want to display the items in my database inside the combo box after the radio option is been selected. when i tried this nothing was displayed in the combo box. please kindly help
private void chkDetailsButton_Click(object sender, EventArgs e)
{
if (radioButtonA.Checked)
{
OleDbConnection connect = db.dbConnect();
try
{
connect.Open();
MessageBox.Show("Opened");
OleDbCommand command = new OleDbCommand();
command.Connection = connect;
command.CommandText = "Select * from Categories";
DataTable dt = new DataTable();
for (int i = 0; i < dt.Rows.Count; i++)
{
cmbDisplay.Items.Add(dt.Rows[i]["SeatNo"]);
}
}
catch (Exception ex)
{
MessageBox.Show("Exception in Database" + ex);
}
finally
{
connect.Close();
}
}
}
Your try block should resemble the following:
try
{
connect.Open();
MessageBox.Show("Opened");
OleDbCommand command = new OleDbCommand();
command.Connection = connect;
command.CommandText = "Select * from Categories";
DataTable dt = new DataTable();
//Put some data in the datatable!!
using(OleDbDataReader reader = command.ExecuteReader())
{
dt.Load(reader);
}
for (int i = 0; i < dt.Rows.Count; i++)
{
cmbDisplay.Items.Add(dt.Rows[i]["SeatNo"]);
}
}
You need to fill your DataTable with data!
You might also consider the following:
using(OleDbDataReader reader = command.ExecuteReader())
{
while(reader.Read())
{
cmbDisplay.Items.Add(reader.GetValue(reader.GetOrdinal("SeatNo"));
}
}
This way you don't even need to use a DataTable; this is a more efficient approach for large sets of data.
As an aside, you may wish to consider using Using:
using(OleDbConnection connect = db.dbConnect())
{
try
{
connect.Open();
//MessageBox.Show("Opened");
using(OleDbCommand command = new OleDbCommand())
{
command.Connection = connect;
command.CommandText = "SELECT * FROM Categories";
using(IDataReader reader = command.ExecuteReader())
{
while(reader.Read())
{
cmbDisplay.Items.Add(reader.GetValue(reader.GetOrdinal("SeatNo"));
}
}
}
}
catch (Exception ex)
{
MessageBox.Show("An erorr occured:" + ex);
}
}
This will ensure your connection, command and reader objects are disposed. This is not appropriate if you intend to hold onto an instance of your connection however as it will be closed AND disposed as soon as your code leaves the using statement.
There is missing filling DataTable dt with datas, which are returned by your sql command.
try with this code - in your sample you don't bind your table with data, you create new instance of table.
$ private void chkDetailsButton_Click(object sender, EventArgs e)
{
if (radioButtonA.Checked)
{
OleDbConnection connect = db.dbConnect();
try
{
connect.Open();
MessageBox.Show("Opened");
OleDbCommand command = new OleDbCommand();
command.Connection = connect;
command.CommandText = "Select * from Categories";
OleDbDataReader myReader = command.ExecuteReader();
while (myReader.Read())
{
cmbDisplay.Items.Add(myReader["SeatNo"]);
}
}
catch (Exception ex)
{
MessageBox.Show("Exception in Database" + ex);
}
finally
{
connect.Close();
}
}
}
I can't believe this. :D
When are you exactly filling the DataTable with data from DB?
There is nothing in between
DataTable dt = new DataTable();
and
for (int i = 0; i < dt.Rows.Count; i++)
you can fill combobox with Datatable :
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Test;Integrated Security=True");
SqlDataAdapter da = new SqlDataAdapter("select * from Books",con);
DataTable dt = new DataTable();
da.Fill(dt);
comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "ID";
comboBox1.DataSource = dt;
You are not filling data in Dataset before attaching try this
if(radio.checked)
{
try
{
connect.Open();
MessageBox.Show("Opened");
OleDbCommand command = new OleDbCommand();
command.Connection = connect;
command.CommandText = "Select * from Categories";
OleDbDataAdapter db = new OleDbDataAdapter();
DataSet ds = new DataSet();
db.SelectCommand = command;
db.Fill(ds);
for(int i=0;i<ds.Tables[0].Rows.Count;i++)
{
cmbDisplay.Items.Add(ds.Tables[0].Rows[i][0].ToString());
}
cmDisplay.DataBind();
}
catch (Exception ex)
{
MessageBox.Show("Exception in Database" + ex);
}
finally
{
connect.Close();
}
}

Categories