I am trying to fill in a combobox on my winform app from the database. I know there is info in the DB. I know the SP works. It returns the correct ColumnNames. But the DataSet itself is empty? Help!?!?
Call from my form-->
cboDiagnosisDescription.Properties.DataSource = myDiagnosis.RetrieveDiagnosisCodes();
The RetrieveDiagnosisCodes -->
public DataSet RetrieveDiagnosisCodes()
{
string tableName = "tblDiagnosisCues";
string strSQL = null;
DataSet ds = new DataSet(tableName);
SqlConnection cnn = new SqlConnection(Settings.Default.CMOSQLConn);
//strSQL = "select * from " & tableName & " where effectivedate <= getdate() and (termdate >= getdate() or termdate is null)"
strSQL = "select tblDiagnosisCues.*, tblDiagnosisCategory.Description as CategoryDesc, tblDiagnosisSubCategory.Description as SubCategoryDesc " + "FROM dbo.tblDiagnosisCategory INNER JOIN " + "dbo.tblDiagnosisSubCategory ON dbo.tblDiagnosisCategory.Category = dbo.tblDiagnosisSubCategory.Category INNER JOIN " + "dbo.tblDiagnosisCues ON dbo.tblDiagnosisSubCategory.SubCategory = dbo.tblDiagnosisCues.SubCategoryID " + "where effectivedate <= getdate() and (termdate >= getdate() or termdate is null) order by tblDiagnosisCues.Description";
SqlCommand cmd = new SqlCommand(strSQL, cnn) {CommandType = CommandType.Text};
SqlDataAdapter da = new SqlDataAdapter(cmd);
try
{
//cnn.Open();
da.Fill(ds);
}
catch (Exception ex)
{
throw;
}
finally
{
cmd.Dispose();
da.Dispose();
//ds.Dispose();
cnn.Close();
cnn.Dispose();
}
return ds;
}
The reason I know it is returning the correct column names is that I tried the following with a DevExpress LookUpEdit box and it populates the correct columns from the DB -->
var myDiagnosis = new Diagnosis();
var ds = myDiagnosis.RetrieveDiagnosisCodes();
lkuDiagnosis.Properties.DataSource = ds;
lkuDiagnosis.Properties.PopulateColumns();
lkuDiagnosis.Properties.DisplayMember = ds.Tables[0].Columns[1].ColumnName;
lkuDiagnosis.Properties.ValueMember = ds.Tables[0].Columns[0].ColumnName;
Ideas? Mainly, I don't even know how to proceed tracking this down...How to debug it?
EDIT 1
Based on a comment I ran the following SQL by itself and it returned 650 results...
select tblDiagnosisCues.*,
tblDiagnosisCategory.Description as CategoryDesc,
tblDiagnosisSubCategory.Description as SubCategoryDesc
FROM dbo.tblDiagnosisCategory
INNER JOIN dbo.tblDiagnosisSubCategory
ON dbo.tblDiagnosisCategory.Category = dbo.tblDiagnosisSubCategory.Category
INNER JOIN dbo.tblDiagnosisCues ON dbo.tblDiagnosisSubCategory.SubCategory = dbo.tblDiagnosisCues.SubCategoryID
where effectivedate <= getdate() and (termdate >= getdate() or termdate is null) order by tblDiagnosisCues.Description
//cnn.open();
...
//ds.dispose();
There is no need to specify a table name in the dataset constructor. The fill method will add a table. Also no need to open the connection since the sqldataadapter will open and close the connection for you. Also, I prefer to return a datatable as opposed to dataset with one table.
The code could be refactored to the following...of coure add the try catch if you want to log the exception.
public DataTable RetrieveDiagnosisCodes()
{
//string tableName = "tblDiagnosisCues";
DataSet ds = new DataSet();
Datatable dt = null;
//strSQL = "select * from " & tableName & " where effectivedate <= getdate() and (termdate >= getdate() or termdate is null)"
string strSQL = "select tblDiagnosisCues.*, tblDiagnosisCategory.Description as CategoryDesc, tblDiagnosisSubCategory.Description as SubCategoryDesc " + "FROM dbo.tblDiagnosisCategory INNER JOIN " + "dbo.tblDiagnosisSubCategory ON dbo.tblDiagnosisCategory.Category = dbo.tblDiagnosisSubCategory.Category INNER JOIN " + "dbo.tblDiagnosisCues ON dbo.tblDiagnosisSubCategory.SubCategory = dbo.tblDiagnosisCues.SubCategoryID " + "where effectivedate <= getdate() and (termdate >= getdate() or termdate is null) order by tblDiagnosisCues.Description";
using(SqlDataAdapter da = new SqlDataAdapter(strSQL, Settings.Default.CMOSQLConn))
{
da.Fill(ds);
}
if (ds.Tables.Count > 0)
{
dt = ds.Tables[0];
}
return dt;
}
If the data is properly binding to another control, it indicates that there is an issue with the databinding process. What does your databinding setup look like for the combobox in question? Are all the column names properly spelled and setup?
Related
I need to filter and query data by using 2 datetimepicker fromdate and todate
when click search button , I tried the following code but its not working :
private void BtnSearch_Click(object sender, EventArgs e)
{
string sql = #" SELECT [LAB_RESULTS].ORDER_ID as 'Order No.'
,labtests.TestId as 'Test Id'
,patients.Patient_No as 'Patient File No'
,Patients.Patient_Name as 'Patient Name'
,testname as 'Test Name'
,[RESULT_NUMBER] as 'Result'
,Machines.Machine_name as 'Machine'
,PatientCat.CatName as 'Category'
,departments.dept_name as 'Department'
,LAB_RESULTS.EXAMINED_BY as 'Examined By'
,LAB_RESULTS.EXAMINED_DATE as 'Examined Date'
,LAB_RESULTS.APPROVED_BY as 'Approved by'
,LAB_RESULTS.APPROVED_DATE as 'Approved Date'
,[RESULT_REPORT] as 'Report'
,[RESULT_NOTE] as 'Notes'
,[NORMAL_RESULT] as 'Normal'
,[UPDATED_BY]
,[UPDATED_DATE]
,REJECTED_BY
,REJECTED_DATE
,Lab_Reject_Reasons.Reject_Reason
FROM [dbo].[LAB_RESULTS]
inner join LabTests on LabTests.testid=LAB_RESULTS.TESTID
inner join Lab_orders_Cash on Lab_orders_Cash.cash_order_id = LAB_RESULTS.ORDER_ID
inner join Patients on Patients.Patient_No = Lab_orders_Cash.patient_no
inner join departments on LAB_RESULTS.deptid = departments.dept_id
inner join PatientCat on PatientCat.CatId = Lab_orders_Cash.catid
left join Machines on Machines.Machine_id = LAB_RESULTS.machine_id
left join Lab_Reject_Reasons on (LAB_RESULTS.REJECTED_REASON = Lab_Reject_Reasons.Reject_ID)
where [LAB_RESULTS].SAMPLE_STATUS in (5,6,8,10) ";
string condition = "";
string orderby = "";
DateTime fromDate ;
DateTime toDate ;
orderby += " order by LAB_RESULTS.ORDER_ID desc";
if (!DateTime.TryParse(dtFromDate.Text, out fromDate))
{
System.Windows.Forms.MessageBox.Show("Invalid From Date");
}
else if (!DateTime.TryParse(dtToDate.Text, out toDate))
{
System.Windows.Forms.MessageBox.Show("Invalid to Date");
}
else
{
condition += " and lab_orders_cash.order_date between '" + fromDate + " and '" + toDate + "'";
}
DataTable dt = data.fireDatatable(string.Format(sql + condition + orderby));
dgvResult.DataSource = dt;
dgvResult.Refresh();
}
I checked the questions in this site but no solution .
how to fix my condition to get the data between two dates?
this is the method fireDatatable which read data from the database :
public DataTable fireDatatable(string sql)
{
dt = new DataTable();
try
{
if (cn.State == ConnectionState.Closed) cn.Open();
cmd.Connection = cn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql;
ad.SelectCommand = cmd;
ad.Fill(dt);
return dt;
}
catch
{
// error in sql or table
return null;
}
finally
{
// performance and speed
SqlConnection.ClearPool(cn);
cmd.Dispose();
if (cn.State == ConnectionState.Open) cn.Close();
}
}
I got the solution from the chat people thank you all ,
you add first the single quote as mr haldo said:
else
{
condition += " and lab_orders_cash.order_date between '" + fromDate + "' and '" + toDate + "'";
}
then to see the error during runtime remove try and catch from the method as mr Fauzi88 said :
public DataTable fireDatatable(string sql)
{
dt = new DataTable();
if (cn.State == ConnectionState.Closed) cn.Open();
cmd.Connection = cn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql;
ad.SelectCommand = cmd;
ad.Fill(dt);
return dt;
// performance and speed
SqlConnection.ClearPool(cn);
cmd.Dispose();
if (cn.State == ConnectionState.Open) cn.Close();
}
When i choose From Date and Todate from datetimepicker to show data in datagridview at that time datagridview show me empty data , code is written button click evet, here im using access database
DateTime startT = new DateTime();
DateTime endT = new DateTime();
startT = dateTimePicker1.Value.Date;
endT = dateTimePicker2.Value.Date;
if (startT.Date > endT.Date)
{
MessageBox.Show("To Date Cannot be greater than Start Date");
}
else
{
string connetionString = null;
connetionString = ConfigurationManager.ConnectionStrings["AccessConnectionString"].ConnectionString;
con.ConnectionString = connetionString;
DataSet ds = new DataSet();
string sql = "SELECT Medicine_name,sum(Medicine_count) as Medicine_count,To_Date from Medicine_count_info where [To_Date] Between #" + startT.ToString("dd'/'MM'/'yyyy") + "#And #" + endT.ToString("dd'/'MM'/'yyyy") + "#group by Medicine_name,Medicine_count,To_Date order by Medicine_count desc ";
OleDbConnection connection = new OleDbConnection(connetionString);
OleDbDataAdapter dataadapter = new OleDbDataAdapter(sql, connection);
ds = new DataSet();
connection.Open();
dataadapter.Fill(ds);
connection.Close();
dataGridView1.DataSource = ds;
dataGridView1.DataMember = ds.Tables[0].TableName;
dataGridView1.Refresh();
}
First of all, in your select you are missing a space in "#And #"
Also,assuming [To_Date] is a datetime field, the problem is probably how you are building your select clause passing the data as string. Use DateTime fields instead and, of course ALWAYS USE PARAMETRIZED QUERIES. Something like this:
string sql = "SELECT Medicine_name,sum(Medicine_count) as Medicine_count,To_Date " +
"FROM Medicine_count_info " +
"WHERE [To_Date] Between #startDate And #endDate " +
"GROUP BY Medicine_name,Medicine_count,To_Date " +
"ORDER BY Medicine_count desc ";
OleDbDataAdapter dataadapter = new OleDbDataAdapter(sql, connection);
dataadapter.SelectCommand.Parameters.AddWithValue("#startDate", startT);
dataadapter.SelectCommand.Parameters.AddWithValue("#startDate", endT);
ds = new DataSet();
dataadapter.Fill(ds);
...
I am getting an error in my SQL command with which I am trying to retrieve values from a SQL Server database. It is showing a error in browser as mentioned in title. If I remove the brackets it shows error in AND operator
string jdate = (string)Session["jdate"];
string clas = (string)Session["class"];
string scode = (string)Session["scode"];
string dcode = (string)Session["dcode"];
cn = new SqlConnection(ConfigurationManager.ConnectionStrings["dummyConnectionString"].ToString());
// error shows up on this line
string slct = "SELECT Route.Route_Source, Route.Route_Destination, Flight.Flight_Name, Schedule.Depart_Time, Schedule.Arr_Time, Schedule.Route_rate_Ad , Seats." + jdate +
"Schedule.Sch_id FROM Schedule INNER JOIN Flight ON Schedule.Flight_Id = Flight.Flight_id INNER JOIN Route ON Schedule.Route_id = Route.Route_id INNER JOIN Seats ON Seats.Sch_id = Schedule.Sch_id WHERE (Route.Route_Source =" + scode + ") AND (Route.Route_Destination =" + dcode + ") AND (Seats.Class=" + clas + ") ORDER BY Schedule.Depart_Time, Schedule.Arr_Time, Flight.Flight_Name";
cn.Open();
SqlDataAdapter da = new SqlDataAdapter(slct, cn);
DataSet ds = new DataSet();
da.Fill(ds);
SearchView.DataSource = ds;
SearchView.DataBind();
You should use a parameterized query.
This would allow a more understandable query text, avoid simple syntax errors
(like the missing comma at the end of the first line (jdate)),
avoid Sql Injections and parsing problems with strings containing quotes or decimal separators
string slct = #"SELECT Route.Route_Source, Route.Route_Destination,
Flight.Flight_Name, Schedule.Depart_Time, Schedule.Arr_Time,
Schedule.Route_rate_Ad, Seats." + jdate + ", Schedule.Sch_id " +
#"FROM Schedule INNER JOIN Flight ON Schedule.Flight_Id = Flight.Flight_id
INNER JOIN Route ON Schedule.Route_id = Route.Route_id
INNER JOIN Seats ON Seats.Sch_id = Schedule.Sch_id
WHERE (Route.Route_Source = #scode)
AND (Route.Route_Destination =#dcode)
AND (Seats.Class=#class)
ORDER BY Schedule.Depart_Time, Schedule.Arr_Time, Flight.Flight_Name";
cn.Open();
SqlCommand cmd = new SqlCommand(slct, cn);
cmd.Parameters.AddWithValue("#scode", scode);
cmd.Parameters.AddWithValue("#dcode", dcode);
cmd.Parameters.AddWithValue("#class", clas);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
I am developing an ATM software in which I want to get report by entering the start date and end date. The date is saving in my table is in the form of string dd/MM/yyyy. I am trying the following code and getting the exception of incorrect syntax.
public DataTable getReportByDate(DateTime startDate, DateTime endDate)
{
try
{
DataTable table = new DataTable();
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlDataAdapter dataAdapter = new SqlDataAdapter("Select * from [Transaction] Where CAST(CurrDate AS Date) >=" + startDate + " AND CAST(CurrDate AS Date) <=" + endDate + ";", connectionString);
// Create a command builder to generate SQL update, insert, and
// delete commands based on selectCommand. These are used to
// update the database.
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
// Populate a new data table and bind it to the BindingSource.
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(table);
}
return table;
}
catch (Exception e)
{
return null;
}
}
Please help me.
Regards
Ok, first off, DO NOT turn the exception into a return null
catch(Exception e)
{
return null;
}
It is bad practice as you suck up EVERY possible exception.
Instead you should only catch the exceptions which the sql adapter is supposed to throw, or even better: do not catch them, instead document them and catch them further outward, because if something goes wrong in this method it means your SQL connection or your code is broken.
If you leave it as is you only hide problems and make debugging much harder.
Secondly, you should use parameters in your query.
Now to the syntax error: startDate and endDate are of type DateTime, so you should convert them to a string first with .ToString("dd/MM/yyyy") - this would be less of a hassle with parameters.
Change
SqlDataAdapter dataAdapter = new SqlDataAdapter("Select * from [Transaction] Where CAST(CurrDate AS Date) >=" + startDate + " AND CAST(CurrDate AS Date) <=" + endDate + ";", connectionString);
To
SqlDataAdapter dataAdapter = new SqlDataAdapter("Select * from [Transaction] Where CAST(CurrDate AS Date) >='" + startDate.ToString("yyyy-MM-dd HH:mm:ss") + "' AND CAST(CurrDate AS Date) <='" + endDate.ToString("yyyy-MM-dd HH:mm:ss") + "';", connectionString);
UPDATE:
SqlDataAdapter dataAdapter = new SqlDataAdapter("Select * from [Transaction] Where CAST(CurrDate AS Date) >='" + startDate.ToString("dd/MM/yyyy") + "' AND CAST(CurrDate AS Date) <='" + endDate.ToString("dd/MM/yyyy") + "';", connectionString);
You should definitely use parameters in your query - both to avoid SQL injection attacks, as well as improve performance (through execution plan reuse). No one so far has showed it - so here it is:
public DataTable getReportByDate(DateTime startDate, DateTime endDate)
{
DataTable table = new DataTable();
string sqlStmt =
"SELECT * FROM [dbo].[Transaction] " +
"WHERE CAST(CurrDate AS DATE) >= #startDate " +
"AND CAST(CurrDate AS DATE) <= #endDate";
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand(sqlStmt, connection))
{
cmd.Parameters.Add("#startDate", SqlDbType.Date).Value = startDate.Date;
cmd.Parameters.Add("#endDate", SqlDbType.Date).Value = endDate.Date;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(table);
}
return table;
}
}
I did try, the sql works normally in a query editor, however, it appears it can only work if parameterized.
So I'm reposting the code, I noticed a moderator converted my initial response to comment.
public DataTable getReportByDate(DateTime startDate, DateTime endDate)
{
DataTable table = new DataTable();
string query = "select * from [transaction] where cast(currdate as date) >= #startdate and cast(currdate as date) <= #enddate";
using (SqlConnection connection = new SqlConnection("server=(local);database=quicksilver;integrated security=true"))
{
connection.Open();
SqlCommand command = new SqlCommand(query);
command.Parameters.AddWithValue("#startdate", startdate);
command.Parameters.AddWithValue("#enddate", enddate);
command.Connection = connection;
SqlDataAdapter dataAdapter = new SqlDataAdapter(command);
//
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
dataAdapter.Fill(table);
}
return table;
}
In my SQL statement I use wildcards. But when I try to select something, it never select something. While when I execute the query in Microsoft SQL Server Management Studio, it works fine.
What am I doing wrong?
Click handler
protected void btnTitelAuteur_Click(object sender, EventArgs e)
{
cvalTitelAuteur.Enabled = true;
cvalTitelAuteur.Validate();
if (Page.IsValid)
{
objdsSelectedBooks.SelectMethod = "getBooksByTitleAuthor";
objdsSelectedBooks.SelectParameters.Clear();
objdsSelectedBooks.SelectParameters.Add(new Parameter("title", DbType.String));
objdsSelectedBooks.SelectParameters.Add(new Parameter("author", DbType.String));
objdsSelectedBooks.Select();
gvSelectedBooks.DataBind();
pnlZoeken.Visible = false;
pnlKiezen.Visible = true;
}
}
In my Data Access Layer
public static DataTable getBooksByTitleAuthor(string title, string author)
{
string sql = "SELECT 'AUTHOR' = tblAuthors.FIRSTNAME + ' ' + tblAuthors.LASTNAME, tblBooks.*, tblGenres.GENRE "
+ "FROM tblAuthors INNER JOIN tblBooks ON tblAuthors.AUTHOR_ID = tblBooks.AUTHOR_ID INNER JOIN tblGenres ON tblBooks.GENRE_ID = tblGenres.GENRE_ID "
+"WHERE (tblBooks.TITLE LIKE '%#title%');";
SqlDataAdapter da = new SqlDataAdapter(sql, GetConnectionString());
da.SelectCommand.Parameters.Add("#title", SqlDbType.Text);
da.SelectCommand.Parameters["#title"].Value = title;
DataSet ds = new DataSet();
da.Fill(ds, "Books");
return ds.Tables["Books"];
}
Try this:
string sql = "SELECT 'AUTHOR' = tblAuthors.FIRSTNAME + ' ' + tblAuthors.LASTNAME, tblBooks.*, tblGenres.GENRE "
+ "FROM tblAuthors INNER JOIN tblBooks ON tblAuthors.AUTHOR_ID = tblBooks.AUTHOR_ID INNER JOIN tblGenres ON tblBooks.GENRE_ID = tblGenres.GENRE_ID "
+"WHERE (tblBooks.TITLE LIKE #title);";
SqlDataAdapter da = new SqlDataAdapter(sql, GetConnectionString());
da.SelectCommand.Parameters.Add("#title", SqlDbType.Text);
da.SelectCommand.Parameters["#title"].Value = "%" + title + "%";
You can't include your query parameter inside a string literal. Do it like this instead:
WHERE (tblBooks.TITLE LIKE '%' + #title + '%');
Also, whenever you have a leading wildcard you should look into a full text index instead. Your query as written is doomed to be much slower than it could be, because you can't use index when you have a leading wild card.
The answer from John Allers is correct. As an aside, you should wrap the SqlDataAdapter in a using block:
using (SqlDataAdapter da = new SqlDataAdapter(sql, GetConnectionString()))
{
da.SelectCommand.Parameters.Add("#title", SqlDbType.Text);
da.SelectCommand.Parameters["#title"].Value = title;
DataSet ds = new DataSet();
da.Fill(ds, "Books");
return ds.Tables["Books"];
}