Search 2 "unrelated" Access tables with button click - c#

I have 2 tables in an Access database. Currently I have a c# winform app in VS 2015 with 2 forms that have a search button on each that will search that particular table The only similarity is the SerialNumber field but it is unrelated as the Serial Numbers for each table are for different equipment. Any tips on how to perform a search of both tables with 1 button?
private void searchItembtn_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(serialSearch.Text))
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.Transaction = transaction;
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();
}
}

Create a UNION query in Access, that will contain data from both tables:
SELECT
SerialNumber,
InventoryField1 AS Field1,
InventoryFieldN AS FieldN
FROM Inventory
UNION ALL
SELECT
SerialNumber,
CompetitiveField1 AS Field1,
CompetitiveFieldN AS FieldN
FROM Competitive
Then use this query as the row source in your command (CompetitiveInventory would be the query name):
string searchFB = "SELECT * FROM CompetitiveInventory WHERE SerialNumber=#searchSerial";
Alternatively, a JOIN may be what you want, depending on the requirement.

Related

SQL Query not Retrieving All Rows in C# Application

I have a stored procedure created in my SQL Server 2012 database that selects data from multiple tables. In C#, I use this procedure to show data in a datagridview.
Issue: when I execute the query in SQL Server, I get the correct result which returns 3 rows, but in C#, it returns only 2 rows.
Query:
SELECT DISTINCT
Employee.Employee_No AS 'Badge'
,Employee.Employee_Name_Ar AS 'Emp Name'
,Employee.Basic_Salary AS 'Basic'
,Employee.Current_Salary AS 'Current'
,Attendance.Present
,Attendance.Leave
,Attendance.Othe_Leave AS 'OL'
,Pay_Slip.Salary_Amount AS 'Sal. Amt.'
,(ISNULL(Pay_Slip.OverTime1_Amount, 0.00) + ISNULL(Pay_Slip.OverTime2_Amount, 0.00)) AS 'O/T Amt.'
,(ISNULL(Pay_Slip.Salary_Amount, 0.00) + ISNULL(ISNULL(Pay_Slip.OverTime1_Amount, 0.00) + ISNULL(Pay_Slip.OverTime2_Amount, 0.00), 0.00)) AS 'Sal. & O/T'
,Pay_Slip.Trasnport AS 'Allow'
,Pay_Slip.CostofLiving AS 'O.Allow'
,Pay_Slip.Gross_Salary AS 'T Salary'
,Pay_Slip.Insurance1_Amount AS 'ss 7%'
,Pay_Slip.Insurance2_Amount AS 'ss 11%'
,(ISNULL(Pay_Slip.Insurance1_Amount, 0.00) + ISNULL(Pay_Slip.Insurance2_Amount, 0.00)) AS 'Total s.s'
,Pay_Slip.Tax
,Pay_Slip.Personal_Loans AS 'Advance'
,Pay_Slip.Other_Deductions AS 'Ded.'
,Pay_Slip.Net_Salary AS 'Net'
FROM Pay_Slip
LEFT JOIN Employee ON Pay_Slip.Employee_No = Employee.Employee_No
LEFT JOIN Attendance ON Pay_Slip.Employee_No = Attendance.Employee_No
WHERE Pay_Slip.Month = '5'
AND Pay_Slip.Year = '2020'
AND Attendance.Month = '5'
AND Attendance.Year = '2020'
Executing this query in SQL Server returns 3 rows which are the employee slips on May-2020 (They all have values in May-2020).
C# code:
private void dateTimePicker_ReportDate_ValueChanged(object sender, EventArgs e)
{
try
{
DateTime date = dateTimePicker_ReportDate.Value;
String Month = dateTimePicker_ReportDate.Value.ToString("MM");
String Year = dateTimePicker_ReportDate.Value.ToString("yyyy");
String str = "server=localhost;database=EasyManagementSystem;User Id=Jaz;Password=Jaz#2020;Integrated Security=True;";
String query = "Execute EMP_PAY_ATT_Selection #Month, #Year";
SqlConnection con = null;
con = new SqlConnection(str);
SqlCommand cmd= new SqlCommand(query, con);
cmd.Parameters.Add("#Month", SqlDbType.Int).Value = Convert.ToInt32(Month);
cmd.Parameters.Add("#Year", SqlDbType.Int).Value = Convert.ToInt32(Year);
SqlDataReader sdr;
con.Open();
sdr = cmd.ExecuteReader();
if (sdr.Read())
{
DataTable dt = new DataTable();
dt.Load(sdr);
dataGridView_Report.DataSource = dt;
dataGridView_Report.EnableHeadersVisualStyles = false;
dataGridView_Report.ColumnHeadersDefaultCellStyle.BackColor = Color.LightBlue;
}
else
{
dataGridView_Report.DataSource = null;
dataGridView_Report.Rows.Clear();
}
con.Close();
}
catch (Exception es)
{
MessageBox.Show(es.Message);
}
}
Again, when running this, it only returns 2 rows on the datagridview. While it should be 3 rows.
These are the tables:
The DbDataReader.Read method advances the reader to the next record.
There is no way to rewind a data reader. Any methods that you pass it to will have to use it from whatever record it is currently on.
If you want to pass the reader to DataTable.Load(), do not Read from it yourself. If you merely want to know if it contains records, use HasRows.

C#: how to add 2 values in ComboBox from stored procedure

