Showing posts with label ASPxGridView. Show all posts
Showing posts with label ASPxGridView. Show all posts

Thursday, November 17, 2011

Validate Edit Form Template Container

Use Validation Group for custom added controls.. and validate using javascript.

 

<script type="text/javascript">
function OnUpdateClick(editor) {
if(ASPxClientEdit.ValidateGroup("EditForm"))
treeList.UpdateEdit();
}
</script>
<dxwtl:ASPxTreeList ID="ASPxTreeList2" runat="server" AutoGenerateColumns="False"
DataSourceID="AccessDataSource1" KeyFieldName="ID"
ParentFieldName="ParentID" ClientInstanceName="treeList">
<Templates>
<EditForm>
<table style="width: 100%">
<tr>
<td>Department:</td>
<td><dxe:ASPxTextBox ID="ASPxTextBox1" runat="server"
Value='<%# Bind("Department") %>'
Width="170px">
<ValidationSettings ValidationGroup="EditForm">
</ValidationSettings>
</dxe:ASPxTextBox></td>
</tr>
<tr>
<td>Location:</td>
<td><dxe:ASPxTextBox ID="ASPxTextBox2" runat="server"
Value='<%# Bind("Location") %>'
Width="170px">
<ValidationSettings ValidationGroup="EditForm">
</ValidationSettings>
</dxe:ASPxTextBox></td>
</tr>
<tr>
<td>Budget:</td>
<td><dxe:ASPxSpinEdit ID="ASPxSpinEdit1" runat="server" Height="21px" Number="0"
Value='<%# Bind("Budget") %>'>
<ValidationSettings ValidationGroup="EditForm">
</ValidationSettings>
</dxe:ASPxSpinEdit></td>
</tr>
<tr>
<td>Phone:</td>
<td><dxe:ASPxTextBox ID="ASPxTextBox3" runat="server"
Value='<%# Bind("Phone") %>' Width="170px">
<ValidationSettings ValidationGroup="EditForm">
<RegularExpression ErrorText="Wrong phone number"
ValidationExpression="((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}" />
</ValidationSettings>
</dxe:ASPxTextBox></td>
</tr>
<tr>
<td colspan="2">
<a href="javascript:void(0);" onclick="OnUpdateClick(this)">Update</a>
<dxwtl:ASPxTreeListEditFormTemplateReplacement runat="server"
Type="CancelButton"/>
</td>
</tr>
</table>
</EditForm>
</Templates>
<Columns>
<dxwtl:TreeListTextColumn FieldName="Department" VisibleIndex="0">
</dxwtl:TreeListTextColumn>
<dxwtl:TreeListTextColumn FieldName="Budget" VisibleIndex="1">
</dxwtl:TreeListTextColumn>
<dxwtl:TreeListTextColumn FieldName="Location" VisibleIndex="2">
</dxwtl:TreeListTextColumn>
<dxwtl:TreeListTextColumn FieldName="Phone" VisibleIndex="3">
</dxwtl:TreeListTextColumn>
<dxwtl:TreeListCommandColumn VisibleIndex="4">
<EditButton Visible="True">
</EditButton>
</dxwtl:TreeListCommandColumn>
</Columns>
<SettingsEditing Mode="EditForm" />
</dxwtl:ASPxTreeList>


To invoke client-side validation for custom editors placed within the Edit Form's template, make use of a template container's ValidationGroup property.You can assign this property value to the ValidationSettings.ValidationGroup property of custom editors to be validated. The code below demonstrates how this can be done when defining an Edit Form's template.




<dx:ASPxGridView ... >
...
<Templates>
<EditForm>
...
<dx:ASPxTextBox ID="ASPxTextBox2" runat="server" Width="170px" ValidationSettings-ValidationGroup="<%# Container.ValidationGroup %>">
<ValidationSettings>
<RequiredField IsRequired="true" />
</ValidationSettings>
</dx:ASPxTextBox>

<dx:ASPxGridViewTemplateReplacement ReplacementType="EditFormUpdateButton" runat="server" />
...
</EditForm>
</Templates>
...
</dx:ASPxGridView>


in Dynamic Templates that inherits ITemplate interface..  use the following way to specify these.



