I have a DataGrid
which is bound to a DataTable
that is filled by an SqlDataAdapter
, which fills it with an unspecified table, and I therefore have no way of knowing how the structure in the table is. I've set the TargetNullValue
to "NULL"
, and the cells that contains a null-value from the database shows NULL in the DataGrid, which is perfect.
However... when I want to add a new row using DataGrid
's CanUserAddRow
, the default values are all "NULL", and I want them to be empty.
I am able to change cells that expect the type of string
to show up empty, but in the cells that expect int
's for example, it can't contain an empty string, or an int
that is NULL
. If I want it to be NULL
, it has to be DBNull
instead, which gives me "NULL" in the cell, which doesn't make any difference.
Any one with an idea how to overcome this issue of mine?
Thanks in advance.
Mainwindow.xaml
<DataGrid x:Name="dataGrid_Table" AutoGenerateColumns="True" CanUserAddRows="true" AutoGeneratingColumn="dataGrid_Table_AutoGeneratingColumn" InitializingNewItem="dataGrid_Table_InitializingNewItem"/>
Mainwindow.xaml.cs
private void dataGrid_Table_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
// Make all columns nullable
((DataGridBoundColumn)e.Column).Binding.TargetNullValue = "NULL";
}
private void dataGrid_Table_InitializingNewItem(object sender, InitializingNewItemEventArgs e)
{
DataRowView drv = (DataRowView)e.NewItem;
for (int i = 0; i < drv.Row.ItemArray.Count(); i++)
{
DataColumn col = drv.Row.Table.Columns[i];
if (col.DataType.ToString() == "System.String")
{
drv.Row[i] = "";
}
else if (col.DataType.ToString() == "System.Int32")
{
// Set cells that expect an int to show up empty
}
}
}
Method for filling the DataTable and binding it to the DataGrid
internal void FillDataGrid(User user, MainWindow mainWindow)
{
dt = new DataTable();
using (SqlConnection con = new SqlConnection(ConnectionString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("SELECT * FROM " + Name, con))
{
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
mainWindow.dataGrid_Table.ItemsSource = dt.DefaultView;
}
}
}