mysql parameters passing not implementing asp.net - c#

I have 3 tables 1>disease_table [columns=] (disease_id,disease_name)2>symptom_table [columns=] (symptom_id,symptom_name)3>disease_symptom [columns=] (disease_id,symptom_id)
there is a checkboxlist on my web page which has symptoms where text=fever, value='fever'..and so on but the problem is that I get no output when I pass parameter to the sql stmt., it doesn't give any output.Also if I pass static parameter (if I choose to pass all the available symptoms) it gives me repeated disease names.
Here is my code:
protected void Button1_Click(object sender, EventArgs e)
{
MySqlConnection connection = new MySqlConnection(ConfigurationManager.ConnectionStrings["myconstring"].ConnectionString);
connection.Open();
symptons = String.Join(", ", CheckBoxList1.Items.Cast<ListItem>().Where(i => i.Selected).Select(i => i.Value).ToArray());
Label3.Text = symptoms;
MySqlCommand cmd = new MySqlCommand("select d.dname from disease d inner join diseasesymptom ds on ds.did = d.did inner join symptom s on s.sid = ds.sid where s.sname in (#pSymptoms)", connection);
cmd.Parameters.AddWithValue("#pSymptoms", symptoms);
using (MySqlDataAdapter sda = new MySqlDataAdapter())
{
cmd.Connection = connection;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
sql stmt :
selectd.name, d.disease_id
from Disease d
inner join DiseaseSymptom ds on ds.disease_id = d.disease_id
inner join Symptom s on s.symptom_id = ds.symptom_id
where s.name in ('Fever');
output: if I pass all the parameters(static) then I get all available diseases multiple times (e.g :if disease 'd1' has 2 symptoms and I choose 2 of those symptoms that disease 'd1' is displayed twice)

Related

C# Using value from Listbox1 for SQL Query to filter Listbox2

I have three SQL Tables - Team (Id, Name), Player (Id, Name) and TeamPlayer (Id, TeamID, PlayerID). I also have two ListBoxes on my Form and want to filter the 2nd ListBox when an Item is selected on the 1st ListBox.
This is mostly setup but I'm having issues where the code is not liking the value being passed to it in the LstTeams_SelectedIndexChanged method at the commented lines.
private void Form1_Load(object sender, System.EventArgs e)
{
showTeams();
}
private void showTeams()
{
// Create the SQL Query, and an SqlDataAdapter using this query and sqlConnection declared earlier
string query = "select * from Team";
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(query, sqlConnection);
// Get the 'Team' Table and Fill it
DataTable teamTable = new DataTable();
sqlDataAdapter.Fill(teamTable);
// Populate the 'Team' ListBox with the 'Team' Table
lstTeams.DataSource = teamTable.DefaultView;
lstTeams.DisplayMember = "Name";
lstTeams.ValueMember = "Id";
}
private void LstTeams_SelectedIndexChanged(object sender, System.EventArgs e)
{
string TeamID = lstTeams.GetItemText(lstTeams.SelectedValue);
MessageBox.Show("TeamID: " + TeamID);
// Create the SQL Query, and an SqlDataAdapter using this query and sqlConnection declared earlier
string query = "select * from Player p inner join TeamPlayer tp on p.Id = tp.PlayerID where tp.TeamID = #TeamID";
SqlCommand sqlCommand = new SqlCommand(query, sqlConnection);
sqlCommand.Parameters.AddWithValue("#TeamID", lstTeams.SelectedValue); // this
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand); // causes the dataadapter to error
// Get the 'Team' Table and Fill it
DataTable teamTable = new DataTable();
sqlDataAdapter.Fill(teamTable);
// Populate the 'Team' ListBox with the 'Team' Table
lstPlayers.DataSource = teamTable.DefaultView;
lstPlayers.DisplayMember = "Name";
}
My Error is:
System.ArgumentException: 'No mapping exists from object type System.Data.DataRowView to a known managed provider native type.'
I've looked up some solutions but have been unable to get a working result.
Thank you for any help provided :).
After further research and some direction from comments made to my question, I have found success with the following:
DataRowView data = lstTeams.SelectedItem as DataRowView;
int TeamID = int.Parse(data["Id"].ToString());
string query = "select * from Player p inner join TeamPlayer tp on p.Id = tp.PlayerID where tp.TeamID = " + TeamID;
Inside the ListBox1.SelectedIndexChanged method.

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.