ASPxTextBox tb = new ASPxTextBox();
tb.ID = "txtName";
tb.Width = 200;
tb.ValidationSettings.CausesValidation = true;
tb.ValidationSettings.RequiredField.IsRequired = true;
tb.ValidationSettings.ErrorDisplayMode = ErrorDisplayMode.ImageWithTooltip;
tb.ValidationSettings.ValidationGroup = editContainer.ValidationGroup;
//tb.CssFilePath = @"~/App_Themes/Soft Orange/{0}/styles.css";
//tb.CssPostfix = "Soft_Orange";
tb.Value = DataBinder.Eval(editContainer.DataItem, "Name");
table.Rows[0].Cells[1].Controls.Add(tb);

Wednesday, November 9, 2011

Find controls in the DataItem template of ASPxGridView column

Add DataItemTemplate to Grid Column to access at server side code. In case of DataRowTemplate, we create template for whole row, but if we want to create template for a single column then we use DataItemTemplate and on the place of DataRowTemplate’s
((sender as ASPxGridView).FindRowTemplateControl(..) method; here we use FindRowCellTempleteControl(..) method on HtmlRowCreated event of ASPxGridView.

Grid Markup:
  <dx:ASPxGridView ID="grvTest" AutoGenerateColumns="False" runat="server" DataSourceID="SqlDataSource1"
OnHtmlRowPrepared="grvTest_HtmlRowPrepared" OnHtmlRowCreated="grvTest_HtmlRowCreated">
<Columns>
<dx:GridViewDataTextColumn Caption="RowID" Name="colRowID" VisibleIndex="0" Width="20px">
<DataItemTemplate>
<dx:ASPxLabel ID="lblRowID" runat="server" Text='Label'>
</dx:ASPxLabel>
</DataItemTemplate>
</dx:GridViewDataTextColumn>


C#


protected void grvTest_HtmlRowCreated(object sender, ASPxGridViewTableRowEventArgs e)
{
if (e.RowType != GridViewRowType.Data) return;

ASPxLabel label = grvTest.FindRowCellTemplateControl(e.VisibleIndex, null,
"lblRowID") as ASPxLabel;
label.Text = (e.VisibleIndex + 1).ToString();
}



Displaying ASPxGridView row index number

You can achieve this through two way:
Method 1
Step 1. Add ASPxGridView on your page:

<dx:ASPxGridView ID="grvTest" AutoGenerateColumns="False" runat="server"
DataSourceID="SqlDataSource1" onhtmlrowprepared="grvTest_HtmlRowPrepared"
onhtmlrowcreated="grvTest_HtmlRowCreated">
<Columns>
<dx:GridViewDataTextColumn Caption="RowID" Name="colRowID" VisibleIndex="0"
Width="20px">
<DataItemTemplate>
<dx:ASPxLabel ID="lblRowID" runat="server" Text="lablel">
</dx:ASPxLabel>
</DataItemTemplate>
</dx:GridViewDataTextColumn>
<dx:GridViewDataTextColumn Caption="User Name" FieldName="UserName"
Name="colUserName" VisibleIndex="1" Width="100px">
</dx:GridViewDataTextColumn>
<dx:GridViewDataTextColumn Caption="Password" FieldName="Password"
Name="colPassword" VisibleIndex="2" Width="30px">
</dx:GridViewDataTextColumn>
<dx:GridViewDataTextColumn Caption="Role" FieldName="Role" Name="colRole"
VisibleIndex="3" Width="30px">
</dx:GridViewDataTextColumn>
</Columns>
</dx:ASPxGridView>

Step 2: Add following ASPxGridView Event code snippet to your code – behind file (.cs)

protected void grvTest_HtmlRowCreated(object sender, ASPxGridViewTableRowEventArgs e)
{
if (e.RowType != GridViewRowType.Data) return;

ASPxLabel label = grvTest.FindRowCellTemplateControl(e.VisibleIndex, null, "lblRowID") as ASPxLabel;
label.Text = (e.VisibleIndex + 1).ToString();
}

Method 2
The another way to do it is this one in the Columns section of your GridView control:

<dx:ASPxGridView ID="grvTest" AutoGenerateColumns="False" runat="server"
DataSourceID="SqlDataSource1" >
<Columns>
<dx:GridViewDataTextColumn Caption="RowID" Name="colRowID" VisibleIndex="0"
Width="20px">
<DataItemTemplate>
<dx:ASPxLabel ID="lblRowID" runat="server" Text='<%# Container.ItemIndex + 1 %>'>
</dx:ASPxLabel>
</DataItemTemplate>
</dx:GridViewDataTextColumn>

Thursday, November 3, 2011

ASPxGridView Hyperlink NavigateUrl at Runtime

In the ASPxHyperLink.Init handler, you can use the ASPxGridView.GetDetailRowKeyValue method with ASPxHyperLink.NamingContainer property as a parameter, to get the main grid row key value.

[C#]

protected void ASPxHyperLink1_Init(object sender, EventArgs e) {
ASPxHyperLink myLink =(ASPxHyperLink)sender;
int key = Convert.ToInt32(ASPxGridView.GetDetailRowKeyValue(myLink.NamingContainer));
}


It would be better to use a binding-expression for the ASPxHyperLink.NavigateUrl property in the .ASPX file.



[ASPx]



<EmptyDataRow>
<dx:ASPxHyperLink ID="ASPxHyperLink1" runat="server" Text="ASPxHyperLink"
NavigateUrl="<%# ASPxGridView.GetDetailRowKeyValue(Container) %>" />
</EmptyDataRow>

ASPxGridView DataRow Template Example

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication164._Default" %>

<%@ Register Assembly="DevExpress.Web.ASPxEditors.v8.3, Version=8.3.4.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a"
Namespace="DevExpress.Web.ASPxEditors" TagPrefix="dxe" %>

<%@ Register Assembly="DevExpress.Web.ASPxGridView.v8.3, Version=8.3.4.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a"
Namespace="DevExpress.Web.ASPxGridView" TagPrefix="dxwgv" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<dxwgv:ASPxGridView ID="ASPxGridView1" runat="server" DataSourceID="AccessDataSource1" AutoGenerateColumns="False"
KeyFieldName="ID" ClientInstanceName="grid">
<Columns>
<dxwgv:GridViewDataTextColumn FieldName="ID" VisibleIndex="0">
</dxwgv:GridViewDataTextColumn>
<dxwgv:GridViewDataTextColumn FieldName="FirstName" VisibleIndex="1">
</dxwgv:GridViewDataTextColumn>
<dxwgv:GridViewDataTextColumn FieldName="LastName" VisibleIndex="2">
</dxwgv:GridViewDataTextColumn>
<dxwgv:GridViewDataTextColumn FieldName="Company" VisibleIndex="3">
</dxwgv:GridViewDataTextColumn>
<dxwgv:GridViewDataTextColumn FieldName="Address" VisibleIndex="4">
</dxwgv:GridViewDataTextColumn>
<dxwgv:GridViewDataTextColumn FieldName="City" VisibleIndex="5">
</dxwgv:GridViewDataTextColumn>
<dxwgv:GridViewDataTextColumn FieldName="State" VisibleIndex="6">
</dxwgv:GridViewDataTextColumn>
<dxwgv:GridViewDataTextColumn FieldName="ZipCode" VisibleIndex="7">
</dxwgv:GridViewDataTextColumn>
<dxwgv:GridViewDataTextColumn FieldName="HomePhone" VisibleIndex="8">
</dxwgv:GridViewDataTextColumn>
</Columns>
<Templates>
<DataRow>
<div style="padding:5px">
<table width="100%" style="background-color:Silver">
<tr><td>First Name:&nbsp;<%# Eval("FirstName") %>
</td><td>Last Name:&nbsp;<%# Eval("LastName") %>
</td></tr><tr><td colspan="2">
<table width="100%">
<tr><td>State:&nbsp;<%# Eval("State") %>
</td><td>City:&nbsp;<%# Eval("City") %>
</td><td>Address:&nbsp;<%# Eval("Address") %>
</td></tr></table>
</td></tr>
<tr><td colspan="2">Company:&nbsp;<%# Eval("Company") %>
</td></tr></table>
<dxe:ASPxButton ID="ASPxButton2" runat="server" Text="Edit" AutoPostBack="False"
ClientSideEvents-Click='<%# "function(s, e) { grid.StartEditRow(" + Container.VisibleIndex + "); }" %>'>
</dxe:ASPxButton>
</div>
</DataRow>
<StatusBar>
<dxe:ASPxButton ID="ASPxButton1" runat="server" Text="New" AutoPostBack="False"
ClientSideEvents-Click="function(s, e) { grid.AddNewRow(); }">
</dxe:ASPxButton>
</StatusBar>
<EditForm>
<div>
<table width="100%"
style="background-color:Silver"><tr><td>First Name:
<dxe:ASPxTextBox ID="ASPxTextBox1"
runat="server" Value='<%# Bind("FirstName") %>' Width="100%">
</dxe:ASPxTextBox>
</td><td>Last Name:
<dxe:ASPxTextBox ID="ASPxTextBox2" runat="server"
Value='<%# Bind("LastName") %>' Width="100%">
</dxe:ASPxTextBox>
</td></tr><tr><td colspan="2">
<table width="100%"><tr><td>State:
<dxe:ASPxTextBox
ID="ASPxTextBox3" runat="server" Value='<%# Bind("State") %>' Width="100%">
</dxe:ASPxTextBox>
</td><td>City:
<dxe:ASPxTextBox ID="ASPxTextBox4" runat="server"
Value='<%# Bind("City") %>' Width="100%">
</dxe:ASPxTextBox>
</td><td>Address:
<dxe:ASPxTextBox ID="ASPxTextBox5"
runat="server" Value='<%# Bind("Address") %>' Width="100%">
</dxe:ASPxTextBox>
</td></tr></table>
</td></tr><tr><td colspan="2">Company:
<dxe:ASPxTextBox
ID="ASPxTextBox6" runat="server" Value='<%# Bind("Company") %>' Width="100%">
</dxe:ASPxTextBox>
</td></tr></table>
</div>
<dxwgv:ASPxGridViewTemplateReplacement runat="server" ReplacementType="EditFormUpdateButton" />
<dxwgv:ASPxGridViewTemplateReplacement runat="server" ReplacementType="EditFormCancelButton" />
</EditForm>
</Templates>
<Settings ShowColumnHeaders="False" ShowStatusBar="Visible" />
<SettingsEditing Mode="EditForm" />
</dxwgv:ASPxGridView>
<asp:AccessDataSource ID="AccessDataSource1" runat="server" DataFile="~/App_Data/Contacts.mdb"
SelectCommand="SELECT * FROM [Customers]"></asp:AccessDataSource>

</div>
</form>
</body>
</html>



To provide editing capabilities you can add the ASPxButton into the DataRow template. Set its AutoPostBack property to False, and attach a script to the client-side Click event. In the script, call the ASPxClientGridView.StartEditRow method, and pass the current row visible index in argument. Use the Container.VisibleIndex property from inline code to get the index.

To add new rows, add a similar button to the StatusBar template, and call the ASPxClientGridView.AddNewRow method in its Click event.





You can get some functionality using the Container object like  Container.KeyValue, Container.VisibleIndex.


Along this formatting in the text is also possible through sever side code calling e.g. String.Format




<dx:ASPxLabel ID="BirthDateLabel" runat="server" Text='<%# String.Format("{0:d}",
Eval("BirthDate")) %>' />



Another example of DataRow Template :




<div>

<dxwgv:ASPxGridView ID="ASPxGridView1" runat="server"

AutoGenerateColumns="False" DataSourceID="AccessDataSource1"

KeyFieldName="CustomerID" ClientInstanceName="grid">

<SettingsEditing Mode="Inline" />

<Columns>

<dxwgv:GridViewCommandColumn VisibleIndex="0">

<EditButton Visible="True">

</EditButton>

</dxwgv:GridViewCommandColumn>

<dxwgv:GridViewDataTextColumn FieldName="CustomerID" ReadOnly="True"

VisibleIndex="1">

</dxwgv:GridViewDataTextColumn>

<dxwgv:GridViewDataTextColumn FieldName="CompanyName" VisibleIndex="2">

</dxwgv:GridViewDataTextColumn>

<dxwgv:GridViewDataTextColumn FieldName="City" VisibleIndex="3">

</dxwgv:GridViewDataTextColumn>

<dxwgv:GridViewDataTextColumn FieldName="Country" VisibleIndex="4">

</dxwgv:GridViewDataTextColumn>

</Columns>

<SettingsPager PageSize="5" />

<Templates>

<DataRow>

<div style="padding:5px">

<table border="1" cellpadding="2" cellspacing="1" width="100%">

<tr>

<td width="150px" rowspan="4"><a href="#" onclick="grid.AddNewRow();">New</a>

<a href="##" onclick="grid.StartEditRow(<%# Container.VisibleIndex %>);">Edit</a>

<a href="###" onclick="grid.DeleteRow(<%# Container.VisibleIndex %>);">Delete</a></td>

<td width="300px"></td>

<td></td>

</tr>

<tr>

<td>CompanyName</td>

<td><%# Eval("CompanyName")%></td>

</tr>

<tr>

<td>City</td>

<td><%# Eval("City")%></td>

</tr>

<tr>

<td>Country</td>

<td ><%# Eval("Country")%></td>

</tr>

</table>

</div>

</DataRow>

</Templates>

</dxwgv:ASPxGridView>

<asp:AccessDataSource ID="AccessDataSource1" runat="server"

DataFile="~/App_Data/nwind.mdb"

DeleteCommand="DELETE FROM [Customers] WHERE [CustomerID] = ?"

InsertCommand="INSERT INTO [Customers] ([CustomerID], [CompanyName], [City], [Country]) VALUES (?, ?, ?, ?)"

SelectCommand="SELECT [CustomerID], [CompanyName], [City], [Country] FROM [Customers]"

UpdateCommand="UPDATE [Customers] SET [CompanyName] = ?, [City] = ?, [Country] = ? WHERE [CustomerID] = ?">

<DeleteParameters>

<asp:Parameter Name="CustomerID" Type="String" />

</DeleteParameters>

<UpdateParameters>

<asp:Parameter Name="CompanyName" Type="String" />

<asp:Parameter Name="City" Type="String" />

<asp:Parameter Name="Country" Type="String" />

<asp:Parameter Name="CustomerID" Type="String" />

</UpdateParameters>

<InsertParameters>

<asp:Parameter Name="CustomerID" Type="String" />

<asp:Parameter Name="CompanyName" Type="String" />

<asp:Parameter Name="City" Type="String" />

<asp:Parameter Name="Country" Type="String" />

</InsertParameters>

</asp:AccessDataSource>

</div>

Wednesday, November 2, 2011

How to refresh a ASPxGridView summary value on the client side

The ASPxGridView is a server side control, so it renders on the server side.

If you know how the summary value should be changed using the client side code, you need to do the following:

1) add the ASPxLabel to the column's FooterTemplate container and set its ClientInstanceName to a some value, for example, lblFooter;
2) use the lblFooter.SetText('some text') to change the displayed summary value.

