I have 2 script components which extract data from result set objects say User::AllXData and User::AllYData.
It is run through a foreach loop and the data is stored in a data table.
Next, I'm adding the data into a excel sheet using Excel destination. Now when I do that. All the data corresponding to column A (i.e, the data from User::AllXData) is being added to the excel sheet, but the column B gets filled with null values till the end of column A's data.
Then column B gets filled leaving column A with null data. It's supposed to be aligned.
Is there a workaround for this?
Edit:
After a long of grinding and running many tests, finally came across a solution.
The answer to this is pretty simple. Instead of using two objects as result set, it's better to use only one.
If you're going to query from a single source, include all the required columns in your SQL query into one object result set and use that as a read only variable in the script component.
Create a single data table that includes all the required columns and adds them into your excel destination row by row without any null values.
Here's an article that has a good example.
I have an ADO.NET DataSet that is persisted as XML. I need to add to it a list of cities and allow the user to select which city they're in. The selection has to be stored in the XML file along with the rest of the data.
This seems like a perfect use for DataSet.ExtendedProperties. However, it turns out that, in order for the extended properties to get written to the XML, I need to use XmlWriteMode.WriteSchema and XmlReadMode.ReadSchema, which adds the entire schema of the DataSet to the XML file just so it can add a single attribute, msprop:CityID.
My DataSet is strongly typed and its schema is hard-coded by the designer, so I really don't need to store the schema in the XML, which can lead to run-time errors.
So my question is, what's the best way to add the selected city to the DataSet itself. For example, using another table called SelectedCity, or using a Boolean column in the City table called IsSelected.
The SelectedCity table will always need to contain exactly one row, and the IsSelected column will need to contain true in exactly one row and false in all the others, and I don't know how to enforce such constraints in ADO.NET.
This seems like a fairly common scenario. What's the recommended way to code it?
If the relation is 1 to 1 put the field in the parent, but if a user can have various 1 to N put in another table. Sorry for my english.
I have a database table like this on SQL Server:
USER PASSWORD
1 samplepassword
2 NULL
3 NULL
4 sample_password
I want to replace the NULL values in the PASSWORD column, along with other columns, with values like '(Not set)' or '-' upon displaying it to the user in a DataGridView.
There are three ways I know of in achieving this. First is to use the NullValue property of the column's DefaultCellStyle. The concern with this method is that the designer would create multiple copies of the same DefaultCellStyle - one per column.
Then there's the CellFormatting event of the DataGridView. Lastly, the replacing can be done on the SQL statement itself, ala ISNULL(password, '(Not set)').
Considering that this DataGridView can be filtered afterwards by the user (e.g. show only those without a password), what is the more suggested way in doing this?
Thanks!
Formatting is not SQL server responsibility, keep formatting in your UI code.
Use DefaultCellStyle and create instance of DefaultCellStyle in the code and set same instance to the all columns of datagridview manually.
Or assign only NullValue property to already existed styles
const string NULL_VALUE = "not set";
DataGridView.Columns["ColumnName1"].DefaultCellStyle.NullValue = NULL_VALUE;
DataGridView.Columns["ColumnName2"].DefaultCellStyle.NullValue = NULL_VALUE;
Not 100% sure on SQL Server but on MySQL I wold do the following
SELECT USER, IF(PASSWORD IS NULL,'Not Set', PASSWORD) AS PASSWORD FROM TABLE
SELECT ISNULL(YourColumn, 'yourcharacter' ) FROM YourTableName
Run a JavaScript or jQuery function after your DataGridView load, to find empty values from DataGridView and replace it with "(Not set)" or "-".
OR
Update your dataset values which are empty with values "-".
The selected answer is the best one from a paradigm standpoint, though you can also handle this by creating a helper function to handle nulls. This will make your default values something you can change based on your datatype. It also lets you manage nulls before they ever touch the UI, but without affecting your queries, which is essential if you have to handle mathematics before displaying output.
public static dynamic NullCheck(object d, dynamic default)
{
return DbNull.Value == d ? default : d;
}
Just be ready to cast the result as needed in your code, such as ((foo)(Nullcheck(foo, bar))).
I'm trying to populate a DataTable, to build a LocalReport, using the following:
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = new MySqlConnection(Properties.Settings.Default.dbConnectionString);
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT ... LEFT JOIN ... WHERE ..."; /* query snipped */
// prepare data
dataTable.Clear();
cn.Open();
// fill datatable
dt.Load(cmd.ExecuteReader());
// fill report
rds = new ReportDataSource("InvoicesDataSet_InvoiceTable",dt);
reportViewerLocal.LocalReport.DataSources.Clear();
reportViewerLocal.LocalReport.DataSources.Add(rds);
At one point I noticed that the report was incomplete and it was missing one record. I've changed a few conditions so that the query would return exactly two rows and... surprise: The report shows only one row instead of two. I've tried to debug it to find where the problem is and I got stuck at
dt.Load(cmd.ExecuteReader());
When I've noticed that the DataReader contains two records but the DataTable contains only one. By accident, I've added an ORDER BY clause to the query and noticed that this time the report showed correctly.
Apparently, the DataReader contains two rows but the DataTable only reads both of them if the SQL query string contains an ORDER BY (otherwise it only reads the last one). Can anyone explain why this is happening and how it can be fixed?
Edit:
When I first posted the question, I said it was skipping the first row; later I realized that it actually only read the last row and I've edited the text accordingly (at that time all the records were grouped in two rows and it appeared to skip the first when it actually only showed the last). This may be caused by the fact that it didn't have a unique identifier by which to distinguish between the rows returned by MySQL so adding the ORDER BY statement caused it to create a unique identifier for each row.
This is just a theory and I have nothing to support it, but all my tests seem to lead to the same result.
After fiddling around quite a bit I found that the DataTable.Load method expects a primary key column in the underlying data. If you read the documentation carefully, this becomes obvious, although it is not stated very explicitly.
If you have a column named "id" it seems to use that (which fixed it for me). Otherwise, it just seems to use the first column, whether it is unique or not, and overwrites rows with the same value in that column as they are being read. If you don't have a column named "id" and your first column isn't unique, I'd suggest trying to explicitly set the primary key column(s) of the datatable before loading the datareader.
Just in case anyone is having a similar problem as canceriens, I was using If DataReader.Read ... instead of If DataReader.HasRows to check existence before calling dt.load(DataReader) Doh!
I had same issue. I took hint from your blog and put up the ORDER BY clause in the query so that they could form together the unique key for all the records returned by query. It solved the problem. Kinda weird.
Don't use
dr.Read()
Because It moves the pointer to the next row.
Remove this line hope it will work.
Had the same issue. It is because the primary key on all the rows is the same. It's probably what's being used to key the results, and therefore it's just overwriting the same row over and over again.
Datatables.Load points to the fill method to understand how it works. This page states that it is primary key aware. Since primary keys can only occur once and are used as the keys for the row ...
"The Fill operation then adds the rows to destination DataTable objects in the DataSet, creating the DataTable objects if they do not already exist. When creating DataTable objects, the Fill operation normally creates only column name metadata. However, if the MissingSchemaAction property is set to AddWithKey, appropriate primary keys and constraints are also created." (http://msdn.microsoft.com/en-us/library/zxkb3c3d.aspx)
Came across this problem today.
Nothing in this thread fixed it unfortunately, but then I wrapped my SQL query in another SELECT statement and it work!
Eg:
SELECT * FROM (
SELECT ..... < YOUR NORMAL SQL STATEMENT HERE />
) allrecords
Strange....
Can you grab the actual query that is running from SQL profiler and try running it? It may not be what you expected.
Do you get the same result when using a SqlDataAdapter.Fill(dataTable)?
Have you tried different command behaviors on the reader? MSDN Docs
I know this is an old question, but for me the think that worked whilst querying an access database and noticing it was missing 1 row from query, was to change the following:-
if(dataset.read()) - Misses a row.
if(dataset.hasrows) - Missing row appears.
For anyone else that comes across this thread as I have, the answer regarding the DataTable being populated by a unique ID from MySql is correct.
However, if a table contains multiple unique IDs but only a single ID is returned from a MySql command (instead of receiving all Columns by using '*') then that DataTable will only organize by the single ID that was given and act as if a 'GROUP BY' was used in your query.
So in short, the DataReader will pull all records while the DataTable.Load() will only see the unique ID retrieved and use that to populate the DataTable thus skipping rows of information
Not sure why you're missing the row in the datatable, is it possible you need to close the reader? In any case, here is how I normally load reports and it works every time...
Dim deals As New DealsProvider()
Dim adapter As New ReportingDataTableAdapters.ReportDealsAdapter
Dim report As ReportingData.ReportDealsDataTable = deals.GetActiveDealsReport()
rptReports.LocalReport.DataSources.Add(New ReportDataSource("ActiveDeals_Data", report))
Curious to see if it still happens.
In my case neither ORDER BY, nor dt.AcceptChanges() is working. I dont know why is that problem for. I am having 50 records in database but it only shows 49 in the datatable. skipping first row, and if there is only one record in datareader it shows nothing at all.
what a bizzareeee.....
Have you tried calling dt.AcceptChanges() after the dt.Load(cmd.ExecuteReader()) call to see if that helps?
I know this is an old question, but I was experiencing the same problem and none of the workarounds mentioned here did help.
In my case, using an alias on the colum that is used as the PrimaryKey solved the issue.
So, instead of
SELECT a
, b
FROM table
I used
SELECT a as gurgleurp
, b
FROM table
and it worked.
I had the same problem.. do not used dataReader.Read() at all.. it will takes the pointer to the next row. Instead use directly datatable.load(dataReader).
Encountered the same problem, I have also tried selecting unique first column but the datatable still missing a row.
But selecting the first column(which is also unique) in group by solved the problem.
i.e
select uniqueData,.....
from mytable
group by uniqueData;
This solves the problem.
I have a grid bound from a mysql db table via c#. Is there any way to get the displayed items in an insert statement?
For ex: If i bind a grid with 20 rows, i need to get all of them in a insert statements, which i can save as a .sql file and run it in another db.
Your thoughs will be highly helpful.
You COULD do it by looping through the grid rows and getting the values of each cell but that would be the hard way to do it. You'd be better off just having the DB do the work by having the DB perform the insert statement using a select statement directly as outlined here:
http://www.sqlteam.com/article/using-select-to-insert-records
This is the normal way to take the results of a select statement and insert into a different table.
Edit My co-worker, who is much smarter than me, figured out how to get the underlying DataTable from the Viewstate and use it as follows (in VB - you will need to translate it to C#):
Dim tblRanked AS System.Data.DataTable = ViewState("tblRanked")
For Each row As DataRow In tblRanked.Rows
db.ExecuteNonQuery("usp_AddRankingForUser", loginId, row("RequestID"), count)
'updates the depthead field for later use
Next
Edit - added
Here's another option that's similar to what it looks like you're asking, and the code snippet definitely shows how to loop through the rows in a datagrid to get values...
http://www.eggheadcafe.com/articles/20060513.asp