I have TWO questions, first how to add 2 values and second is: if we add 2 values so we need to change the code when we save combo-box value in database (second question with code I also ask from end of this question)?
I need to add 2 values from table dep_Id and dep_Name in `ComboBox; like this:
(Department ID: Department Name)
This is the stored procedure:
CREATE PROCEDURE [dbo]. SelectComoboxData_SP
AS
SELECT dep_Id, dep_Name
FROM department
RETURN 0
This is the C# code:
public void updateDepartmentList()
{
refresh_DataGridView();
SqlCommand cmd = new SqlCommand("SelectComoboxData_SP", con);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
try
{
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
com_boxDepartment.Items.Add(dr["dep_Id"]);
com_boxDepartment.SelectedIndex = 0;
}
dr.Close();
}
catch (Exception ex)
{
MessageBox.Show("<<<INVALID SQL OPERATION \n" + ex);
}
con.Close();
}
Let me also know when I select any department from the combobox so now I wrote this code
cmd.Parameters.AddWithValue("#dId", com_boxDepartment.Text);
for saving by id, so when add 2 values in combobox so we need to change anything?
If it were my C# I'd do it more like this (though I'd use strongly typed datasets)
public void updateDepartmentList()
{
refresh_DataGridView();
SqlCommand cmd = new SqlCommand("SelectComoboxData_SP", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
com_boxDepartment.DataSource = dt;
com_boxDepartment.DisplayMember = "dep_Name";
com_boxDepartment.ValueMember = "dep_Id";
}
Your combo will show "History Department" for example, but when you ask it for the .SelectedValue it will return e.g. 2 (the id for the history department)

How to get ID of the Last Inserted Record in SQL using ASP.net

Here is my code
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (!string.IsNullOrWhiteSpace(Request.QueryString["id"]))
{
string clientId = Context.User.Identity.GetUserId();
if (clientId != null)
{
int id = Convert.ToInt32(Request.QueryString["id"]);
customize1 customize = new customize1
{
client_id = clientId,
product_id = id,
paper_type = Labelpt.Text,
corner = Labelpc.Text,
shipping_type = Labelsp.Text,
text = TextBox3.Text,
amount = Convert.ToInt32(lbResult.Text)
};
customizeModel model = new customizeModel();
Label9.Text = model.Insertcustomize(customize);
con.Open();
SqlCommand cmd2 = con.CreateCommand();
cmd2.CommandType = CommandType.Text;
cmd2.CommandText = "select top 1 * from customize1 where client_id='"+clientId+"' order by Id desc ";
cmd2.ExecuteNonQuery();
DataTable dt2 = new DataTable();
SqlDataAdapter da2 = new SqlDataAdapter(cmd2);
da2.Fill(dt2);
foreach (DataRow dr2 in dt2.Rows)
{
customizeid = dr2["Id"].ToString();
}
con.Close();
}
}
}
I need the last row id but my query does not generate any value.I also check my query in SSMS and query is working fine but in asp it is not generating any data and for inserting record i used the concept of class and entity relationship.
Any Solution.
Brother there are two ways:
One is when you insert your row place after the Insert query this:
SELECT SCOPE_IDENTITY()
For example:
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
SELECT SCOPE_IDENTITY()
It gives the inserted ID back.
The second way is this query;
SELECT id FROM table ORDER BY id DESC LIMIT 1
If you keep struggling with problems be open to ask more.

C#, Access Search through multiple tables for a Serial Number

I have 1 Access database with 2 tables. I am using a C# winforms application. I have Serial Number fields in each table but nothing is related. I have a form with a text field and a button to search for a Serial Number, then will return results into a datagrid on the form. Currently I can simply search 1 table. What I would like to do is type in the number, hit the button and return the value after searching both tables. I would rather do this without a union because somehow I need to set the table name in a text box when the results return.
private void btnSearch_Click(object sender, EventArgs e)
{
OleDbCommand command = new OleDbCommand();
OleDbDataAdapter db = new OleDbDataAdapter(command);
DataTable dt = new DataTable();
if (!string.IsNullOrEmpty(txtSerial.Text))
{
try
{
connection.Open();
command.Connection = connection;
command.Transaction = transaction;
command.Parameters.Add("#searchSerial", OleDbType.VarWChar).Value = txtSerial.Text;
string searchFB = "SELECT (SerialNumber) FROM Inventory WHERE SerialNumber = #searchSerial";
command.CommandText = searchFB;
db.Fill(dt);
dgResults.DataSource = dt;
connection.Close();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Message);
connection.Close();
}
}
}

OleDbCommand select does not return expected rows

I have two Access tables, namely Projects, including the rows of projectTitle and partyID, and ProjectParty, including the rows of title and ID.
private void btnSearch_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=HesabKetab.accdb;Persist Security Info=False;";
//search in the database
OleDbCommand oleCmd = new OleDbCommand();
oleCmd.Connection = conn;
if (radioBtnByTitle.Checked)
{
oleCmd.CommandText = "SELECT * FROM Projects WHERE projectTitle=#projectTitle";
oleCmd.Parameters.AddWithValue("#projectTitle", txtProjectTitle.Text);
}
else if (radioBtnByParty.Checked)
{
oleCmd.CommandText = "SELECT * FROM Projects WHERE partyID=#partyID";
oleCmd.Parameters.AddWithValue("#partyID", comboParty.SelectedValue.ToString());
}
//execute query
OleDbDataAdapter ole_da = new OleDbDataAdapter(oleCmd);
DataTable dt= new DataTable();
try
{
conn.Open();
ole_da.Fill(dt);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
dataGridViewDisplaySearchResults.DataSource = dt;
conn.Close();
}
In the above code I am trying to retrieve the values of the Projects Access database table. The second if is successful and it loads the queried rows into DataGridView. But the first if (when true) does not return the expected values. In fact, it loads nothing into the DataGridView. I have no idea why the query does not work when I try to do the select based on projectTitle. I tried debugging but I got no clue which parameters were being passed to the select command. Where am I wrong?
instead txtProjectTitle.ToString() in the first condition, isn't it txtProjectTitle.Text

Categories