Thursday, March 22, 2012

default data value in gridview?

Hi,

I am trying to set a default value for a date field in my update parameters:

When I try an update with the DefaultValue="<% Now %>", I get this error:
"String was not recognized as a valid DateTime."

The updates work fine if no default value is set and it also works ok if I change the default value to a set string, such as "6/24/06". I've tried using different data sources and datasets, but no luck.

Anyone have any ideas on this?

Thanks!

<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:db1ConnectionString%>" ProviderName="<%$ ConnectionStrings:db1ConnectionString.ProviderName%>" SelectCommand="SELECT [ID], [Name], [Date] FROM [Table1]" DeleteCommand="DELETE FROM [Table1] WHERE [ID] = ?" InsertCommand="INSERT INTO [Table1] ([ID], [Name], [Date]) VALUES (?, ?, ?)" UpdateCommand="UPDATE [Table1] SET [Name] = ?, [Date] = ? WHERE [ID] = ?"> <DeleteParameters> <asp:Parameter Name="ID" Type="Int32" /> </DeleteParameters> <UpdateParameters> <asp:Parameter Name="Name" Type="String" /> <asp:Parameter Name="Date" Type="DateTime" DefaultValue="<%Now()%>" /> <asp:Parameter Name="ID" Type="Int32" /> </UpdateParameters> <InsertParameters> <asp:Parameter Name="ID" Type="Int32" /> <asp:Parameter Name="Name" Type="String" /> <asp:Parameter Name="Date" Type="DateTime" /> </InsertParameters> </asp:SqlDataSource> <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ID" DataSourceID="SqlDataSource1"> <Columns> <asp:CommandField ShowDeleteButton="True" ShowEditButton="True" /> <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" /> <asp:BoundField DataField="Date" HeaderText="Date" ReadOnly="true" SortExpression="Date" /> </Columns> </asp:GridView>

I'm not sure you're using the right way to call the function in page script, but it works if I set the default value in the code behind:

SqlDatasSource1.SelectParameters.Add("@.OD", TypeCode.DateTime, DateTime.Now.ToString());

|||Great, thanks! I don't know why I didn't think to do it that way.

Just in case anyone else runs this, I ended up using an ObjectDataSource and added this event handler to set the parameters...it works great:

Protected Sub ObjectDataSource1_Inserting(ByVal senderAs Object,ByVal eAs System.Web.UI.WebControls.ObjectDataSourceMethodEventArgs)Handles ObjectDataSource1.Inserting e.InputParameters("Date") = DateTime.NowEnd Sub Protected Sub ObjectDataSource1_Updating(ByVal senderAs Object,ByVal eAs System.Web.UI.WebControls.ObjectDataSourceMethodEventArgs)Handles ObjectDataSource1.Updating e.InputParameters("Date") = DateTime.NowEnd Sub
|||I'm glad to hear that you managed to make it worksSmile BTW someone told me the reason why your code in page script (set DefaultValue for a parameter a value returned by a function) didn't work is that the Parameter elements can not be boundsql

No comments:

Post a Comment