DataGridView binding to two tables - c#

I have two tables. Most of the data is coming from the first table but there is a second table which has a column which I want to present in my UI
Here is my SQL Query
String sqlQuery = "SELECT u.CallerName, t.* FROM users u INNER JOIN tickets t ON u.id = t.user WHERE u.CallerName = 'tim.smith'";
I am using WinForms

If your query result is DataTable, then you can use Merge function to merge two table.
DataTable table1 = GetTable1Data(...);
DataTable table2 = GetTable2Data(...);
table1.Merge(table2, true);
Or if your query result is List, then you can use same approach as in DataTable case, using AddRange function:
List<YourClassType> list1 = GetList1Data(...);
List<YourClassType> list2 = GetList2Data(...);
list1.AddRange(list2, true);

It looks like you are doing just fine.
When binding with the DataGridView you can use:
Eval("CallerName")
to access the other column, but that column should work like all of the others.

Related

get column name in addition to the result (oracle)

I have a program in c# (asp.net environment) that dynamically runs ORACLE queries.
the queries can be like:
select * from app_costumers;
select a.first_name, a.last name, b.salary from app_costumers inner join app_costs b on a.id = b.id;
(As you can see, this is sometimes about a single table and sometimes more.
Sometimes writing the column names and sometimes using only in "*").
until now, I returned only the results,
But now I need to return the names of the results columns.
Do you have any idea how to do this?
(I can't use something like this:
SELECT column_name FROM user_tab_cols WHERE table_name = UPPER ('app_costumers');
Because it only fits for one table ...).
Thank you
You can use reader.GetName(i), for example:
var reader = cmd.ExecuteReader();
var columns = new List<string>();
for(int i=0;i<reader.FieldCount;i++)
{
columns.Add(reader.GetName(i));
}

C#: DataTable getting only one row of the search result

I'm having a sudden and strange problem with DataTable. I'm using C# with MySQL database to develop a system, and I'm trying to export custom reports. The problem is that, somehow, my DataTable is getting only one result (I've tested my query on MySQL and should be something like 30 results on the xls file and the DataTable).
Strangely, these functions are used in other parts of the system to export other kinds of reports, and work perfectly. This is the select function that I'm using:
public DataTable selectBD(String tabela, String colunas) {
var query = "SELECT " + colunas + " FROM " + tabela;
var dt = new DataTable();
Console.WriteLine("\n\n" + query + "\n\n");
try
{
using (var command = new MySqlCommand(query, bdConn)) {
MySqlDataReader reader = command.ExecuteReader();
dt.Load(reader);
reader.Close();
}
}
catch (MySqlException) {
return null;
}
bdConn.Close();
return dt;
}
And this is my query:
SELECT
cpf_cnpj, nomeCliente, agenciaContrato, contaContrato,
regionalContrato, carteiraContrato, contratoContrato,
gcpjContrato, avalistaContrato, enderecoContrato,
telefoneContrato, dataChegadaContrato, dataFatoGerContrato,
dataPrimeiraParcelaContrato, dataEmissaoContrato, valorPlanilhaDebitoContrato
FROM
precadastro
INNER JOIN
contrato
ON precadastro.cpf_cnpj = contrato.FK_cpf_cnpj
LEFT JOIN faseprocessual
ON contrato.idContrato = faseprocessual.FK_idContrato
And that is the result of the query on SQLyog
I've tested and the DataTable returned by the function only receive the one row, and it's not the first row of the MySQL results. Someone had this kind of problem before?
DataTable load expects primary key from your data (supplied by DataReader) and tries to guess it from passed rows. Since there's no such key, Load method guesses it's the first column (cpf_cnpj). But, values in that column aren't unique so the each row gets overwritten by next one, and the result is just one row in your DataTable.
It's the issue that persist for years, and I'm not sure there's one solution to rule them all. :)
You can try:
change query so that some unique values get into first column (unfortunately, I can't see something unique in your screenshot) or concatenate two or more values to get unique value.
Prepare DataTable by yourself by creating columns (this mirroring structure of resultset) and then iterate through DataReader to copy data.
add some autoincrement value in your query (or make temporary table with auto_increment column then fill that table)
Last suggestion could be something like this (I haven't worked much with mySql, so this is some suggestion i have googled :)):
SELECT
#i:=#i+1 AS id,
cpf_cnpj, nomeCliente, agenciaContrato, contaContrato,
regionalContrato, carteiraContrato, contratoContrato,
gcpjContrato, avalistaContrato, enderecoContrato,
telefoneContrato, dataChegadaContrato, dataFatoGerContrato,
dataPrimeiraParcelaContrato, dataEmissaoContrato, valorPlanilhaDebitoContrato
FROM
precadastro
INNER JOIN
contrato
ON precadastro.cpf_cnpj = contrato.FK_cpf_cnpj
LEFT JOIN faseprocessual
ON contrato.idContrato = faseprocessual.FK_idContrato
CROSS JOIN (SELECT #i:= 0) AS i
here's answer on SO which uses auto number in query.

C# SQL Is it possible to insert from a joined table into datagridview

I have four tables in my SQL database
In C# I have made a datagridview which shows the DeliveryDate, Quantity, Description and Price from the Order, Linkedtable and Stock table being joined in a select statement.
Here is the code used to join three tables into one datagridview
// this code for the load button of the datagridview
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("SELECT O.DeliveryDate, L.Quantity, S.Description, S.Price FROM [Order] O JOIN Linkedtable L ON O.OrderID = L.OrderID JOIN Stock S ON S.StockID = L.StockID ORDER BY O.DeliveryDate ", con);
DataTable DATA = new DataTable();
sda.Fill(DATA);
dataGridView1.DataSource = DATA;
con.Close();
This is how the datagridview looks
I would like to insert DeliveryDate, Quantity, Description and price from four textboxes into datagridview but i'm not sure how to do an INSERT statement with the tables joined like i have with the SELECT statement, is there a way to do this?
Since data will reside in different tables, there is no way to insert them at once and therefore, you can't execute it with one single command. However, you can create a store procedure to insert data into different tables separately, or you can insert them with two different INSERT commands in one batch.

c# all distincts value from datatable

I've found this piece of code that can be used to get all distinct values. But my datatable has 10 columns. The distinctValues only shows the columns I write in the toTable(); Is it possible to use this function, but also show the rest of the columns?
DataView view = new DataView(table);
DataTable distinctValues = view.ToTable(true, "Column1", "Column2");
Unless those columns you mention are the full key to the table, there is no guarantee that for a particular combination of those two columns the other columns will have exactly one value.
And if they were the key, then there would be no need to use a "distinct" filter.
You can use Linq-To-DataTable
var distinct = from row in table.AsEnumerable()
group row by new
{
Col1 = row.Field<string>("Column1"),
Col2 = row.Field<string>("Column2")
} into Group
select Group.First()
DataTable tblDistinct = distinctRows.CopyToDataTable();
(assuming that you just want an arbitrary row[the first])

How i can sort data in Datagridview by Column name

I have LINQ query:
var product_view = from productallinfo in QProductAllInfo select productallinfo;
Then i load data to table
MainCatalog_Table.DataSource = product_view.Distinct();
And next i want sort data by column name for example "ProductName"
Why don't you sort it before you bind it to the DataSource, something like this:
var product_view = from productallinfo in QProductAllInfo
orderby productallinfo.ProductName
select productallinfo;
And then you bind it to your data source....

Categories

Resources