问题
I'm using a FormView with an ObjectDataSource and binding using <%# Bind("WhateverProp") %> - and all of my nullable columns are coming back with default values of the type in them.
It appears that the FormView object doesn't have a ConvertEmtpyStringToNull property like the other binding containers do. I've found articles suggesting that this was a bug in VS 2005 / .Net 2.0 - but don't see any saying what the resolution was.
Does anyone have any suggestions as to how I can work around this without just re-capturing all of the fields in the ODS_Inserting event? I'd rather not have to write code to re-bind all of my bound fields on the form just to test for nulls.
回答1:
Struggled with it too. For a dropdownlist, I do that:
AppendDataBoundItems="true"
<asp:ListItem Text="" Value=""></asp:ListItem>
For my ObjectDataSource, even thoug my UpdateMethod takes a single parameter, the entity, I add Update params for each Nullable Field of the Entity with convert to NULL
<UpdateParameters>
<asp:Parameter Name="No_Empl_Ferme" Type="Int32" ConvertEmptyStringToNull="true" />
</UpdateParameters>
I do the same for the Insert.
Works fine.
回答2:
I ended up doing this - kind of a shotgun approach, but in this case all of my empty string values should be nulls. I've also considered using a string array in the code to specify which values should be nulled - and then could just loop thru the string array instead of over all of the values.
protected void RequestItemFormView_ItemInserting(object sender, FormViewInsertEventArgs e)
{
for (int i = 0; i < e.Values.Count - 1; i++)
{
if (e.Values[i].ToString() == string.Empty)
{
e.Values[i] = null;
}
}
}
回答3:
In your Object DataSource, you need to add InsertParameters for each of your nullable type with the Attribute ConvertEmtpyStringToNull="True" :
<InsertParameters>
<asp:Parameter Name="NullableFieldName" Type="Int32" ConvertEmptyStringToNull="true" />
</InsertParameters>
回答4:
Quote: Tonio - i'm not using individual params, but DataObjectTypeName instead. My insert method takes a single param, and that's the business object that I want to have saved back to the database. – Scott Ivey May 1 at 12:57
I've fixed it like this:
protected void FormViewSettings_ItemUpdating(object sender, FormViewUpdateEventArgs e)
{
OrderedDictionary values = e.NewValues as OrderedDictionary;
var personID = values["PersonID"];
if (string.IsNullOrEmpty(personID.ToString()))
{
values.Remove("PersonID");
values.Add("PersonID", null);
}
}
It's a little hack but it works fine. This way you can set the object property to null instead of string.empty without using the ConvertEmptyStringToNull setting.
来源:https://stackoverflow.com/questions/753455/formview-convertemptystringtonull-and-binding