VS2013, WebForms, .NET 4.51
I have a FormView defined and in my EditTemplate I have as follows:
<div class="form-group">
<asp:Label ID="lblClientClassification" CssClass="col-md-2 control-label" runat="server" for="cblClientClassifications" Text="Kind"></asp:Label>
<div class="col-md-5">
<asp:CheckBoxList ID="cblClientClassifications" runat="server"></asp:CheckBoxList>
<asp:CustomValidator ID="cfvClientKinds" runat="server" Display="Dynamic" CssClass="label label-danger" ErrorMessage="XXXX" ValidationGroup="Default" OnServerValidate="cfvClientClassifications_OnServerValidate"></asp:CustomValidator>
</div>
and then in the code behind:
protected void cfvClientClassifications_OnServerValidate(object aSource, ServerValidateEventArgs aArgs)
{
CustomValidator cvCheckBoxKinds = aSource as CustomValidator;
int checkedCount = 0;
if (cvCheckBoxKinds != null)
{
CheckBoxList cblClientClassifications = GuiClientClassificationsFind();
foreach (ListItem listItem in cblClientClassifications.Items)
{
if (listItem.Selected)
{
checkedCount++;
}
}
if (checkedCount == 0)
{
aArgs.IsValid = false;
cvCheckBoxKinds.ErrorMessage = "Select client kind.";
}
}
}
The OnServerValidate is firing and I am getting to set the validator to invalid as well as setting the error message (Page.IsValid is also false as expected). However, the error text is not displaying. When I view the page source I see:
<span id="ctl00_cphMainContent_fvData_cfvClientKinds" class="label label-danger" style="display:none;">XXXX</span>
instead of the error message I set as well as the fact that it is not visible.
Has anyone got any pointers here on how to track this down? I have looked at similar questions of SO but none of the comments seem to apply. Is this related to FormView perhaps?
Try your control without the CssClass="label label-danger" bootstrap first, and use the code below to check your boxes:
protected void cfvClientKinds_ServerValidate(object aSource, ServerValidateEventArgs aArgs)
{
aArgs.IsValid = cblClientClassifications.SelectedItem != null;
cfvClientKinds.ErrorMessage = "Hey! this is a new message";
}
and I guess you call this line before you fire the above event:
protected void btnValidate_Click(object sender, EventArgs e)
{
Page.Validate();
}
In Short, I think that your problem is either related to your way of finding cblClientClassifications checkBoxList or other code that you haven't stated above.
CheckBoxList cblClientClassifications = GuiClientClassificationsFind();
I decided to try out your case and created a new webform added formview and bind it to northwind categories table then inside edititemtemplate I added a checkboxlist and populated it manually. added CustomValidator double clicked it copied your codebehind and it works for me except for the findcontrol part: GuiClientClassificationsFind();
Here is the formview:
<asp:FormView ID="FormView1" runat="server" DataKeyNames="CategoryID" DataSourceID="SqlDataSource1">
<EditItemTemplate>
...
<asp:CheckBoxList ID="cblClientClassifications" runat="server">
<asp:ListItem>Bir</asp:ListItem>
<asp:ListItem>iki</asp:ListItem>
<asp:ListItem>Üç</asp:ListItem>
<asp:ListItem>Dört</asp:ListItem>
</asp:CheckBoxList>
<asp:CustomValidator ID="cfvClientKinds" runat="server" Display="Dynamic" CssClass="label label-danger" ErrorMessage="CustomValidator" OnServerValidate="cfvClientKinds_ServerValidate"></asp:CustomValidator>
<br />
<asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True" CommandName="Update" Text="Update" />
<asp:LinkButton ID="UpdateCancelButton" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel" />
</EditItemTemplate>
</asp:FormView>
And codebehind with your code:
protected void cfvClientKinds_ServerValidate(object aSource, ServerValidateEventArgs aArgs)
{
CustomValidator cvCheckBoxKinds = aSource as CustomValidator;
CheckBoxList cblClientClassifications = (CheckBoxList)FormView1.FindControl("cblClientClassifications");
int checkedCount = 0;
if (cvCheckBoxKinds != null)
{
foreach (ListItem listItem in cblClientClassifications.Items)
{
if (listItem.Selected)
{
checkedCount++;
}
}
if (checkedCount == 0)
{
aArgs.IsValid = false;
cvCheckBoxKinds.ErrorMessage = "Select client kind.";
}
}
}
I Ali Shahrokhi's method is shorter and works as well as yours..
protected void cfvClientKinds_ServerValidate(object aSource, ServerValidateEventArgs aArgs)
{
CustomValidator cvCheckBoxKinds = aSource as CustomValidator;
CheckBoxList cblClientClassifications = (CheckBoxList)FormView1.FindControl("cblClientClassifications");
aArgs.IsValid = cblClientClassifications.SelectedItem != null;
cvCheckBoxKinds.ErrorMessage = "Select client kind.";
}
if you check as you entered edititemtemplate in formview you'll see before submitting that your customvalidators span will be there just as you mentioned that's because server hasn't sent it to the client yet somehow.
Related
I'm working on an ASP.NET form based application.
I have a repeater bound to database. It has any of the the following controls per row:
RadioButtonList
TextBox
DropDownList
CheckBoxList
There are one of the following validation controls per row:
RequiredFieldValidator
CustomValidator
I have a button outside the repeater. When I click on save button, the code will loop through each repeater item, read selected data and saves it in database.
The problem I'm facing is as soon as I click on save button, it gives me error:
The ControlToValidate property of 'reqValidator' cannot be blank.
I made sure that repeater is loaded for the first time only and not when the page is posted back.
Also, the code in save button does not seem to be executed. Here is my code:
<cms:CMSUpdatePanel runat="server" ID="updatePanelCampaignQuestions">
<ContentTemplate>
<asp:Repeater ID="repeaterQuestions" runat="server" OnItemDataBound="repeaterQuestions_ItemDataBound">
<ItemTemplate>
<div class="repeater-container">
<asp:Label ID="lbQuestion" runat="server" Text='<%# Eval("Question") %>' />
<asp:Label ID="lbQuestionType" runat="server" Text='<%# Eval("QuestionType") %>' Style="display: inline; visibility: hidden" />
<asp:Label ID="lbAnswers" runat="server" Text='<%# Eval("Answers") %>' Style="display: inline; visibility: hidden" />
<asp:Label ID="lbArticleCampaignQuestionID" runat="server" Text='<%# Eval("ArticleCampaignQuestionID") %>' Style="display: inline; visibility: hidden" />
<div class="row validation-container">
<div class="col-md-12 col-lg-12">
<asp:TextBox ID="txtAnswer" CssClass="form-control" runat="server" TextMode="MultiLine" Rows="2" ValidationGroup="Campaign"></asp:TextBox>
<asp:RadioButtonList ID="rdAnswer" runat="server"></asp:RadioButtonList>
<asp:DropDownList ID="ddnAnswer" runat="server"></asp:DropDownList>
<asp:CheckBoxList ID="chkAnswer" CssClass="chkAnswer" runat="server"></asp:CheckBoxList>
<asp:RequiredFieldValidator ID="reqValidator" runat="server" Display="Dynamic" Style="color: #f00" />
<asp:CustomValidator ID="customValidator" runat="server" ClientValidationFunction="checkAnswer" Display="Dynamic" Style="color: #f00" />
<hr />
</div>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
The code for repeater OnItemDataBound:
protected void repeaterQuestions_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
string questionType = (e.Item.FindControl("lbQuestionType") as Label).Text;
RequiredFieldValidator reqValidator = (RequiredFieldValidator)e.Item.FindControl("reqValidator");
CustomValidator customValidator = (CustomValidator)e.Item.FindControl("customValidator");
if (questionType.ToLower().Equals("text"))
{
e.Item.FindControl("txtAnswer").Visible = true;
e.Item.FindControl("rdAnswer").Visible = false;
e.Item.FindControl("chkAnswer").Visible = false;
e.Item.FindControl("ddnAnswer").Visible = false;
reqValidator.ControlToValidate = e.Item.FindControl("txtAnswer").ID;
reqValidator.ErrorMessage = "Please fill the answer";
e.Item.Controls.Remove(customValidator);
}
else if (questionType.ToLower().Equals("single selection"))
{
e.Item.FindControl("txtAnswer").Visible = false;
e.Item.FindControl("rdAnswer").Visible = true;
e.Item.FindControl("chkAnswer").Visible = false;
e.Item.FindControl("ddnAnswer").Visible = false;
string strAnswers = (e.Item.FindControl("lbAnswers") as Label).Text;
string[] answers = strAnswers.Split(new[] { "##" }, StringSplitOptions.None);
foreach(string answer in answers)
{
(e.Item.FindControl("rdAnswer") as RadioButtonList).Items.Add(answer);
}
reqValidator.ControlToValidate = e.Item.FindControl("rdAnswer").ID;
reqValidator.ErrorMessage = "Please select one";
e.Item.Controls.Remove(customValidator);
}
else if (questionType.ToLower().Equals("drop down"))
{
e.Item.FindControl("txtAnswer").Visible = false;
e.Item.FindControl("rdAnswer").Visible = false;
e.Item.FindControl("chkAnswer").Visible = false;
e.Item.FindControl("ddnAnswer").Visible = true;
string strAnswers = (e.Item.FindControl("lbAnswers") as Label).Text;
string[] answers = strAnswers.Split(new[] { "##" }, StringSplitOptions.None);
(e.Item.FindControl("ddnAnswer") as DropDownList).Items.Add(new ListItem("- Please Select -", "0"));
foreach (string answer in answers)
{
(e.Item.FindControl("ddnAnswer") as DropDownList).Items.Add(answer);
}
reqValidator.InitialValue = "0";
reqValidator.ControlToValidate = e.Item.FindControl("ddnAnswer").ID;
reqValidator.ErrorMessage = "Please select one";
e.Item.Controls.Remove(customValidator);
}
else if (questionType.ToLower().Equals("multiple selection"))
{
e.Item.FindControl("txtAnswer").Visible = false;
e.Item.FindControl("rdAnswer").Visible = false;
e.Item.FindControl("chkAnswer").Visible = true;
e.Item.FindControl("ddnAnswer").Visible = false;
string strAnswers = (e.Item.FindControl("lbAnswers") as Label).Text;
string[] answers = strAnswers.Split(new[] { "##" }, StringSplitOptions.None);
foreach (string answer in answers)
{
(e.Item.FindControl("chkAnswer") as CheckBoxList).Items.Add(answer);
}
e.Item.Controls.Remove(reqValidator);
customValidator.ErrorMessage = "Please select at least one";
}
}
}
The code for save button:
private void SaveAnswer()
{
int userID = GetUserID();
int campaignID = GetCampaignID();
foreach (RepeaterItem item in repeaterQuestions.Items)
{
string answer = "";
string questionType = (item.FindControl("lbQuestionType") as Label).Text;
int articleCampaignQuestionID = int.Parse((item.FindControl("lbArticleCampaignQuestionID") as Label).Text);
if (questionType.ToLower().Equals("text"))
{
answer = (item.FindControl("txtAnswer") as TextBox).Text;
}
else if (questionType.ToLower().Equals("single selection"))
{
answer = (item.FindControl("rdAnswer") as RadioButtonList).SelectedItem.Text;
}
else if (questionType.ToLower().Equals("drop down"))
{
answer = (item.FindControl("ddnAnswer") as DropDownList).SelectedItem.Text;
}
else if (questionType.ToLower().Equals("multiple selection"))
{
CheckBoxList answerList = (item.FindControl("chkAnswer") as CheckBoxList);
foreach (ListItem checkItem in answerList.Items)
{
if (checkItem.Selected)
{
answer += checkItem.Text + "##";
}
}
if (answer.EndsWith("##"))
answer = answer.Substring(0, answer.Length - 2);
}
// save value of answer to database
}
I'm stuck on this for a very long time now. There is no other exception on the page other than the one mentioned above.
Edit
What is the flow of page postback?
Click on btnSaveAnswer , code for button executes , repeater is reloaded
Or
Click on btnSaveAnswer, repeater is reloaded , code for button executes
If I put repeater binding with:
if(!Page.IsPostBack)
I get the required field validator error
and
if I don't use above if, then I cannot read values from controls in repeater
I figured out the problem in my code. Here is what I did:
Since my repeater is being built dynamically, I'm binding repeater every time and not using Page.IsPostBack
Instead of binding repeater in Page_Load, I'm binding in Page_Init
This fixed my issue
I have added an extra step to my uzerwizard
<asp:TemplatedWizardStep id="stpPayment" runat="server" Title="Payment">
<ContentTemplate>
<asp:DropDownList ID="cmbSubs" runat="server" ClientIDMode="Static"
Width="200px">
<asp:ListItem Value="month">Monthly Subscription</asp:ListItem>
<asp:ListItem Value="year">Annual Subscription</asp:ListItem>
</asp:DropDownList>
i am successfully navigating to the new step
protected void NewUserprofileWizard_NextButtonClick(object sender, WizardNavigationEventArgs e)
{
if (NewUserprofileWizard.ActiveStepIndex == 0)
{
NewUserprofileWizard.ActiveStepIndex = 1;
}
}
but I cant get access to the dropdownlist from my codebehind
note: i can get a handle onto the controls in the 1st (createuser) step.
but any controls in the next step always return a null.
this is the code i am using
DropDownList cmb = (DropDownList)NewUserprofileWizard.WizardSteps[1].FindControl("cmbSubs");
i always return a null.
note that this works just fine
TextBox tmp = (TextBox)NewUserprofileWizard.CreateUserStep.ContentTemplateContainer.FindControl("Email");
userProfile.AccountEmail = tmp.Text;
problem seems unique to custom steps
Thanks for the help
Tried Gregors suggestion. no luck. mine always comes up as null.
if thsi helps any:
my wizard is inside a user control..
the page that uses the user control is inside a master page.....
Here is little sample I have created for you, first aspx code:
<asp:CreateUserWizard ID="CreateUserWizard1" runat="server" OnNextButtonClick="CreateUserWizard1_NextButtonClick">
<WizardSteps>
<asp:WizardStep runat="server" Title="My Custom Step">
<asp:DropDownList ID="cmbSubs" runat="server" ClientIDMode="Static"
Width="200px">
<asp:ListItem Value="month">Monthly Subscription</asp:ListItem>
<asp:ListItem Value="year">Annual Subscription</asp:ListItem>
</asp:DropDownList>
</asp:WizardStep>
<asp:CreateUserWizardStep runat="server" />
<asp:CompleteWizardStep runat="server" />
</WizardSteps>
</asp:CreateUserWizard>
And now the code to find first dropdown:
protected void CreateUserWizard1_NextButtonClick(object sender, WizardNavigationEventArgs e)
{
if (e.CurrentStepIndex == 0)
{
//get instance to dropdown...
string selectedValue = null;
string controlId = null;
foreach (var item in CreateUserWizard1.WizardSteps[0].Controls)
{
DropDownList ddl = item as DropDownList;
if (ddl != null)
{
selectedValue = ddl.SelectedValue;
controlId = ddl.ClientID;
break;
}
}
}
}
Of course you can also find your dropdown like this:
DropDownList cmbSubs = CreateUserWizard1.WizardSteps[0].FindControl("cmbSubs") as DropDownList;
Happy coding!
it appears that today my google foo was doing much better
because i am in a templateswizardstep, i have to cast the wizardstep into the templatedwizardstep.
from here i can now find the control. whooohoo!
TemplatedWizardStep step = (TemplatedWizardStep)NewUserprofileWizard.WizardSteps[1];
cmb = (DropDownList)step.ContentTemplateContainer.FindControl("cmbSubs");
Thanks all for the help
I am experiencing a problem with an ASPX page not executing a CustomValidator. The Page consists of 3 ASP Panels which swap visibility for each step in a 3 step process. The first step/panel functions as expected, executing all CustomValidators when I click the submit button. If valid, the button click hides its panel and shows the second panel for step #2 which contains another CustomValidator. When clicking the submit button on this second panel, the CustomValidator never executes and the Page always reports that it IsValid.
I have reproduced this behavior in a small, example app. Here is the relevant code...
Default.aspx
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<h2>
Welcome to ASP.NET!
</h2>
<p>
To learn more about ASP.NET visit www.asp.net.
</p>
<p>
You can also find <a href="http://go.microsoft.com/fwlink/?LinkID=152368&clcid=0x409"
title="MSDN ASP.NET Docs">documentation on ASP.NET at MSDN</a>.
</p>
<asp:Panel ID="Panel1" runat="server" Visible="true">
<div>
<asp:CustomValidator
ID="CustomValidator1"
runat="server"
ControlToValidate="TextBox1"
ValidateEmptyText="true"
Display="Dynamic"
OnServerValidate="CustomValidator1_ServerValidate">
</asp:CustomValidator>
</div>
<div>
<asp:Label ID="Label1" runat="server" Text="Type in anything:" AssociatedControlID="TextBox1" />
<asp:TextBox ID="TextBox1" runat="server" />
</div>
<div>
<asp:Button ID="Button1" runat="server" Text="Show Panel #2" OnClick="Button1_Click" />
</div>
</asp:Panel>
<asp:Panel ID="Panel2" runat="server" Visible="false">
<div>
<asp:CustomValidator
ID="CustomValidator2"
runat="server"
Display="Dynamic"
OnServerValidate="CustomValidator2_ServerValidate">
</asp:CustomValidator>
</div>
<div>
<asp:Button ID="Button2" runat="server" Text="I should cause an Exception..." OnClick="Button2_Click" />
</div>
</asp:Panel>
<asp:Panel ID="Panel3" runat="server" Visible="false">
<p>An exception should have been thrown. :(</p>
</asp:Panel>
</asp:Content>
Default.aspx.cs
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Panel1.Visible = true;
Panel2.Visible = false;
Panel3.Visible = false;
}
protected void Button1_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
Panel1.Visible = false;
Panel2.Visible = true;
Panel3.Visible = false;
}
}
protected void Button2_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
Panel1.Visible = false;
Panel2.Visible = false;
Panel3.Visible = true;
}
}
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
string userEnteredText = TextBox1.Text;
if (string.IsNullOrEmpty(userEnteredText))
{
CustomValidator1.Text = "Text is required!";
args.IsValid = false;
}
else if (!userEnteredText.ToLower().Equals("anything"))
{
CustomValidator1.Text = "You didn't type 'anything'! ;)";
TextBox1.Text = null;
args.IsValid = false;
}
else
{
args.IsValid = true;
}
}
protected void CustomValidator2_ServerValidate(object source, ServerValidateEventArgs args)
{
throw new Exception("This ServerValidate() method never triggers!");
}
}
I don't understand why the CustomValidator2 method is never executing. Can anyone explain this behaviour?
As you're not setting the ControlToValidate property in your scenario set the property ValidateWhenEmpty to true on the CustomValidator.
The CustomValidator will not be evaluated when the ControlToValidate is blank unless ValidateWhenEmpty is true.
UPDATE:
Ok this was wrong. But do you really need to set visibility of the panels in the Page_Load? You've done it already declaratively in the .aspx.
If you remove it from Page_Load, the validator works. I suppose it does not work if the validator is Visible=false or is inside a containing control that is Visible=false.
You should use ValidationGroup property of the buttons and the corresponding validation controls in each panel.
Here is my template field with 2linkbuttons in a gridview.
How do I hide one of the lnkbuttons depending on the user selection
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<table>
<tr>
<td align="center">
<asp:LinkButton ID="LinkButton1" runat="server" CommandName= "Publish" CommandArgument="<%# Container.DataItemIndex %>"></asp:LinkButton>
</td>
<<td align="center">
<asp:LinkButton ID="LinkButton2" runat="server" CommandName= "Block" HeaderText="Block" CommandArgument="<%# Container.DataItemIndex %>">Block</asp:LinkButton>
</td>
</tr>
</table>
</ItemTemplate>
</asp:TemplateField>
protected void GridView1_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if(Status=="Posted")
{
LinkButton lbtn2 = (LinkButton)e.Row.FindControl("LinkButton2");
lbtn2.Visible = false;
}
if(Status=="Publish")
{
LinkButton lbtn1 = (LinkButton)e.Row.FindControl("LinkButton1");
lbtn1.Visible = false;
}
}
I am doing this using 2 linkbuttons in the template field.
Here if the Status == Posted, then hide LinkButton2.
If ItemType == Published, then hide LinkButton1.
I don't mind using only Linkbutton and set the commandName and commandArgument in aspx.cs`
I am getting an error at...
LinkButton lbtn2 = (LinkButton)e.Row.FindControl("LinkButton2");
lbtn2.Visible = false;
Error: Object reference not set to an instance pointing to lnbt2.Visible = false;
Any clues,
Thanks
Sun
Check to be sure that the row in question is a data row, not a header, etc. The issue is probably because the current row is a header or footer, so it doesn't contain your controls and throws an exception.
protected void GridView1_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
if(Status=="Posted")
{
LinkButton lbtn2 = (LinkButton)e.Row.FindControl("LinkButton2");
lbtn2.Visible = false;
}
if(Status=="Publish")
{
LinkButton lbtn1 = (LinkButton)e.Row.FindControl("LinkButton1");
lbtn1.Visible = false;
}
}
}
I know this is old but I was looking for the same thing; I was able to do it this way also and posting just for reference:
This is in a listview but should be same for gridview:
<asp:LinkButton ID="btnForms" runat="server" Text='MyButton' CommandName="MyCommandName"
Style='<%#GetHiddenTag(Eval("Status").ToString())%>' CommandArgument='<%#Eval("Status")%>' OnClick="MyOnClickCodeBehind" />
Codebehind:
public string GetHiddenTag(string Status)
{
if (Status.ToLower() == "completed")
return "visibility:hidden;";
return "visibility:visible;";
}
I have a repeater control and textbox in that repeater. I want a required field validator in the textbox ho can i do this
<asp:Repeater id="myRep" OnItemDataBound="rep_ItemDataBound" runat="server">
<ItemTemplate>
<asp:TextBox id="tx" runat="server" />
<asp:RequiredFieldValidator id="myVal" ControlToValidate="tx" ErrorMessage="Required" runat="server" />
</ItemTemplate>
</asp:Repeater>
UPDATE
Add this to code-behind (also modify the markup a bit to subscribe to an event, see above):
protected void rep_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
RequiredFieldValidator val = (RequiredFieldValidator)e.Item.FindControl("myVal");
TextBox tb = (TextBox)e.Item.FindControl("tx");
val.ControlToValidate = tb.ID;
}
If you want all textboxes in a repeater to be validated by a single button click then thats simple like this
<asp:Repeater ID="rpt" runat="server">
<ItemTemplate>
<asp:TextBox ID="txt" runat="server">
</asp:TextBox>
<asp:RequiredFieldValidator ID="rqf" ControlToValidate="txt"
ErrorMessage="*" ValidationGroup = "TestValidationGroup" runat = "server">
</asp:RequiredFieldValidator>
</ItemTemplate>
</asp:Repeater>
<asp:Button ID = "btnSubmit" runat = "server" ValidationGroup = "TestValidationGroup" />
No need to check for any event for databound or anything.
You can set ControlToValidate value on repeater itemdatabound.
Try this one
<asp:Repeater ID="rptSample" runat="server">
<ItemTemplate>
Name:<br />
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvName" ControlToValidate="txtName" runat="server" Display="Static" ErrorMessage="Name field cannot be left blank"></asp:RequiredFieldValidator>
</ItemTemplate>
</asp:Repeater>
<br />
<asp:Button ID="btnSubmit" Text="Submit" runat="server" />
protected void myRep_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
((RequiredFieldValidator)e.Item.FindControl("myVal")).ValidationGroup = ((TextBox)e.Item.FindControl("tx")).UniqueID;
}
}
protected void Repeater_OnItemDataBound(object sender, RepeaterItemEventArgs e) {
tblData tbldata = e.Item.DataItem as tblData;
RequiredFieldValidator val = (RequiredFieldValidator)e.Item.FindControl("rfv");
if (tbldata.FieldName.ToUpper().Contains("NOT NULL")) {
TextBox tb = (TextBox)e.Item.FindControl("txtDATFieldName");
val.ControlToValidate = tb.ID;
}
else {
val.Enabled = false; // disable when you dont need a validator
}
}
Maybe you want have a validation per row... Set the validation group to a group per row like this
ValidationGroup='<%# "gropname" + Eval("Id") %>'
do this in the validator, textbox and the button
HTH
G.
I kept getting a duplicate key exception in RegisterExpandoAttribute trying to do this.
I was using a UserControl inside a repeater, when "OnDataBinding" instead of "ItemDataBinding"
This worked for me:
/// <summary>
/// Raises the <see cref="E:System.Web.UI.Control.DataBinding" /> event.
/// </summary>
/// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param>
protected override void OnDataBinding(EventArgs e)
{
base.OnDataBinding(e);
foreach (Control ct in this.Controls)
{
BaseValidator bv = ct as BaseValidator;
if (null == bv)
{
continue;
}
bv.ControlToValidate = this.FindControl(bv.ControlToValidate).ID;
bv.ValidationGroup = this.ValidationGroup;
}
}
And yes, I don't think it makes any sense either