App doesn't run it crashed directly after I started it

I have a problem, this is my code:
DataTable DT1 = new DataTable();
public static DataTable DATASETRETURN(string queryString)
{
DataSet DS = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter
{
SelectCommand = new SqlCommand(queryString, CLSERVICES.CON)
};
adapter.Fill(DS, "TABLE");
return DS.Tables["TABLE"];
}
private void FE_C_HISTORIQUE_Load(object sender, EventArgs e)
{
E_HISTORIQUE_LV_HISTORIQUE_04.Items.Clear();
string req = "select H.NHistorique, P.Intitulle, H.QuantiteVendu, P.PrixVente,"+
"(P.PrixVente * H.QuantiteVendu) as PQ, H.TypeAction, H.DateAction " +
"from HISTORIQUE as H, PRODUIT as P" +
"where (P.NProduit = H.NProduit)"+
"order by H.NHistorique desc";
DT1 = DATASETRETURN(req);
for (int i = 0; i < DT1.Rows.Count; i++)
{
ListViewItem LV = new ListViewItem(DT2.Rows[i][0].ToString());
LV.SubItems.Add(DT1.Rows[i][1].ToString());
LV.SubItems.Add(DT1.Rows[i][2].ToString());
LV.SubItems.Add(DT1.Rows[i][3].ToString());
LV.SubItems.Add(DT1.Rows[i][4].ToString());
LV.SubItems.Add(DT1.Rows[i][5].ToString());
LV.SubItems.Add(DT1.Rows[i][6].ToString());
E_HISTORIQUE_LV_HISTORIQUE_04.Items.Add(LV);
}
}
After I run the app, I get an error in method DATASETRETURN oin the line
adapter.Fill(DS, "TABLE");
The error is:
System.Data.SqlClient.SqlException
"\"P\" is not a recognized table hints option. If it is intended as a parameter to a table-valued function or to the CHANGETABLE function, ensure that your database compatibility mode is set to 90."
Is there is any solution?
problem caused by the missing spaces between "P_where" and between "H.NProduit)_order"
when specifying multiline queries I prefer:
string req = #"
select H.NHistorique,P.Intitulle,H.QuantiteVendu,P.PrixVente,
(P.PrixVente*H.QuantiteVendu)as PQ,H.TypeAction,H.DateAction
from HISTORIQUE as H, PRODUIT as P
where(P.NProduit = H.NProduit)
order by H.NHistorique desc
";
this way you decrease the chance of missing new lines in your queries.

changing value of cell on condition in gridview - c#

