sort date into descending order - c#

I want to display the date into descending order in Gridview as default.
DataTable dt = new DataTable();
SqlDataAdapter adp =
new SqlDataAdapter("SELECT Customer.CustomerID, Customer.lastname, Customer.firstname,
Ticket.Date, Ticket.Store, Ticket.Amount, Ticket.NoStub " +
"FROM Customer INNER JOIN Ticket ON Customer.CustomerID = Ticket.CustomerID
WHERE Customer.CustomerID like " + txtCustomerID.Text, cn);
adp.Fill(dt);
gvHistory.DataSource = dt;

Just add:
order by Ticket.Date desc
to the end of your sql statement, like the following:
DataTable dt = new DataTable();
SqlDataAdapter adp = new SqlDataAdapter("SELECT Customer.CustomerID, Customer.lastname, Customer.firstname, Ticket.Date, Ticket.Store, Ticket.Amount, Ticket.NoStub " +
"FROM Customer INNER JOIN Ticket ON Customer.CustomerID = Ticket.CustomerID WHERE Customer.CustomerID like " + txtCustomerID.Text + " order by Ticket.Date desc", cn);
adp.Fill(dt);
gvHistory.DataSource = dt;

As #Adels answer you can order by changing your sql statement, if you want to do it by code. try DataGridView.Sort method as below
gvHistory.Sort(gvHistory.Columns["ColumnName"], ListSortDirection.Descending);

I suggest using the Sort function on the data grid, as Damith recommended
DO NOT PUT USER PARAMETERS DIRECTLY INTO THE SQL STATEMENT. You must use WHERE Customer.CustomerID like #customerId and then add a parameter to the command, with name = #customerId and value = txtCustomerID.Text. This 1) prevents user input from destroying the database, 2) prevents bloating the SQL plan cache.

System.Data.DataTable dt = new System.Data.DataTable();
System.Data.SqlClient.SqlDataAdapter adp = new System.Data.SqlClient.SqlDataAdapter(
"SELECT Customer.CustomerID,
Customer.lastname,
Customer.firstname,
Ticket.Date,
Ticket.Store,
Ticket.Amount,
Ticket.NoStub " +
"FROM Customer INNER JOIN Ticket ON
Customer.CustomerID = Ticket.CustomerID WHERE
Customer.CustomerID like " + txtCustomerID.Text + "
order by Ticket.Date desc", cn);
adp.Fill(dt);
gvHistory.DataSource = dt;

Related

how to query select data from table where first 3 character defined

i want to filter dropdownlist by first 3 charater on job code, this is my query
string result3 = Checked_By.ToString().Substring(0, 3);
SqlCommand cmd = new SqlCommand(" SELECT [Kode], [Nama]
FROM [Job] WHERE LEFT(Kode, = '" + result3 + "') ORDER BY
Nama ASC", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
con.Open();
sda.Fill(dt);
con.Close();
This is straightforward fix. First, fix SQL syntax error (SQL LEFT function takes 2 parameter, a string and a number. LEFT('abcdef', 3) returns abc), next rewrite using parameters. Something like this.
string result3 = Checked_By.ToString().Substring(0, 3);
SqlCommand cmd = new SqlCommand(" SELECT [Kode], [Nama] FROM [Job] WHERE LEFT(Kode, 3) = #result3 ORDER BY Nama", con); //ASC is OK but not required as it is default option
cmd.Parameters.Add("#result3", SqlDbType.Char, 3).Value = result3;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
//con.Open(); //not necessary. SqlDataAdapter.Fill opens connection if it needs
sda.Fill(dt);
//con.Close(); //and closed if it wasn't open before .Fill
"SELECT [Kode], [Nama]
FROM [Job] WHERE SUBSTR(Kode,1,3) = '" + result3 + "' ORDER BY
Nama ASC"

Combo box Where Clause

i have a table of POMain po_no and a table of Shipping invoice, then when i search the po_no, i will add an invoice. the thing i want to do is if the po_no already have an invoice the po_no in search button will not appear
public AddForm()
{
InitializeComponent();
string ID = cb_po_search.SelectedValue.ToString();
string strPRSconn = ConfigurationManager.ConnectionStrings["POSdb"].ConnectionString;
SqlConnection sc = new SqlConnection(strPRSconn);
sc.Open();
string strQry = "SELECT POMain.po_no FROM POMain LEFT JOIN Shipping ON POMain.po_no = Shipping.po_no WHERE Shipping.invoice IS NULL AND POMain.po_no = '" + ID + "'";
SqlCommand scmd = new SqlCommand(strQry, sc);
SqlDataReader dr = scmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("po_no", typeof(string));
dt.Load(dr);
cb_po_search.ValueMember = "po_no";
cb_po_search.DisplayMember = "po_no";
cb_po_search.DataSource = dt;
sc.Close();
}
}
You need to use a LEFT OUTER join here instead of an INNER join
string strQry ="SELECT POMain.po_no FROM POMain INNER JOIN Shipping ON POMain.po_no = Shipping.po_no WHERE Shipping.invoice IS NULL";
And you need to add another condition to the WHERE clause at the end:
AND POMain.po_no = " + ID
Having said that, you would be much better off using a stored procedure instead of trying to form an inline query.

fetch data into datagridview from textbox's selected text

In textbox I am fetching city name and when I select any city name, information related to that city should display on datagridview, to fetch other information about the state I used a foreign key because state table is different and its information is stored in another table so I fetch that information from foreign key state_id. Here is my code
DataTable dt = new DataTable();
SqlDataAdapter tda = new SqlDataAdapter("SELECT a1.type,a1.state_id,a1.desc1,a1.from_date,a1.to_date,a1.expr1005 FROM item_rate a1 FULL OUTER JOIN item_rate_state a2 ON a1.state_id=a2.state_id WHERE state_name='" + textBox2.Text + "'", scon);
tda.Fill(dt);
dataGridView2.DataSource = dt;
The query seems a little wrong
it should be
SqlDataAdapter tda = new SqlDataAdapter("SELECT a1.type,a1.state_id,a1.desc1,a1.from_date,a1.to_date,a1.expr1005 FROM item_rate a1 FULL OUTER JOIN item_rate_state a2 ON a1.state_id=a2.state_id WHERE a2.state_name='" + textBox2.Text + "'", scon);
i would suggest you to use SqlCommand and add parameters to query proper way as your code is vulnerable to sql injection!
Answer as per the comment.
since you do now want to show any record when textbox is empty simple on TextChanged event do this
if (!String.IsNotNullOrEmpty(textBox2.Text))
{
DataTable dt = new DataTable();
SqlDataAdapter tda = new SqlDataAdapter("SELECT a1.type,a1.state_id,a1.desc1,a1.from_date,a1.to_date,a1.expr1005 FROM item_rate a1 FULL OUTER JOIN item_rate_state a2 ON a1.state_id=a2.state_id WHERE a2.state_name='" + textBox2.Text + "'", scon);
tda.Fill(dt);
dataGridView2.DataSource = dt;
}
You have Try like this
Set textBox2.AutoPostBack="True" in design page
protected void textBox2_TextChanged(object sender, EventArgs e)
{
DataTable dt = new DataTable();
SqlDataAdapter tda = new SqlDataAdapter("SELECT a1.type,a1.state_id,a1.desc1,a1.from_date,a1.to_date,a1.expr1005 FROM item_rate a1 FULL OUTER JOIN item_rate_state a2 ON a1.state_id=a2.state_id WHERE state_name='" + textBox2.Text + "'", scon);
tda.Fill(dt);
dataGridView2.DataSource = dt;
}

Connecting two tables into one datagridview using RIGHT JOINT

I have got this code below, which should connect 2 tables (ZAJSLUZ and KLISLUZ) but I need to add into it condition to select only those from ZAJSLUZ where column AKCE = zakce.Text
Would someone improve my code please ?
It gives me error that there is "bad syntax near ="
DataTable dt = new DataTable();
//SqlDataAdapter SDA = new SqlDataAdapter("select * from zajsluz",spojeni);
SqlDataAdapter SDA = new SqlDataAdapter("SELECT zajsluz.akce ,zajsluz.text,klisluz.pocet FROM zajsluz RIGHT JOIN klisluz ON zajsluz.ID=klisluz.id WHERE zajsluz.akce="+zakce.Text, spojeni);
SDA.Fill(dt);
dtg_ksluzby.DataSource = dt;
check if zakce.Text is a valid string before.
string sZakce = string.Empty;
if(zakce != null && zakce.Text != null)
{
sZakce = zakce.Text;
}
string sQuery = string.Format("SELECT zajsluz.akce ,zajsluz.text,klisluz.pocet FROM zajsluz RIGHT JOIN klisluz ON zajsluz.ID=klisluz.id WHERE zajsluz.akce= '{0}'", sZakce)
SqlDataAdapter SDA = new SqlDataAdapter(sQuery, spojeni);
i also suggest you to use the using block if you work with DataAdapters, so your adapter is disposed automatically.
using (SqlDataAdapter a = new SqlDataAdapter("SELECT * FROM table", con))
{
// use your adapter a
}
Change your line like this.
SqlDataAdapter SDA = new SqlDataAdapter("SELECT zajsluz.akce ,zajsluz.text,klisluz.pocet FROM zajsluz RIGHT JOIN klisluz ON zajsluz.ID=klisluz.id WHERE zajsluz.akce='"+zakce.Text+"'", spojeni);
...zajsluz.akce=+"zakce.Text,...
you might want to change it into
...zajsluz.akce='"+zakce.Text+"'",...
Change your line to
SqlDataAdapter SDA = new SqlDataAdapter("SELECT zajsluz.akce ,zajsluz.text,klisluz.pocet FROM zajsluz RIGHT JOIN klisluz ON zajsluz.ID=klisluz.id WHERE zajsluz.aakce='" + zakce.Text + "'", spojeni);
SqlDataAdapter SDA = new SqlDataAdapter("SELECT zajsluz.akce ,zajsluz.text,klisluz.pocet FROM zajsluz RIGHT JOIN klisluz ON zajsluz.ID=klisluz.id WHERE zajsluz.akce= '" +zakce.Text +"'", spojeni);

Dataset returning ZERO results

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?

Categories