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.
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 searched a lot but could not find the right solution.
Lets say ill select data like:
using(MySqlConnection connection = new MySqlConnection(MyConnectionString))
using(MySqlCommand cmd = connection.CreateCommand())
{
connection.Open();
cmd.CommandText = "SELECT a.Id, a.Foo, b.Bar FROM tableA a, tableB b where a.Id = b.Id";
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
DataTable dt = ds.Tables[...]; //<== here is the problem
}
and I want to add this to a datatable,
How do I call the table in this case ?
Is it tableA ?
Does it matters how I name it ? (could I name it foobar as well???)
It is unclear what you are really asking for, but due to the length of comment and clarification, putting into an answer.
If you are trying to get multiple query results back from MySQL into a single "DataSet" (which can contain multiple tables), your query could contain multiple sql-statements and each would be returned into the dataset for you as different table results. For example, if you did something like...
using(MySqlConnection connection = new MySqlConnection(MyConnectionString))
using(MySqlCommand cmd = connection.CreateCommand())
{
connection.Open();
cmd.CommandText =
#"select * from TableA;
select * from TableB;
SELECT a.Id, a.Foo, b.Bar FROM tableA a, tableB b where a.Id = b.Id;";
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
}
Your dataset would have 3 tables in it in direct correlation of the queries provided..
ds.Tables[0] = result of tableA all records.
ds.Tables[1] = result of tableB all records.
ds.Tables[2] = result of JOIN query tableA and tableB.
you could then refer to them locally however you need to...
ds.Tables[0].TableName = "anyLocalTableNameReference".
var t1Recs = ds.Tables[0].Rows.Count;
etc... or even create your own individual datatable variable name without having to explicitly reference the dataset and table array reference
DataTable myLocalTableA = ds.Tables[0];
DataTable myLocalTableB = ds.Tables[1];
DataTable myJoinResult = ds.Tables[2];
Hopefully this clarifies a bunch with the querying and referencing of multiple data results returned and how to then reference to the tables individually.
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 have a DbConnect class which queries a MySQL database and store the results into a datatable - something like this:
public DataTable selectCombo()
{
string query = "SELECT DISTINCT month FROM printer_count";
if (this.OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(query, connection);
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
}
this.CloseConnection();
return dt;
}
Now how to retrieve the datatable from the class into the combo box main form? Can I do something like this?
ComboBox1.DataSource = dbConnect();
ComboBox1.DisplayMember = "Name"; // column name to display
You have two variables with the same name. (dt) One is defined as a string, the other one inside the if block is defined as a datatable. You return the empty string and this, of course, cannot work when you try to assign the DataSource of the combo
public DataTable selectCombo()
{
DataTable dt = new DataTable();
string query = "SELECT DISTINCT month FROM printer_count";
if (this.OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(query, connection);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
}
this.CloseConnection();
return dt;
}
Now you could write
....
ComboBox1.DisplayMember = "Name";
ComboBox1.DataSource = selectCombo();
.....
Also this code is not very safe. If, for any reason, you get an exception, the CloseConnection will not be called leaving an open connection around and this is very problematic for the stability of your system. However, fixing that problem, requires a different approach to you OpenConnection code. Instead of true this method should return the MySqlConnection object so your calling code could apply the using statement around the connection instance