I know it is a repeated question but i have tried much but i am getting exception
$exception {"String was not recognized as a valid DateTime."} System.Exception {System.FormatException}
Following is my code please check and guide
SQL QUERY
SELECT gangId as gang, respectPoints as respectPoints,DATE_FORMAT( purchasedDate, '%d-%m-%Y') as date_purchase FROM tbl_gang t where gangId=" + gangId
Data Access Layer Code
DataTable dt = new DataTable();
MySqlCommand cmd = conn.CreateCommand();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
cmd.CommandText = inAppPurchaseQuery;
da.Fill(dt)
Sorting Code
dt = gangRPObj.getGangRPLogsBL(gangId, fromDate, toDate);
var sortedTable = dt.AsEnumerable()
.OrderBy(r => DateTime.ParseExact(("date_purchase"),
"dd-mm-yyyy", null))
.CopyToDataTable();
Thanks
You are passing string to datetime conversion that's why exception is coming. Try
var orderedRows = from row in dt.AsEnumerable()
let date = DateTime.ParseExact(row.Field<string>("date_purchase"),"dd-mm-yyyy", null)
orderby date
select row;
Sorting a date-column as string also doesn't sort correctly. You should also sort in the database instead of in memory and use parameters instead of string concatenation to prevent sql-injection and date-conversion-issues like this.
string sql = #"SELECT gangId as gang,
respectPoints as respectPoints,
DATE_FORMAT(purchasedDate, '%d-%m-%Y') as date_purchase,
FROM tbl_gang t
WHERE gangId=#gangId
ORDER BY purchasedDate ASC";
using (var cmd = new MySqlCommand(sql, conn))
using (var da = new MySqlDataAdapter(cmd))
{
da.SelectCommand.Parameters.Add("#gangId", MySql.Data.MySqlClient.MySqlDbType.Int32).Value = gangID;
da.Fill(dt); // no need to order this on client side
}
Related
I created a Windows Forms application in C# and my database in Visual Studio. I want to know how, if it's possible, to sort one of the columns in the table by clicking a button? Or how can I sort this column automatically without using a button?
I've tried to implement this sort in the code below, but it doesn't work :(
private c void button5_Click(object sender, EventArgs e)
{
SqlConnection sqlConnection = new SqlConnection("Here is my connecting string");
SqlCommand myCommand = new SqlCommand("SELECT * FROM [Information] ORDER BY (Перевозчик)", sqlConnection);
sqlConnection.Open();
myCommand.ExecuteNonQuery();
}
As found here: https://www.w3schools.com/sql/sql_orderby.asp
Sine we don't know what you want to oder we can only guess here.
But with the query you could try:
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC
In your case:
"SELECT * FROM [Information] ORDER BY (Перевозчик) ASC"
Best would be to use the visual query builder where you can query against your database. When you are happy with your result you can at least be sure that the query is correct.
How you can do that is explained here:
https://www.c-sharpcorner.com/article/connect-to-a-database-from-visual-studio/
Since the sqlconnection and the sqlcommand is disposable you should consider putting it in a using tag, like in this example.
https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlcommand?view=netframework-4.8
private static void ReadOrderData(string connectionString)
{
string queryString =
"SELECT OrderID, CustomerID FROM dbo.Orders;";
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand(
queryString, connection);
connection.Open();
using(SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader[0], reader[1]));
}
}
}
}
There is 2 way for sort data
1) sorting just data and fill into grid:
DataGridView datagridview1 = new DataGridView(); // for show data
DataTable dt1 = new DataTable(); // have data
DataTable dt2 = new DataTable(); // temp data table
DataRow[] dra = dt1.Select("", "ID DESC");
if (dra.Length > 0)
dt2 = dra.CopyToDataTable();
datagridview1.DataSource = dt2;
2) sort default view that is like of sort with grid column header:
DataGridView datagridview1 = new DataGridView(); // for show data
DataTable dt1 = new DataTable(); // have data
dt1.DefaultView.Sort = "ID DESC";
datagridview1.DataSource = dt1;
I found this solution here:
Sorting rows in a data table
For a listbox you could give this a shot
ArrayList q = new ArrayList();
foreach (object o in listBox4.Items)
q.Add(o);
}
q.Sort();
listBox5.Items.Clear();
foreach(object o in q){
listBox5.Items.Add(o);
}
I found this solution here:
Sorting a list of items in a list box
You need to do ExecuteDatareader then process the result coming from this call. ExecuteNonQuery cannot be used to retrieve data.
I am trying to drop down box in design but in database table category has duplicates. I tried to execute by using below code. But it is not executing. It just receiving all commands which I have been changes in properties:
cmd.CommandText = #"Select Distinct Category_Desc from
Database***name order
by Category_Desc";
adapter.SelectCommand = cmd;
SqlDataReader dr1 = cmd.ExecuteReader();
dr1.Read();
comboBoxCategory.ValueMember = "Category_Desc";
comboBoxCategory.DisplayMember = "Category_Desc";
comboBoxCategory.DataSource = dr1;
dr1.Dispose();
Can anyone please help how to execute distinct query from the code?
Data reader is a forward only cursor that you have to iterate and close after the last item.Look at this code segment
SqlDataReader dr1= command.ExecuteReader();
ArrayList arl= new ArrayList();
while (dr1.Read())
{
arl.Add(dr1("Category_Desc"));
}
dr1.close();
//If its a winform project use this
string [] str = al.ToArray(typeof(string));
FarPoint.Win.Spread.ComboBoxCellType cb = new
FarPoint.Win.Spread.ComboBoxCellType();
cb.Items = arl;
Use the adapter to fill a DataTable instead. You already have the adapter and it already has the SelectCommand assigned.
adapter.SelectCommand = cmd;
System.Data.DataTable dtCategories = new System.Data.DataTable();
adapter.Fill(dtCategories);
comboBoxCategory.ValueMember = "Category_Desc";
comboBoxCategory.DisplayMember = "Category_Desc";
comboBoxCategory.DataSource = dtCategories;
I have one DataTable that executes this SQL query on my MS Access database in C#:
DataTable dtCdDvd = cls.Fun_RetornaDataTable("SELECT tblCdDvd.Cod, tblCdDvd.Nome, tblCdDvd.Tamanho, tblTipo.Tipo, tblCdDvd.Grupo FROM [tblCdDvd] INNER JOIN [tblTipo] ON tblCdDvd.Tipo=tblTipo.Cod WHERE Status = TRUE");
If I use
DataRow[] result = dtCdDvd.Select("[Grupo]=0");
the result is 0 rows and exist registry with informed code.
The more interesting is if my SQL query runs
DataTable dtCdDvd = cls.Fun_RetornaDataTable("SELECT Grupo FROM tblCdDvd");
without join table my result is different of 0.
My function of return datatable
public DataTable Fun_RetornaDataTable(string query)
{
DataTable dt = null;
using (var dbcon = new OleDbConnection(Fun_ConnString()))
{
dbcon.Open();
if (dbcon.State == ConnectionState.Open)
{
var command = new OleDbCommand(query, dbcon);
dt = new DataTable();
dt.Load(command.ExecuteReader());
}
}
return dt;
}
Very difficult to understand the question, but a couple of things that stand out.
" WHERE Status = TRUE"
What is 'Status'? Is it defined in one of the tables uniquely?
When you run "SELECT Grupo FROM tblCdDvd", are you getting any rows returned?
"the result is 0 rows and exist registry with informed code"
What does this mean in English?
I'm having trouble updating a mySQL database with a datatable. I can do it with an INSERT statement, but the table fails the assignment when I insert a row with the error "Couldn't store <...> in date Column. I have millions of records to insert and I thought this way might be faster. I actually don't care about the time, just the date.
MySqlConnection con = new MySqlConnection();
con.ConnectionString = string.Format(#"server={0};userid={1};password={2};database={3};AllowZeroDatetime=True", srvr, user, pass, db);
MySqlCommand cmnd = new MySqlCommand();
cmnd.Connection = con;
con.Open();
cmnd.CommandText = "DROP TABLE IF EXISTS dateTest";
cmnd.ExecuteNonQuery();
cmnd.CommandText = "CREATE TABLE dateTest (date DATE, dateTime DATETIME)";
cmnd.ExecuteNonQuery();
string myDate = "2014-04-19";
string myDateTime = "2014-04-20 00:00:00";
//this code works
cmnd.CommandText = string.Format("INSERT INTO dateTest(date, dateTime) VALUES('{0}', '{1}')", myDate, myDateTime);
cmnd.ExecuteNonQuery();
MySqlDataAdapter da = new MySqlDataAdapter("SELECT * from dateTest", con);
MySqlCommandBuilder cb = new MySqlCommandBuilder(da);
DataTable tbl = new DataTable();
da.Fill(tbl);
foreach (DataRow row1 in tbl.Rows)
{
Debug.WriteLine(string.Format("{0} : {1}", row1["date"], row1["dateTime"]));
//returns: 4/19/2014 : 4/20/2014 12:00:00 AM
}
DataRow row2 = tbl.NewRow();
row2["date"] = myDate; //Errors here: Couldn't store <2014-04-19> in date Column. Expected type is MySqlDateTime.
row2["dateTime"] = myDateTime; //Also errors here: Couldn't store <2014-04-20 00:00:00> in dateTime Column. Expected type is MySqlDateTime.
tbl.Rows.Add(row2);
da.Update(tbl);
this is my first time trying to answer a question. Hope this help.
I think you have to convert the date to DateTime first before you can store it in mysql.
string myDateTime = "2014-04-20 00:00:00";
DateTime myDateTimeValue = DateTime.Parse(myDateTime);
Then
row2["dateTime"] = myDateTimeValue;
I have not tried it yet. Hope it works
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.