Here is some sample code:

[ASPx]

<dx:GridViewDataTextColumn FieldName="CategoryID" ReadOnly="True" VisibleIndex="1">
<EditFormSettings Visible="False" />
<FooterTemplate>
<dx:ASPxLabel ID="ASPxLabel1" ClientInstanceName ="lblFooter" runat="server"
Text="<%# GetSummaryValue(Container)%>">
</dx:ASPxLabel>
</FooterTemplate>
</dx:GridViewDataTextColumn>
....


[C#]



protected string GetSummaryValue(GridViewFooterCellTemplateContainer container) {
ASPxGridView gridView = container.Grid;
GridViewDataColumn column = container.Column as GridViewDataColumn;
if(column == null)
return string.Empty;
for(int i = 0; i < gridView.TotalSummary.Count; i ++)
if(gridView.TotalSummary[i].FieldName == column.FieldName) {
return gridView.GetTotalSummaryValue(gridView.TotalSummary[i]).ToString();
}
return string.Empty;
}

Monday, October 17, 2011

ASPxGridView GridViewCommandColumn delete button image at runtime with delete confirmation

 Scenario:
I have aspxGridView with list of items and i want to confirm from user before deletion
of a row/ record.

Solution:
There are two approach to achieve this target. one is
Using the in-built Delete button:  
GridViewCommandColumn.DeleteButton


and another is:
Custom Button that you will create from scratch

Sunday, September 18, 2011

Changing ASPxGridView Cell and Row Color on Condition

Changing ASPxGridView Cell Color:

To work with this functionality use the ASPxGridView.HtmlDataCellPrepared event. Here you can get values from other fields within the same row using the e.GetValue method. Using this value setup your condition and set the formatting on the cell. using the ASPxGridView ASPxGridViewTableDataCellEventArgs object named e here. e.g.
protected void grvProduct_HtmlDataCellPrepared(object sender, 
DevExpress.Web.ASPxGridView.ASPxGridViewTableDataCellEventArgs e)
{
if (e.DataColumn.FieldName != "Stock") return;
if (Convert.ToInt32(e.CellValue) < 100)
e.Cell.BackColor = System.Drawing.Color.Red;
}
}

