The Self-Taught Programmer

Recipes from real-world experience with asp.net.

How To Make a Column in an ASPxGridView ReadOnly for Editing but Enabled when Inserting a New Record

leave a comment »

The Situation:

You have a DevExpress ASPxGridView on your page with a column designated as “ReadOnly=true”. This works great when you are editing an existing record — it won’t allow you to change that field, but when you try to insert a NEW record, you can’t enter anything in the field.

Note: I don’t know if this happens under all circumstances, but for me, it happened for an ASPxGridView that is databound via code rather than from a datasource object on an aspx page.

A Solution:

The simple solution for this problem is to handle the “oncelleditorinitialize” event of the ASPxGridView.

Here is (simplified) ASPxGridView in my aspx page:

<dx:ASPxGridView ID="ASPxGridView1" runat="server" AutoGenerateColumns="False"
	KeyFieldName="SettingName" onrowdeleting="ASPxGridView1_RowDeleting"
	onrowinserting="ASPxGridView1_RowInserting"
	onrowupdating="ASPxGridView1_RowUpdating" Theme="DevEx"
	oncelleditorinitialize="ASPxGridView1_CellEditorInitialize">
	<Columns>
		<dx:GridViewCommandColumn VisibleIndex="0">
			<EditButton Visible="True" />
			<NewButton Visible="True" />
			<DeleteButton Visible="True" />
		</dx:GridViewCommandColumn>
		<dx:GridViewDataTextColumn FieldName="SettingName" ReadOnly="true"
			VisibleIndex="1">
		</dx:GridViewDataTextColumn>
		<dx:GridViewDataTextColumn FieldName="SettingValue" VisibleIndex="2">
		</dx:GridViewDataTextColumn>
	</Columns>
</dx:ASPxGridView>

And here is the code called for the oncelleditorinitialize event:

protected void ASPxGridView1_CellEditorInitialize(object sender, ASPxGridViewEditorEventArgs e)
{
	if (ASPxGridView1.IsNewRowEditing)
	{
		if ((e.Column.FieldName) == "SettingName")
		{
			e.Editor.ReadOnly = false;
		}
	}
}
Advertisements

Written by Jim McMullen

February 12, 2013 at 11:16 am

Posted in How-To

Tagged with ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: