i'm new on .net, and i'm trying to make a gridview table that take data from a database (i bind data with <asp:sqldatasource selectcommand> tag) and for a specific integer value from this table column i want to display in gridview a string that is in another table and is specific for the integer.
So 2 tables, 1 is inserted in gridview, another has static number of columns, table "a" has integers and other columns, tabel "b" has same integers but different strings on other columns for them. In gridview i want to show other columns from table "a" and 1 column from table "b".
I can display the first table but i don't have ideas to link 2 tables.
I can't make changes in databes.
Thank you!
Table a Table b
column1 column2 column3 column4 column5
data1 data2 integer integer string
Output
Gridview
column1 column2 column5
To display the other data, then simply use a left join in your sql.
So, say we have this to load up the data grid:
if (IsPostBack == false)
{
GridView1.DataSource = Myrst("Select FirstName, LastName, Hotel_ID FROM tblBooked");
GridView1.DataBind();
}
We thus get this result:
But, that hotel_id is rather ugly, so we want to pull that data from tblHotels
So, you simply left join in the other table. You can write out the sql, or say lets create a view like this:
Now, our simple code can say go like this:
GridView1.DataSource = Myrst("SELECT * from vBookedHotels");
GridView1.DataBind();
And we get this result:
So the "general" approach here is to write some sql and use a left join. You can thus quite much pull in any "id" value and translate it to the other table. So friendly text names or descriptions can thus be pulled from the other table.
I recommend using SQL for this, since then your two lines of code to load up the gridview can be done as per above. And it often possible that you need to do this in several places in your application - so a handy view to query against makes is rather easy.
in above, I use a custom routine called MyRst(), and all it does is create the sqlcommand object, get the connection and returns a data table (i was tired of writing the same code over and over (eg: create connection, create data adaptor etc - so I just put that code in a simple routine, and now I can just type in some sql and quite much assign it to a gridview, or even a listview, or even dropdown boxes with the two lines of code as per above.
So, the general approach here is to use SQL to get/grab/pull and translate some "ID" in a column to some nice user friendly description or text columns in the 2nd table as you outlined.
Related
I have two database table to store the current data and another to store historical data, whenever a user makes any changes then the current table is updated and that data in the current data is saved to historical table. However, I would like to use a SQL query to display on the gridview both the current and historical data. I've outlined a picture of the results I would like to achieve.
You seem to be looking for union all:
select ct.* from current_table
union all
select ht.* from history_table
For this to work properly, both tables must have the same number of columns, with the same datatype (and length) - the description of your question makes me think that this really is the case here.
Use as command for your sql query as below
select column1, column2 from table1
union
select column4 as column1, column2 from table2.
This will rename you non matching column to matching column.
Some reading link
here is the scenario: I have a .CSV bind in a dataTable, I want to move the entire columns in the DT to match the order of my data base's columns.
Once the order is executed, I'll have a Query to insert in the DB.
I thought of looping through my DT and select all row with the same index as the column like so :
Is there a better/quicker way to do it?
PS: I'll use CSV with ~100-5000 rows.
EDIT:
My database columns are like so :
first name, last name, age, Country
and my CSV is ordered like this
age, last name, country, first name
I want the CSV's columns to match the order of the DB's
It sounds like you are trying to insert using INSERT INTO [table] VALUES (...). For queries, the column order should not matter. Plus, this can be dangerous. What if in the future the database columns are changed? What if the table is dropped and then created with a different column order? Sure, most of us build Apps assuming the back-end structure is static, but things happen, and it does not take much effort to declare the columns like INSERT INTO [table] ([first name], [last name], [age], [Country]) VALUES (...). Plus this way has the benefit of being easier to read.
If you want to reorder the columns in the view layer, reorder them in the view layer, but I suggest keeping your DataTable in the order that it was read.
At first use bulk copy https://johnnycode.com/2013/08/19/using-c-sharp-sqlbulkcopy-to-import-csv-data-sql-server/ to copy your full table in the database then do whatever you want in the database which is so much faster.
In Visual Studio Designer, I have created a DataSet that has 2 DataTables; EmployeeDT and PayrollSheetDT which pull data from SQL Server via SELECT statements. The two DataTables have a relation via the SSN column.
Relevant SQL Server database structure:
Table: Employee, columns: SSN (primary key), Driver
Table: PayrollSheet, columns: SSN (foreign key), PSDate
In my PayrollSheet form, I have multiple combo boxes where I have bound DataSource, DisplayMember and ValueMember of the EmployeeDT DataTable. When I start the program, I am successful in clicking the down arrow in the "Driver" combobox, choosing a drivers name, and having the other comboboxes display information from that Driver / SQL record - as they are bound to the same DataSource.
I also have a listbox next to the comboboxes, with the goal of displaying the PSDate for whatever SSN is selected in the comboboxes.
The listbox is my issue. I need to be able to change the value in any combobox, and have the PSDate displayed in the listbox. I don't know if this can be done, as the PayrollSheetDT DataTable executes a static SQL query, but what I'm wanting would be the equivalent of adding a WHERE SSN = <selected ssn in other datatable>
I don't have a good understanding of how to do this, but if I try to fill the TableAdapter, I get the following error:
One or more rows contain values violating non-null, unique, or foreign-key constraints.
Thanks for your help
These things are VERY finickly.
That error could mean a few things. Try to (temporarily) delete the PayrollSheet table and only populate the Employee table.
Make sure your column names match the sql query, like the short words/phrases for the column names are exact matches. EmployeeLastName is not the same as EmployeeLName.
Make sure there is not an "extra" PayrollSheet row that doesn't have a parent row (back to Employee), aka, an orphan row in PayrollSheet.
Here is a generic helper. Try to populate a DataSet object (just "DataSet", not a strongly typed one)...and then do a ds.WriteXml(#"C:\myds.xml") and then go through that xml and make sure the column names match.
Also..check datatypes. Check that a column (in the ds definition) isn't marked as "not null" and then the query returns a null value for some row. It's some kind of tick tack issue, I'm pretty sure.
99x out of 100x, when I had this issue, it was something tiny tiny that screwed me.
Using: ado.net
How can I select data from a DataTable using SQL with an aggregation function?
I know that I can use select property (http://msdn.microsoft.com/en-us/library/t5ce3dyt(vs.71).aspx ) but I need an aggregation function to use it with, and I didn't find any examples for this.
Aggregates in DataSet are normally used in conjunction with relations:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemdatadatacolumnclassexpressiontopic.asp
Basically if you need your result as single row with single column, you'd need to create that extra table with that column and add expression to it so you would get a single row:
Table1, column Number: 3 rows containing 1,2,3
Table2, column Average, expression set to "Avg(Table1.Number)": One rows containing 2
As to your particular example: "SELECT COUNT(*) FROM ", you could use row count: table.Rows.Count
You can also create DataView with particular filter and get number of rows in it to emulate more complex cases of COUNT.
Scenario Having a table with one of the column varchar(20). Column mostly contains integer values but we haven't restricted the user. 90% of users enter 50, but there are 5% users who enter 50 Units.
Defined an in code query as follows
qry = select coalesc(CONVERT(Varchar(20),column1),'') from table1
Have got c# code to populate dataset as follows
DataSet ds = loader.LoadDataSet(qry);
Now what happens is that the .net runtime gets the first row and because it's an integer (in most of the case), it assigns the column an int data type and in scenarios like '50 Units', it returns blank as column1 is int (in.net runtime view) and fails at CONVERT(varchar(20), column1) and returns empty ('') column.
One alternative is to user strongly typed dataset and get it done but I would love to know of any other alternative to get it done before going on that path.
My bad. Actually, it was the sql query which was failing in .net code. When a column is varchar, doing something like COALESC(CONVERT(VARCHAR(20),column1),0) fails. It should be COALESC(CONVERT(VARCHAR(20),column1),'0')