Changing ASPxGridView Row Color:

To work with this functionality use the ASPxGridView.HtmlRowPrepared event.Here you can get values from other fields within the same row using the e.GetValue method. Using this value setup your condition and set the formatting on the row and cell(e.Row.Cell is accessible here) using the ASPxGridView ASPxGridViewTableDataRowEventArgs object named e here.
protected void grvProduct_HtmlRowPrepared(object sender, 
DevExpress.Web.ASPxGridView.ASPxGridViewTableRowEventArgs e)
{
if (e.RowType != DevExpress.Web.ASPxGridView.GridViewRowType.Data) return;
decimal value = (decimal)e.GetValue("Stock");
if (value < 100)
e.Row.ForeColor = Color.Red;
}

Wednesday, September 14, 2011

client-side ASPxClientGridView.SelectionChanged event is raised twice

Regarding to issue: ASPxGridView - SelectionChanged event fires twice when selecting rows manually, and once when selection is performed on the client side

Reason: The ASPxClientGridView.SelectionChanged event is raised each time row selection is changed. If ASPxGridView allows selecting only one row, the previously selected row is unselected before another row is selected. Row unselection is also a selection change action. Therefore the SelectionChanged event is raised. Next time this event is raised when the new row is selected. So, a callback is sent twice in the sample project.
You can use the e.isSelected property to check whether a row has been selected or unselected.

