I am facing a problem for validating the dependency controls. How to validate the another controls which is based on the values of dropdownlist (combo box). Please see the below example. For Example : A dropdown has two values A and B. If user selects "A", then rest of the fields should become required fields and if user selects value “B” from the dropdown, then all other fields should become non-mandatory fields.
Note : i am using the devexpress gridview with default template.
<dx:ASPxGridView ID="ABC" runat="server" AutoGenerateColumns="False"
DataSourceID="ABCDataSource" EnableTheming="True"
Width="100%" ClientInstanceName="gridABC">
<Columns>
<dx:GridViewCommandColumn Caption="Actions" ShowInCustomizationForm="True"
VisibleIndex="0">
<EditButton Visible="True">
</EditButton>
</dx:GridViewCommandColumn>
<dx:GridViewDataComboBoxColumn Caption="List of Type" FieldName="ListType"
ShowInCustomizationForm="True" VisibleIndex="4" Width="100px">
<PropertiesComboBox DataSourceID="ListTypeDataSource"
TextField="ListTypeABC" ValueField="ListTypeABCId" Width="100px">
<ValidationSettings>
<RequiredField ErrorText="ListType required" IsRequired="True" />
</ValidationSettings>
</PropertiesComboBox>
<EditFormSettings ColumnSpan="1" VisibleIndex="1" />
</dx:GridViewDataComboBoxColumn>
<dx:GridViewDataTextColumn Caption="Name" FieldName="Name" ShowInCustomizationForm="True"
VisibleIndex="2" Width="100px">
<PropertiesTextEdit MaxLength="30" Width="100px">
<ValidationSettings>
<RequiredField ErrorText="Item Name required" IsRequired="False" />
</ValidationSettings>
</PropertiesTextEdit>
<EditFormSettings ColumnSpan="1" VisibleIndex="2" />
</dx:GridViewDataTextColumn>
<dx:GridViewDataTextColumn Caption="Contact" FieldName="Contact" ShowInCustomizationForm="True"
VisibleIndex="3" Width="100px">
<PropertiesTextEdit MaxLength="30" Width="100px">
<ValidationSettings>
<RequiredField ErrorText="Contact" IsRequired="False" />
</ValidationSettings>
</PropertiesTextEdit>
<EditFormSettings ColumnSpan="1" VisibleIndex="3" />
</dx:GridViewDataTextColumn>
<Templates>
<EditForm>
<table>
<tr>
<td>`<dx:ASPxGridViewTemplateReplacement ReplacementType="EditFormEditors" ID="ASPxGridViewTemplateReplacement1"
runat="server">
</dx:ASPxGridViewTemplateReplacement>
`
The simplest approach is to set the DropDownList's AutoPostBack property to true and handle it's SelectedIndexChanged event. Then you can Enable/Disable the validator there.
Another approach is to use a CustomValidator. This validator is not dependent on a single control. You must write the validation rules on your own. For example the ClientValidationFunction:
<script type="text/javascript" >
function ClientValidate(source, arguments)
{
var txt = document.getElementById('TextBox1');
var ddl = document.getElementById('DropDownList1');
var decision = ddl.options[ddl.selectedIndex].text;
if(decision=='Yes')
{
arguments.IsValid = txt.value.length > 0;
}else{
arguments.IsValid = true;
}
}
</script>
<asp:DropDownList id="DropDownList1" runat="server">
<asp:ListItem Selected="True">Yes</asp:ListItem>
<asp:ListItem Selected="False">No</asp:ListItem>
</asp:DropDownList>
<asp:TextBox id="TextBox1" runat="server" />
<asp:Button ID="BtnSubmit" runat="server" Text="Submit" />
<asp:CustomValidator id="CustomValidator1"
ValidateEmptyText="true"
ControlToValidate="TextBox1"
ClientValidationFunction="ClientValidate"
OnServerValidate="ServerValidation"
Display="Static"
ErrorMessage="Please enter text!"
runat="server"/>
Remember to always implement a OnServerValidate because you should not rely on javascript only(can be disabled). This is easy:
void ServerValidation(object source, ServerValidateEventArgs args)
{
args.IsValid = DropDownList1.SelectedIndex == 1 || TextBox1.Text.Length > 0;
}
Related
Label text not updating after handling gridview row update.
My devexpress gridview has a row updating handler that when I try to change the text on a label, that change is not reflected on the screen.
I am not getting any error either.
<%# Register Assembly="DevExpress.Web.v19.2, Version=19.2.3.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a"
Namespace="DevExpress.Web" TagPrefix="dxwgv" %>
df
<dxwgv:ASPxGridView ID="aspxgrdNotes" KeyFieldName="PoolItemNoteId" ClientInstanceName="grdNotes" OnRowUpdating="aspxgrdNotes_RowUpdating"
runat="server" AutoGenerateColumns="False" EnableRowsCache="false">
<SettingsCommandButton>
<EditButton ButtonType="Image" Text="Edit" Image-IconID="edit_edit_16x16" />
</SettingsCommandButton>
<Columns>
<dxwgv:GridViewDataTextColumn Caption="Id" FieldName="PoolItemNoteId" VisibleIndex="0" ReadOnly="true" CellStyle-Wrap="True" Width="100px" Visible="false"/>
<dxe:GridViewCommandColumn VisibleIndex="3" ShowEditButton="true" Caption="Edit"/>
<dxwgv:GridViewDataTextColumn Caption="Date" FieldName="NoteDate" VisibleIndex="2" ToolTip="Created Date"
ReadOnly="true" Width="100px">
<PropertiesTextEdit DisplayFormatString="{0:MM/dd/yyyy}" EncodeHtml="False">
</PropertiesTextEdit>
</dxwgv:GridViewDataTextColumn>
<dxwgv:GridViewDataTextColumn Caption="Note" FieldName="NoteText" VisibleIndex="2"
ReadOnly="false" CellStyle-Wrap="True" Width="600px">
</dxwgv:GridViewDataTextColumn>
</Columns>
<SettingsPager PageSize="25" ShowDefaultImages="False" Position="TopAndBottom">
<AllButton Text="All" />
<NextPageButton Text="Next >" />
<PrevPageButton Text="< Prev" />
</SettingsPager>
<Settings ShowFilterRow="true" ShowHeaderFilterButton="true" ShowGroupPanel="True" />
<SettingsBehavior AllowMultiSelection="false" AllowGroup="true" />
<SettingsPager PageSize="25" ShowDefaultImages="False">
<AllButton Visible="true" Text="All" />
<FirstPageButton Visible="true" />
<LastPageButton Visible="true" />
<NextPageButton Text="Next >">
</NextPageButton>
<PrevPageButton Text="< Prev">
</PrevPageButton>
</SettingsPager>
<Templates>
<EmptyDataRow>
No notes entered for this pool item.
</EmptyDataRow>
</Templates>
</dxwgv:ASPxGridView>
<dxwgv:ASPxLabel runat="server" ID="lblErrMsg" Text="" ForeColor="DarkRed" Visible="false"></dxwgv:ASPxLabel>
code behind:
Protected Sub aspxgrdNotes_RowUpdating(sender As Object, e As DevExpress.Web.Data.ASPxDataUpdatingEventArgs) Handles aspxgrdNotes.RowUpdating
e.Cancel = True
Me.aspxgrdNotes.CancelEdit()
' Update note
Dim poolItemNote As New PoolItemNote
If poolItemNote.LoadByPrimaryKey(e.Keys("PoolItemNoteId")) Then
poolItemNote.NoteText = e.NewValues("NoteText")
poolItemNote.ModBy = ALGMembershipUser.UserName
poolItemNote.ModTime = DateTime.Now
poolItemNote.Save()
' Rebind the notes grid
BindJobDetailData()
Else
lblErrMsg.Text = "Error updating note. Try reloading the page."
lblErrMsg.Visible = True
End If
End Sub
I was able to fix this by setting the EnableCallBacks property of the ASPxGridView to false
I have a nested ASPxGridView inside another ASPxGridView. The second grid is in the DetailRow Template area.
Based on the user's role I need to enable/disable buttons (on the server side).
I can find and then perform actions on buttons when they are located in the GridViewDataColumn area (see buttonDocumentTypeEdit and buttonDocumentSubtypeEdit buttons). I use OnHtmlDataCellPrepared event for that purpose.
But I cannot find the way to find buttonDocumentSubtypeAdd button on the server side, which is in the DetailRow area.
ASPxGridView:
<dx:ASPxGridView ID="gridDocumentTypes" ClientInstanceName="gridDocumentTypes" runat="server" AutoGenerateColumns="False"
DataSourceID="odsDocumentTypes" KeyFieldName="Id" Width="100%"
OnHtmlDataCellPrepared="gridDocumentTypes_OnHtmlDataCellPrepared">
<Columns>
<dx:GridViewDataTextColumn Caption="Document Type" FieldName="Name"/>
<dx:GridViewDataColumn Name="columnDocumentTypeActions">
<DataItemTemplate>
<dx:ASPxButton ID="buttonDocumentTypeEdit" runat="server" Text="Edit"/>
</DataItemTemplate>
</dx:GridViewDataColumn>
</Columns>
<Templates>
<DetailRow>
<dx:ASPxButton ID="buttonDocumentSubtypeAdd" ClientInstanceName="buttonDocumentSubtypeAdd" runat="server"
Text= "Add Subtype" AutoPostBack="False" UseSubmitBehavior="False">
</dx:ASPxButton>
<dx:ASPxGridView ID="gridDocumentSubtypes" runat="server" ClientInstanceName="gridDocumentSubtypes"
DataSourceID="GetDocumentSubtypes" KeyFieldName="Id" Width="100%">
<Columns>
<dx:GridViewDataColumn FieldName="Name" Caption="Document Subtype" />
<dx:GridViewDataColumn Name="columnDocumentSubtypeActions">
<DataItemTemplate>
<table>
<tr>
<td style="padding-right: 5px">
<dx:ASPxButton ID="buttonDocumentSubtypeEdit" runat="server" Text="Edit">
</dx:ASPxButton>
</td>
</tr>
</table>
</DataItemTemplate>
</dx:GridViewDataColumn>
</Columns>
</dx:ASPxGridView>
</DetailRow>
</Templates>
</dx:ASPxGridView>
Server code:
protected void gridDocumentTypes_OnHtmlDataCellPrepared(object sender, ASPxGridViewTableDataCellEventArgs e)
{
if (e.DataColumn.Name == "columnDocumentTypeActions")
{
var buttonEdit = (ASPxButton)gridDocumentTypes.FindRowCellTemplateControl(e.VisibleIndex, e.DataColumn, "buttonDocumentTypeEdit");
//TODO: action
}
}
I am very new to dev express .
<dx:ASPxGridView ID="aspxgvOMContracts" runat="server" KeyFieldName="OMContractId" Settings-UseFixedTableLayout="true"
AutoGenerateColumns="False" Settings-HorizontalScrollBarMode="Auto" Width="477px" Theme="PlasticBlue"
OnRowUpdating="aspxgvOMContracts_OnRowUpdating" OnRowUpdated="aspxgvOMContracts_OnRowUpdated">
<SettingsPager PageSize="5" />
<SettingsBehavior AllowFocusedRow="true" />
<SettingsEditing Mode="Inline" />
<%-- <Styles>
<CommandColumnItem Spacing="">
<Paddings PaddingLeft="7" PaddingRight="7" />
</CommandColumnItem>
</Styles>--%>
<Columns>
<dx:GridViewCommandColumn ButtonType="Image" Width="65px" VisibleIndex="0">
<EditButton Visible="True" Image-Url="../Content/Images/icon_edit.png">
</EditButton>
<UpdateButton Visible="True" Image-Url="../Content/Images/icon_update.png">
</UpdateButton>
<CancelButton Visible="true" Image-Url="../Content/Images/icon_cancel.png">
</CancelButton>
<DeleteButton Visible="true" Image-Url="../Content/Images/icon_delete.png">
</DeleteButton>
<ClearFilterButton Visible="True">
</ClearFilterButton>
<%-- <HeaderTemplate>
<dx:ASPxLabel ID="headerLabel" runat="server">
</dx:ASPxLabel>
</HeaderTemplate>--%>
</dx:GridViewCommandColumn>
<dx:GridViewDataComboBoxColumn FieldName="OrganisationName" Caption="OrganisationName" VisibleIndex="1">
<PropertiesComboBox TextField="CompanyName" ValueField="OrganisationId" ValueType="System.Int32">
</PropertiesComboBox>
</dx:GridViewDataComboBoxColumn>
<dx:GridViewDataTimeEditColumn FieldName="DateAnnounced" Caption="DateAnnounced" VisibleIndex="2">
</dx:GridViewDataTimeEditColumn>
<dx:GridViewDataTextColumn FieldName="Cost" Caption="Cost" VisibleIndex="3">
</dx:GridViewDataTextColumn>
<dx:GridViewDataTextColumn FieldName="CostCurrency" Caption="Cost Currency" VisibleIndex="4">
</dx:GridViewDataTextColumn>
</Columns>
</dx:ASPxGridView>
and in code behind i Bind the data as
aspxgvOMContracts.DataSource = phase.OMContracts;
aspxgvOMContracts.DataBind();
here phase.OMContracts is of type List()
Now once I edit any row I need the modified collection back . How do I get the modified collection ?
You have assigned the DataSource Property of AspxGridview control then you can directly access that assigned assigned List from DataSource Property, it is a read and write property.
Check the documentation:
ASPxDataWebControlBase.DataSource Property
Gets or sets the object from which the data-bound control retrieves
its list of data items.
From: Get GridView data source to Data table
if you bind gridview on every postback..then you can get DataTable dt = GridView1.DataSource as DataTable;
Same for you alos as List<SomeType> data = grid.DataSource as List<SomeType>;
Hope this help..
for testing i have tried customvalidation
function ClientValidate(sender, args) {
//return false for testing...
args.IsValid = false;
}
<asp:CustomValidator runat="server" ID="CustomValidator1" ControlToValidate="ddldetail"
Text="Please select" ValidateEmptyText="true"
ClientValidationFunction="ClientValidate"
Display="Dynamic">
</asp:CustomValidator>
edit: here is what i exaclty wants to happen:
how to validate a dropdownlist and i have done this zillion times but what i am doing wrong here? any second pair of eye might spot it? i am trying to validate the dropdownlist if the user have not select any help?
<asp:Button ID="btn" runat="server" Text="Submit" OnClick="btn_Click" CausesValidation="true"/>
<asp:GridView ID="GVInputMapping" runat="server" AutoGenerateColumns="False" DataKeyNames="Id"
EnableModelValidation="True" onrowdatabound="GVInputMapping_RowDataBound">
<Columns>
<asp:BoundField DataField="Name" ControlStyle-Width="250px" HeaderText="Name" SortExpression="Name" />
<asp:TemplateField>
<ItemTemplate>
<asp:DropDownList runat="server" ID="ddldetail">
<asp:ListItem Selected="True" Value="0">Select me</asp:ListItem>
<asp:ListItem Value="1">abc</asp:ListItem>
<asp:ListItem Value="2">GHt</asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="requiredDDL" runat="server"
ControlToValidate="ddldetail" ErrorMessage="Please select" InitialValue="Select me" Display="Dynamic"></asp:RequiredFieldValidator>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
You have the InitialValue of the validator set to Select me, but the Value of that item is actually 0:
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem Text="Select Me" Value="0" />
<asp:ListItem Text="Foo" Value="1" />
<asp:ListItem Text="Bar" Value="2" />
</asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="DropDownList1"
ErrorMessage="Please select"
InitialValue="0"
Display="Dynamic">
</asp:RequiredFieldValidator>
You'll also need to assign a unique validation group for each row, otherwise validation will kick off for every row. To assign a unique validation group, you can use the Id column:
ValidationGroup='<%# string.Format("Group_{0}", Eval("Id")) %>'
You would add this to the validator and the button in the row.
I am having an issue where I have a custom validator on each row in a gridview, and a summary at the bottom of the panel the gridview sits in.
The custom validator fires when it is supposed and I set args.IsValid=false and assign an appropriate error message, but on my screen I don't see either the text of my custom validator, or the errorMessage in my summary. In fact I don't see my summary at all.
I have looked and I can't see why this would be happening, as I have a used near-identical setup elsewhere and it worked fine.
Markup:
<asp:GridView ID="gvConsolidatedPeriods" runat="server" OnRowDataBound="gvConsolidatedPeriods_OnRowDataBound" SkinID="alternativeRows"
AutoGenerateColumns="false" Width="99%" OnDataBound="gvConsolidatedPeriods_OnDataBound" OnRowEditing="gvConsolidatedPeriods_OnRowEditing"
OnRowCancelingEdit="gvConsolidatedPeriods_OnRowCancellingEdit" OnRowDeleting="gvConsolidatedPeriods_OnRowDeleting" ValidationGroup="ConsolidatedPeriodValidationGroup">
<Columns>
<asp:TemplateField HeaderText="Period">
<HeaderStyle Font-Bold="True" HorizontalAlign="Left" Width="250px" />
<ItemStyle HorizontalAlign="Left" Width="250px" />
<ItemTemplate>
<asp:Label ID="lblPeriod" runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:HiddenField ID="hdPeriodId" runat="server" />
<asp:Label ID="lblPeriod" runat="server" Visible="false"/>
<asp:TextBox ID="txtFromDate" runat="server" CssClass="datepicker" Visible="false"/>
<br />
<asp:Label ID="lblTo" runat="server" Visible="false" Text=" to " CssClass="label" />
<br />
<asp:TextBox ID="txtEndDate" runat="server" CssClass="datepicker" Visible="false"></asp:TextBox>
abc
<asp:CustomValidator ID="cvConsolidatedPeriodDates" runat="server" ValidationGroup="ConsolidatedPeriodValidationGroup" Text="*"
SetFocusOnError="True" ErrorMessage="" OnServerValidate="cvConsolidatedPeriodDates_OnServerValidate" ValidateEmptyText="true" Visible="true" Style=""/>s
</EditItemTemplate>
</asp:TemplateField>
...
Server Validate Code:
var rowToSave = gvConsolidatedPeriods.Rows[gvConsolidatedPeriods.EditIndex];
if (rowToSave != null)
{
var txtfromDate = rowToSave.FindControl("txtFromDate") as TextBox;
var txtendDate = rowToSave.FindControl("txtEndDate") as TextBox;
var cvConsolidatedPeriodValidator =
rowToSave.FindControl("cvConsolidatedPeriodDates") as CustomValidator;
var test = source as CustomValidator;
if (txtfromDate != null && txtendDate != null && txtfromDate.Visible)
{
if (String.IsNullOrEmpty(txtfromDate.Text))
{
args.IsValid = false;
test.ErrorMessage = "Period Dates are required";
return;
}
...