I want to save null values to a decimal column(allows nulls on db) on a wpf datagrid (with autogenerate columns).
It doesn't allow me to save nulls and shows red error box.
I suspect you are running into a problem that I had but it was a simple text box (not a datagrid). You think you are passing a null but you are really passing string.empty which is neither null nor a decimal. I fixed it with a converter to convert string.empty to null. H.B. (the same H.B.) that edited your question answered mine.
Cannot Assign a Null Value to a Nullable Int32? via Binding
to which kind of database are you binding your datagrid to ? for instance if you bind it to a datatable with ado.net, the datatable is not aware of the underlying sql schema unless you update it yourself. --> see http://support.microsoft.com/kb/310128
with linq2sql it should work fine without this update, with others like MySql i don't know.
Just add this code in AutogeneratingColumn event:
if (e.Column.ToString() ==
"System.Windows.Controls.DataGridTextColumn")
{
(((System.Windows.Controls.DataGridBoundColumn)(e.Column)).Binding).TargetNullValue
= string.Empty;
}
Related
my problem is this:
I have a table in SQL Server that have a NOT NULL Column that uses a SEQUENCE as default (NEXT VALUE FOR SeqDefa),
that column is not the PK from the table.
I building a web form in ASP.NET that does a CRUD in that table, when i want to send a null value in that column to use the default in that table i get an error. that's because LINQ says that you can't send a null value to a not null column
how can i fix it?
can i get the sequence´s next value from LINQ in my form?
there's another option than changing table column from not null to allowing nulls?
If you are using Entity Framework, then you might be looking for the [DatabaseGenerated] attribute or .ValueGeneratedOnAdd() in the fluent API.
Microsoft Documentation
If You are using EF core, You could also look at Value converters.
Write a simple one that will set chosen default value when given value is null, or some calculated value if You prefer.
Thanks to this You there will be no more need to have some special behaviour in your linq code - just normally use null when needed and value converter will take care of the rest.
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 am using Ultragrid in c# .net windows application,
I used a column of datatype System.DateTime., On page loading it is showing empty (like '--/--/--'),
aftrer some validations i want to make that column empty
when am trying to make that column empty, it is taking current date as default or '01/01/0001'.
i made defaultvalue to null.
How to make empty that column means it should show like '--/--/--'
This is probably an issue with your DataSource, not the grid.
The DateTime data type in DotNet is a struct, so it can't be null. If you use a DataSet/DataTable or UltraDataSource as the data source for your grid, then these objects store everything as an object so that they can handle null or DBNull. My guess is that you are probably binding the grid to a list of your own custom classes and the DataType of the field is DateTime and cannot accept nulls.
If you are using CLR2, maybe you can use a nullable DateTime, instead. You might have to set the Nullable property on the column to Nothing, though, since even a nullable type can't handle DBNull.
Dear Colleagues
I have a problem with sorting in DataGridView module.
When i click on column which needs to be sort then system throws NullReferenceException. I understand that column has some null values and this couses error message.
Have You got any idea how to change sort module to thread null values as string without any characters?
Your prompt will be appreciated.
Why not use an empty string instead of null strings?
I know this is a bit complicated for your need but you could try a workaround similar to this after programmatically selecting those rows that have nulls in them.
Sorting selected rows in DataGridView
Dear Geaorge and Mamta
Thank You both once again for help. I have found solution which ease resolved problem.
As I wrote, all data is transfered from database to visual studio, so I changed query from:
"SELECT number_of_invoice FROM invoices"
to:
"SELECT CASE WHEN (number_of_invoice is null) then '' else number_of_invoice END FROM invoices"
This automaticly change null values to '', and problem is dismissed.
Have a good day!
I have designed a dataset using VS2008 dataset designer. In one of the datatables, I have set "AllowDBNull" property of most of the columns to be False. However, still if I create a DataRow containing null values for these columns, this datatable accepts this row, without any error.
Am I not understanding something here? Please advice. Thank you.
Edit Mike Spross' excellent explanation however, brings forth another question. How do we check text fields if they are System.DBNull? It is surprising that DataSets are not considering a string "" as System.DBNull and throwing an exception. Or is it not?
Edit I think I have found the problem and reason. I am initializing a new row of the DataTable, before filling in the values to that row. While initializing the row, default value for string, ie, "" might be being filled in that column. I think that's it? Any ideas about this?
The short answer is:
System.DBNull.Value != null
The longer answer is:
In C#, the concept of a NULL value in SQL is represented by the Value property of the System.DBNull class. When dealing with a database, the more familiar C# null doesn't actually mean "null value."
When you set a database column to null, ADO.NET will initialize the column to whatever the default value is for that column (for example, an int column would be initialized to 0). That is, using null can actually cause a non-null value to end up in the database, and therefore you won't get an error.
If you instead set a database column to System.DBNull.Value, the column will actually be set to NULL. This is the situation that AllowDBNulls == false will prevent you from doing.
Regarding your "bonus" ;-) question: NULL (no string) and "" (empty string) are two different things. So it's perfectly reasonable to treat them differently. It's the distinction between null and DBNull that is messing things up. If nullable types had been available at the time of designing ADO.NET, things probably would be a lot easier. But before .NET 2.0, there was no way to represent e.g. a "null integer".
Are you exactly assigning NULL values or an empty string to those columns? If you don't assign any value to a column, it will default to NULL (if a DEFAULT constraint is not imposed). Else you can assign a NULL value by doing -
ds.Tables[0].Rows[0]["Col"] = null;
If you are assigning an Empty string to those columns, it's not equal to NULL.
And if you have a NULL value in a column which has been marked as NOT NULLABLE, it will throw an error -
Column 'Col1' does not allow nulls.
EDIT:
By NOT NULLABLE, I mean AllowDBNull = false.
Your code seems correct. Can you try trimming the text?
Here's the whole code -
DataTable dt = new DataTable();
DataColumn column = new DataColumn("Col1");
column.AllowDBNull = false;
dt.Columns.Add(column);
DataRow dr = dt.NewRow();
dr["Col1"] = null;
dt.Rows.Add(dr);