Solution: It is the behavior of the grid, so you need to determine that whether row get select or unselect.

The client-side ASPxClientGridView.SelectionChanged event is raised twice
 (e.processOnServer == true), add the following condition to your code to
enable both ASPxButtons on the client side only when DataRow is selected:

SelectionChanged="function(s, e) {
if (e.isSelected) {
clBtnMentes.SetEnabled(e.isSelected);
clBtnMegsem.SetEnabled(e.isSelected);
}
}";



Thursday, August 25, 2011

Set Custom Error Message in ASPxGridView


This enable you to specify whether row data is valid and whether the row can be updated.
The RowValidating event is automatically raised when a row is about to be updated, and allows you to
specify whether its data is valid. To manually validate the edited row, call the
DoRowValidation method.

To obtain the edited row's values, use the event parameter's ASPxDataValidationEventArgs.NewValues
property. The old values are returned by the
ASPxDataValidationEventArgs.OldValues property. If the
value is invalid, use the
ASPxDataValidationEventArgs.Errors property to specify the error description
text. As a result, an error icon will be displayed next to the invalid value. Pointing to the icon shows the
hint with the error description.

using DevExpress.Web.ASPxGridView;
using System.Collections.Generic;
namespace Petshop.Core
{
    class RowValidationDemo
    {
        protected void grid_RowValidating(object sender,
DevExpress.Web.Data.ASPxDataValidationEventArgs e)
        {
            // Checks for null values.
            foreach (GridViewColumn column in grid.Columns)
            {
                GridViewDataColumn dataColumn = column as GridViewDataColumn;
                if (dataColumn == null) continue;
                if (e.NewValues[dataColumn.FieldName] == null)
                    e.Errors[dataColumn] = "Value cannot be null.";
            }
            // Displays the error row if there is at least one error.
            if (e.Errors.Count > 0) e.RowError = "Please, fill all fields.";

            if (e.NewValues["ContactName"] != null &&
                e.NewValues["ContactName"].ToString().Length < 2)
            {
                AddError(e.Errors, grid.Columns["ContactName"],
                "Contact Name must be at least two characters long.");
            }
            if (e.NewValues["CompanyName"] != null &&
            e.NewValues["CompanyName"].ToString().Length < 2)
            {
                AddError(e.Errors, grid.Columns["CompanyName"],
                "Company Name must be at least two characters long.");
            }
            if (string.IsNullOrEmpty(e.RowError) && e.Errors.Count > 0)
                e.RowError = "Please, correct all errors.";
        }

