When I click on the add record button I want one of my columns to have a default value in it. How do I do this in the code behind? It is a dynamic date and can change all the time?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
If the column is not a GridTemplateColumn
, you can specify a default value using the column's DefaultInsertValue
property, like this:
<telerik:GridBoundColumn DefaultInsertValue="12/21/2012" DataType="System.DateTime" DataField="Column1" UniqueName="Column1"></telerik:GridBoundColumn>
Otherwise, if it is a GridTemplateColumn
, take a look at the following Telerik article :
Inserting Values Using InPlace and EditForms Modes
Update:
You can also specify the default column values using the ItemCommand
method in your code-behind:
Protected Sub RadGrid1_ItemCommand(ByVal source As Object, ByVal e As Telerik.Web.UI.GridCommandEventArgs) Handles RadGrid1.ItemCommand
If (e.CommandName = RadGrid.InitInsertCommandName) Then
'cancel the default operation
e.Canceled = True
'Prepare an IDictionary with the predefined values
Dim newValues As System.Collections.Specialized.ListDictionary = New System.Collections.Specialized.ListDictionary()
newValues("Column1") = New DateTime(2013, 1, 22)
newValues("Column2") = "hello"
newValues("Column3") = Nothing
'Insert the item and rebind
e.Item.OwnerTableView.InsertItem(newValues)
End If
End Sub
回答2:
You can intercept the ItemDataBound event, and render content to control.
<telerik:RadGrid ID="RadGrid1" AutoGenerateColumns="false"
AllowSorting="True" runat="server" OnNeedDataSource="RadGrid1_NeedDataSource"
OnItemDataBound="RadGrid1_ItemDataBound">
<MasterTableView DataKeyNames="ID" CommandItemDisplay="Top">
<Columns>
<telerik:GridBoundColumn DataField="ID" HeaderText="ID"
UniqueName="ID" />
<telerik:GridBoundColumn DataField="Name" HeaderText="Name"
UniqueName="Name" />
</Columns>
<EditFormSettings ColumnNumber="1" EditFormType="Template">
<FormTemplate>
Name:<asp:TextBox runat="server" ID="NameTextBox"/>
</FormTemplate>
</EditFormSettings>
</MasterTableView>
</telerik:RadGrid>
public class Customer
{
public int ID { get; set; }
public string Name { get; set; }
}
protected void RadGrid1_NeedDataSource(object sender,
GridNeedDataSourceEventArgs e)
{
RadGrid1.DataSource = new List<Customer>
{
new Customer {ID = 1, Name = "John"},
new Customer {ID = 2, Name = "Marry"},
new Customer {ID = 3, Name = "Eric"}
};
}
protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
{
if (e.Item is GridEditFormItem && e.Item.IsInEditMode)
{
var item = e.Item as GridEditFormItem;
var nameTextBox = item.FindControl("NameTextBox") as TextBox;
// Insert mode
if (e.Item.OwnerTableView.IsItemInserted)
{
nameTextBox.Text = "Please enter name";
}
else // Edit mode
{
}
}