I have fetched the data from SQL server to datagridview but I don't know how to change the cell value. I have to change the fetched value 1 and 0 to available and unavailable. here is my code for fetching data ... please help.
private void btnsearch_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("server = 192.168.100.6;Database=sms;UID=sa;Password=1234;");
SqlCommand cmd = new SqlCommand("Select id as 'Book ID',name as 'Name' , status as 'Status' from book where Name = #name", con);
cmd.Parameters.AddWithValue("#name", txtFirstName.Text);
try
{
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataTable dt = new DataTable();
da.Fill(dt);
BindingSource bsource = new BindingSource();
bsource.DataSource = dt;
dataGridView1.DataSource = bsource;
}
catch (Exception ec)
{
MessageBox.Show(ec.Message);
}
// chage_value();
dataGridView1.Show();
}
}
Please find below answer
private void btnsearch_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("server = 192.168.100.6;Database=sms;UID=sa;Password=1234;");
string sSql=#"Select id as 'Book ID',name as 'Name' ,
Case when status=0 then 'unavailable' else 'available '
End as 'Status' from
book where Name ='"+txtFirstName.Text +"'"
SqlCommand cmd = new SqlCommand(sSql, con);
try
{
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
}
catch (Exception ec)
{
MessageBox.Show(ec.Message);
}
// chage_value();
dataGridView1.Show();
}
}
First of all, try to store your queries in variables. This will help you in the long run. Also, it is good practise to check whether you are connected or not before trying to send a query away to the server. It is important to remeber that when you fetch data from your server, it will most likely be seen as a string, so if you want to compare it as a number, you need to convert it first.
What you could do is something similar to what i've written below. You count the amount of answers your query returns, then loop through them and check whether they are 0 or 1. Then just replace the value with Avaliable or Unavaliable.
if (dbCon.IsConnect()){
MySqlCommand idCmd = new MySqlCommand("Select * from " + da.DataGridView1.Text, dbCon.Connection);
using (MySqlDataReader reader = idCmd.ExecuteReader()){
// List<string> stringArray = new List<string>(); // you could use this string array to compare them, if you like this approach more.
while (reader.Read()){
var checkStatus= reader["Status"].ToString();
Console.WriteLine("Status: " + checkStatus.Split(' ').Count()); //checks how many items you've got.
foreach (var item in checkStatus.Split(' ').Select(x => x.Trim()).Where(x => !string.IsNullOrWhiteSpace(x)).ToArray()){
var item2 = 0.0; // your 0 or 1 for avaliable or unavaliable..
try{
item2 = double.Parse(item.ToString());
if(strcmp(item2,'0') == 1){ //assuming you only have 0's and 1's.
item2 = "unavaliable";
}else{
item2 = "avaliable";
}
}
catch (Exception){
//do what you want
}
Console.WriteLine("item: " + item2);
}
}
dbCon.Close();
}
}
return //what you want;
}

access 2007 query and c# datatable show different output

I have the below query in access 2007 which gave me correct results using the sql design view of access..
SELECT B1.LAYER_TYPE,
B1.LAYER_NAME AS LAYER_NAME,
B2.LAYER_NAME AS RELATED_LAYER_NAME,
B3.LAYER_NAME AS RELATED_LAYER2_NAME,
C.RULE_NAME
FROM (((NCS_RULES_RELATIONS AS A
LEFT JOIN NCS_LAYERS AS B1 ON A.LAYER_ID = B1.LAYER_ID)
LEFT JOIN NCS_LAYERS AS B2 ON A.RELTD_LAYER_ID = B2.LAYER_ID)
LEFT JOIN NCS_LAYERS AS B3 ON A.RELTD_LAYER2_ID = B3.LAYER_ID)
LEFT JOIN NCS_RULES AS C ON A.RULE_ID = C.RULE_ID
ORDER BY B1.LAYER_TYPE;
the results are below :
but when i try to get the results to a datatable using c# and oledbconnection to access, the RULE_NAME field value for the last row shows weird results(see pic below).
my code for retrieving table is below:
public DataTable GetTable(string strSelectSQL)
{
if (this.con.State != ConnectionState.Open)
con.Open();
DataTable dt = new DataTable();
DataSet ds = new DataSet();
IDbCommand command = con.CreateCommand();
command.CommandText = strSelectSQL;
command.Connection = con;
IDbDataAdapter da = factory.CreateDataAdapter();
da.SelectCommand = command;
da.Fill(ds);
dt = ds.Tables[0];
con.Close();
return dt;
}
can somebody help me with this strange behavior?
Seems everything is fine. My guess you have multiline value in Rule_name field like this: AnnoFromLine\n\rDimOnLine. Datagridview displaying multiline value as you can see and sql design view diplaying just first line.

Categories