        void AddError(Dictionary<GridViewColumn, string> errors,
        GridViewColumn column, string errorText)
        {
            if (errors.ContainsKey(column)) return;
            errors[column] = errorText;
        }

        protected void grid_HtmlRowPrepared(object sender,
        ASPxGridViewTableRowEventArgs e)
        {
            // Checks whether the generated row has the errors.
            bool hasError = e.GetValue("ContactName").ToString().Length <= 1;
            hasError = hasError || e.GetValue("CompanyName").ToString().Length <= 1;
            hasError = hasError || e.GetValue("Country") == null;
            // If the row has the error(s), its text color is set to red.
            if (hasError)
                e.Row.ForeColor = System.Drawing.Color.Red;
        }

        protected void grid_StartRowEditing(object sender,
        DevExpress.Web.Data.ASPxStartRowEditingEventArgs e)
        {
            // Validates the edited row if it isn't a new row,.
            if (!grid.IsNewRowEditing)
                grid.DoRowValidation();
        }

    }
}
The HtmlRowPrepared event is handled to paint the row's contents red if the row is invalid. This event is raised
for each data row when the corresponding row within the table has been created. This indicates rows within
invalid data.

The StartRowEditing event is handled to display erorrs (if any) within the edited row when an end-user
switches to edit mode.

Another Way is collect the exception at ASPxGridView CustomErrorText event and set the e.ErrorText property to show
the custom error text.
string customeErrorMessage = string.Empty;

if
(e.Exception is ExceptionType)
{
       customeErrorMessage = your message;
}
e.ErrorText = customeErrorMessage;

When the ASPxGridView launches a callback that catches exceptions by default, since each exception during page processing cancels the generation of the page. Even if a callback, the ASPxGridView (and other controls DX) catch exceptions to display in the proper format. For example, the ASPxGridView displays an error, display an alert ASPxCallbackPanel and so on.
If you catch exceptions with a try ... catch the ASPxGridView see that all is well and not make the error message.

 



 

Wednesday, August 24, 2011

Specified method is not supported - ASPxGridView Exception


When you use a complex LINQ query, the result that is returned from the Linq-To-Sql is a
projection that can't be edited. All its properties are set as read-only.
The DataController determines that the datasource has fields with get accessors only, and
"tells" the ASPxGridView to render fields in readonly mode.

A possible solution is to remove the ReadOnly attribute in the ASPxGridView.CellEditorInitialize
event handler:
[C#]
e.Editor.ReadOnly = false;
A custom updating and inserting can be implemented by handling the ASPxGridView.RowUpdating
and ASPxGridView.RowInserting events.
[C#]
var obj = /* find an object by e.Keys[0] */;
obj.Prop = e.NewValues["Prop"];
...
obj.Save;

e.Cancel = true;
grid.CancelEdit();

When you do insert or Update Operations in the DevExpress ASPxGridView then this kind of
exception occurred after completing these operations. To prevent this just add the following two lines
of code to avoid the problem in the  RowInsert or RowUpdating events.
e.Cancel = true;
grid.CancelEdit();

Tuesday, August 23, 2011

Insert, edit and delete data in a data table by ASPxGridView at runtime

It shows how to insert, edit and delete data in a data table by ASPxGridView. The data table and the
grid are created at runtime.
public partial class _Default : System.Web.UI.Page {
    private DataTable dataTable;

    protected void Page_Load(object sender, EventArgs e) {
        CreateGrid();
    }

    private DataTable CustomDataSourse {
        get {
            if (dataTable != null)
                return dataTable;

            dataTable = ViewState["CustomTable"] as DataTable;
            if (dataTable != null)
                return dataTable;


            dataTable = new DataTable("CustomDTable");
            dataTable.Columns.Add("Id", typeof(Int32));
            dataTable.PrimaryKey = new DataColumn[] { dataTable.Columns[0] };
            dataTable.Columns.Add("Data", typeof(string));

            dataTable.Rows.Add(0, "Data1");
            dataTable.Rows.Add(1, "Data2");
            dataTable.Rows.Add(2, "Data3");
            dataTable.Rows.Add(3, "Data4");
            dataTable.Rows.Add(4, "Data5");
            ViewState["CustomTable"] = dataTable;

            return dataTable;
        }
    }
    protected void grid_DataBinding(object sender, EventArgs e) {
        (sender as ASPxGridView).DataSource = CustomDataSourse;
    }
    protected void grid_DataBound(object sender, EventArgs e) {
        ASPxGridView g = sender as ASPxGridView;
        for (int i = 0; i < g.Columns.Count; i++) {
            GridViewDataTextColumn c = g.Columns[i] as GridViewDataTextColumn;
            if (c == null)
                continue;

            c.PropertiesTextEdit.ValidationSettings.RequiredField.IsRequired = true;
        }

    }


    protected void grid_RowDeleting(object sender, ASPxDataDeletingEventArgs e) {
        int id = (int)e.Keys[0];
        DataRow dr = CustomDataSourse.Rows.Find(id);
        dataTable.Rows.Remove(dr);

        ASPxGridView g = sender as ASPxGridView;
        UpdateData(g);
        e.Cancel = true;
    }
    protected void grid_RowUpdating(object sender, ASPxDataUpdatingEventArgs e) {
        int id = (int)e.OldValues["Id"];
        DataRow dr = CustomDataSourse.Rows.Find(id);
        dr[0] = e.NewValues["Id"];
        dr[1] = e.NewValues["Data"];

        ASPxGridView g = sender as ASPxGridView;
        UpdateData(g);
        g.CancelEdit();
        e.Cancel = true;
    }
    protected void grid_RowInserting(object sender, ASPxDataInsertingEventArgs e) {
        CustomDataSourse.Rows.Add(e.NewValues["Id"], e.NewValues["Data"]);

        ASPxGridView g = sender as ASPxGridView;
        UpdateData(g);
        g.CancelEdit();
        e.Cancel = true;
    }

    private void CreateGrid() {
        ASPxGridView grid = new ASPxGridView();
        grid.ID = "grid";
        this.Form.Controls.Add(grid);

        grid.EnableCallBacks = false;
        grid.KeyFieldName = "Id";

        grid.DataBinding += grid_DataBinding;
        grid.RowDeleting += grid_RowDeleting;
        grid.RowUpdating += grid_RowUpdating;
        grid.RowInserting += grid_RowInserting;
        grid.DataBound += grid_DataBound;
        grid.RowValidating += new ASPxDataValidationEventHandler(grid_RowValidating);
        grid.DataBind();
        if (!this.IsPostBack) {
            GridViewCommandColumn c = new GridViewCommandColumn();
            grid.Columns.Add(c);

            c.EditButton.Visible = true;
            c.UpdateButton.Visible = true;
            c.NewButton.Visible = true;
            c.DeleteButton.Visible = true;
            c.CancelButton.Visible = true;
        }

        GridViewDataTextColumn col = grid.Columns["Id"] as GridViewDataTextColumn;
        col.PropertiesTextEdit.ValidationSettings.RegularExpression.ValidationExpression
                                                                            = "\\d{1,9}";
    }

    void grid_RowValidating(object sender, ASPxDataValidationEventArgs e) {       
        int id = (int)e.NewValues["Id"];
        if ((!e.OldValues.Contains("Id") || ((int)e.OldValues["Id"] != id))
            && (CustomDataSourse.Rows.Find(id) != null)) {
            ASPxGridView grid = sender as ASPxGridView;
            e.Errors[grid.Columns["Id"]] =
String.Format("Column 'Id' is constrained to be unique.  Value '{0}' is already present.", id);
        }
    }
    private void UpdateData(ASPxGridView g) {
        ViewState["CustomTable"] = dataTable;
        g.DataBind();
    }
}