Require TextBox depending on RadioButtonList selection in Repeater - c#

I have a repeater with a RadioButtonList and TextBox inside. I want the TextBox to be required only if the RadioButtonList has a value of 1 or 2. How can I achieve this?
I thought I could initially enable the RFV on a selected index change but it can't see the items since it is within a repeater. Do I need to do this within the ItemDataBound?
<asp:Repeater ID="repeaterSurvey" runat="server">
<ItemTemplate>
<div class="form-group">
<asp:Label ID="labelQuestion" runat="server" Text='<%# Eval("Question")%>' />
<asp:RequiredFieldValidator ID="RFV1" CssClass="required" runat="server"
ErrorMessage="Required" Display="Dynamic" ControlToValidate="surveyList" />
<asp:RadioButtonList RepeatDirection="Horizontal" ID="surveyList" AutoPostBack="true"
OnSelectedIndexChanged="surveyList_SelectedIndexChanged" runat="server">
<asp:ListItem Value="1">Strongly Disagree</asp:ListItem>
<asp:ListItem Value="2">Disagree</asp:ListItem>
<asp:ListItem Value="3">Agree</asp:ListItem>
<asp:ListItem Value="4">Strongly Agree</asp:ListItem>
<asp:ListItem Value="0">N/A</asp:ListItem>
</asp:RadioButtonList>
<asp:HiddenField ID="hiddenfieldID" Value='<%# Eval("ID")%>' runat="server" />
<asp:TextBox ID="textboxComment" Placeholder="Comments" CssClass="form-control" TextMode="MultiLine"
Rows="3" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RFV2" Enabled="false" CssClass="required" runat="server"
ErrorMessage="Comment Required" Display="Dynamic" ControlToValidate="textboxComment" />
</div>
</ItemTemplate>
</asp:Repeater>
Codebehind
protected void surveyList_SelectedIndexChanged(object sender, System.EventArgs e)
{
if (surveyList.SelectedValue == "1" || surveyList.SelectedValue == "2")
{
RFV2.Enabled = true;
}
else
{
RFV2.Enabled = false;
}
}

With the help of the comment section (stephen.vakil) I was able to create a solution to my problem:
protected void surveyList_SelectedIndexChanged(object sender, System.EventArgs e)
{
RadioButtonList surveyList = (RadioButtonList)sender;
string value = surveyList.SelectedValue;
RepeaterItem row = (RepeaterItem)surveyList.NamingContainer;
if (value == "1" || value == "2")
{
((RequiredFieldValidator)row.FindControl("RFV2")).Enabled = true;
}
else
{
((RequiredFieldValidator)row.FindControl("RFV2")).Enabled = false;
}
}

Related

server side custom validator in asp.net,when discount applicable dropdown is "yes" then textbox should be manditory,else textbox is not manditory

server side custom validator in asp.net,when discount applicable dropdown is "yes" then textbox should be manditory,else textbox is not manditory
HTML
<td>
<asp:DropDownList ID="ddlDiscountApplicable" runat="server" CssClass="wd150">
<asp:ListItem Text="--Select--" Value="0"></asp:ListItem>
<asp:ListItem Text="Yes" Value="Yes"></asp:ListItem>
<asp:ListItem Text="No" Value="No"></asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator10" runat="server" ErrorMessage="Select Discount Applicable"
ControlToValidate="ddlDiscountApplicable" InitialValue="0" Display="Dynamic" ValidationGroup="NameValidator"
ForeColor="Red">*</asp:RequiredFieldValidator>
</td>
</tr>
<tr id="DiscountRow" style="display:none">
<td style="width:170px" runat="server" id="labelDiscount">
Discount
</td>
<td runat="server" id="TextboxDiscount">
<asp:TextBox ID="DiscountText" runat="server" CssClass="wt150"></asp:TextBox>
<asp:CustomValidator runat="server" id="cusCustom" controltovalidate="DiscountText" onservervalidate="checkDiscountApplicable" errormessage="Enter Discount" />
</td>
code behind
protected void checkDiscountApplicable(object sender, ServerValidateEventArgs e){
var discount = ddlDiscountApplicable.SelectedValue;
var validData = true;
var val = e.Value;
if (discount == "Yes")
{
if (val == null || val == "")
{
validData = false;
}
}
else
{
e.IsValid = true;
}
if (validData)
e.IsValid = true;
else
e.IsValid = false;
}

If condition for required field validation

I have a DropDownList and a TextBox in c#.net. If DropDownList value is "No" then some value must enter in TextBox. If dropdownlist value is yes then required field validator is not needed for that TextBox. How to make it possible?
<asp:DropDownList ID="dropdownlist1" runat="server"
CssClass="NormalText" Width="155px" AutoPostBack="true"
onselectedindexchanged="ddls_SelectedIndexChanged">
<asp:ListItem Selected="True" Value=""></asp:ListItem>
<asp:ListItem Value="Yes">Yes</asp:ListItem>
<asp:ListItem Value="No">No</asp:ListItem>
</asp:DropDownList>
<br />
<br />
<asp:TextBox ID="Textbox1" runat="server" CausesValidation="True"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="Textbox1" ErrorMessage="Explanation needed If you select NO">
</asp:RequiredFieldValidator>
</td>
protected void dropdownlist1_SelectedIndexChanged(object sender, EventArgs e)
{
}
Use this code for conditional validation:
protected void dropdownlist1_SelectedIndexChanged(object sender, EventArgs e)
{
if(dropdownlist1.SelectedValue == "No")
{
RequiredFieldValidator1.Enabled = true;
}
else if(dropdownlist1.SelectedValue == "Yes")
{
RequiredFieldValidator1.Enabled = false;
}
}
Optionally, you may also have to set Submit Button Validation group:
ButtonSubmit.ValidationGroup = string.Empty;
when field validator is not enabled.

Disable RequiredFieldValidator in asp.net c#

I am trying to disable a RequiredFieldValidator by radio button list value. I have it coded but it doesn't seems to be working.
What i have done so far:
protected void radioButtonList(object sender, EventArgs e)
{
if (((RadioButtonList)dvInsertPromotion.FindControl("RadioButtonList2")).SelectedValue == "Y")
{
((RequiredFieldValidator)dvInsertPromotion.FindControl("rfvdate1")).Enabled = false;
((RequiredFieldValidator)dvInsertPromotion.FindControl("rfvdate")).Enabled = false;
this.addPromotion.Show();
}
else
{
((RequiredFieldValidator)dvInsertPromotion.FindControl("rfvdate1")).Enabled = true;
((RequiredFieldValidator)dvInsertPromotion.FindControl("rfvdate")).Enabled = true;
this.addPromotion.Show();
}
}
html:
<asp:RadioButtonList ID="RadioButtonList2" runat="server" ValidationGroup="addValidationGp" OnSelectedIndexChanged="radioButtonList">
<asp:ListItem Text="Yes" Value="Y"></asp:ListItem>
<asp:ListItem Text="No" Value="N" Selected></asp:ListItem>
</asp:RadioButtonList>
<asp:TextBox ID="txtPubDate" Width="75" MaxLength="10" runat="server" AutoPostBack="true" OnTextChanged="insertStartEndDateTime_SelectedIndexChanged"/>
<asp:CalendarExtender ID="CalendarExtender1" runat="server" TargetControlID="txtPubDate"
PopupPosition="Right" Format="dd/MM/yyyy" />
<asp:RequiredFieldValidator ID="rfvdate" ValidationGroup="addValidationGp" runat="server"
ControlToValidate="txtPubDate" ErrorMessage="*" Display="Dynamic" Enabled="true"
SetFocusOnError="true" /><br />
I've had the same problem in the past and the only way I was able to solve this was by making the validators invisible altogether:
((RequiredFieldValidator)dvInsertPromotion.FindControl("rfvdate1")).Visible = false;
Just don't forget to set them to visible again whenever you want to enable them.

Set id for multiple radio buttons list generated by a repeater

Is there a way to set the ID for multiple radiobuttonlists generated via repeater.
ie. ID= rep1 rep2 rep3 rep4
I would like to be able to place my data in multiple columns across a table.
Heres is my code so far:
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<h2><%: Title %></h2>
<h3>Your application description page.</h3>
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1">
<ItemTemplate>
<asp:Label ID="lblQuestion" runat="server" Text='<%# Eval("Text") %>' />
<asp:RadioButtonList ID="ddlAnswer" runat="server" AutoPostBack="True" RepeatDirection="Horizontal">
<asp:ListItem Text="Yes" Value="True" />
<asp:ListItem Text="No" Value="False" />
</asp:RadioButtonList>
<asp:Panel ID="Panel1" runat="server">
<asp:Label ID="Label1" runat="server" Text="Provide more details:"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</asp:Panel>
</p>
</ItemTemplate>
</asp:Repeater>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:DefaultConnection %>" SelectCommand="SELECT [Text] FROM [Questions]"></asp:SqlDataSource>
Behind:
protected void Page_Load(object sender, EventArgs e)
{
foreach (RepeaterItem item in Repeater1.Items)
{
RadioButtonList ddlAnswer = item.FindControl("ddlAnswer") as RadioButtonList;
System.Web.UI.WebControls.Panel Panel1 = item.FindControl("Panel1") as System.Web.UI.WebControls.Panel;
if (ddlAnswer.SelectedValue == "False")
{
Panel1.Visible = true;
}
else
{
Panel1.Visible = false;
}
}
}
You can just use ClientIdMode="Predictable" attribute in the aspx mark-up to assign different ids to different dropdownlists like this:
<asp:RadioButtonList ClientIDMode="Predictable" ID="ddlAnswer" runat="server" AutoPostBack="True" RepeatDirection="Horizontal"> ...

Button onClick does not fire in GridView inside of TemplateField

I'm trying to write a code that would update only one record for the data.
I do not need to be able to update every field on the row, only one particular field.
I have page that defines a GridView as following:
<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
<UpdatePanel>
<ContentTemplate>
<fieldset style="width: 1%">
<legend>Search Customer</legend>
<table>
<tr>
<td>
<asp:DropDownList id="ddlSearchOption"
AutoPostBack="True"
OnSelectedIndexChanged="ddlSearchOption_SelectedIndexChanged"
runat="server">
<asp:ListItem Selected="True" Value="SearchBy"> Search By </asp:ListItem>
<asp:ListItem Value="CustID"> Customer ID </asp:ListItem>
<asp:ListItem Value="CustFirst"> First Name </asp:ListItem>
<asp:ListItem Value="CustLast"> Last Name </asp:ListItem>
<asp:ListItem Value="CustCity"> City </asp:ListItem>
</asp:DropDownList>
</td>
<asp:Panel id="pnlCustSearch" runat="server" >
<td>
<asp:Label id="lblEntry" runat="server" Text="" width="120px"></asp:Label>
</td>
<td>
<asp:TextBox id="txtSearchOptions" runat="server" width="50px">Hello</asp:TextBox>
</td>
<td>
<asp:Button id="btnFind" Text="Search" runat="server" onClick="btnFind_Click"></asp:Button>
</td>
</asp:Panel>
</tr>
</table>
</fieldset>
<div id ="msg">
<asp:Label id="lblMsg" runat="server" Text=""></asp:Label>
</div>
<div id="gridShow">
<asp:GridView ID="GridView1" runat="server" GridLines="None" AutoGenerateColumns="false"
AlternatingRowStyle-BackColor="#EEEEEE" EditRowStyle-BorderColor="Red">
<Columns>
<asp:TemplateField Visible="true" HeaderText="Customer ID">
<ItemTemplate>
<asp:Label runat="server" ID="lblCustID" Text='<%#Eval("CustID")%>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="First Name">
<ItemTemplate>
<asp:Label runat="server" ID="lblFirstName" Text='<%#Eval("CustFirstName") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Name">
<ItemTemplate>
<asp:Label runat="server" ID="lblLastName" Text='<%#Eval("CustLastName") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="City">
<ItemTemplate>
<asp:Label runat="server" ID="lblCity" Text='<%#Eval("CustCity") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Email">
<ItemTemplate>
<asp:TextBox runat="server" ID="txtEmail" Text='<%#Eval("CustEmail") %>' />
<asp:Button runat="server" ID="btnUpdate" Text="Update" onClick="GridView1_btnUpdate_Click"/>
<asp:RequiredFieldValidator runat="server" ID="rfdCountry" ControlToValidate="txtEmail"
ValidationGroup="var1" ErrorMessage="*" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</ContentTemplate>
</UpdatePanel>
</asp:Content>
Then in codebehind I write the following:
protected void GridView1_btnUpdate_Click(Object sender, EventArgs e)
{
//Code goes here
}
When clicking button to update email nothing happens.
What am I doing wrong?
I tried to use one of suggestions here:
if (!IsPostBack)
{
GridView1.DataSource = App_Data.DataHandler.GetData("fname", "de");
GridView1.DataBind();
GridView1.Visible = true;
}
The data is displayed but the click event does not work anyway
I added the following to my GridView definition:
onrowcommand="GridView1_RowCommand"
and added the code suggested:
<asp:Button runat="server" ID="btnUpdate" Text="Update" CommandName="UpdateEmail"
CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"/>
In my .cs file I added the following:
protected void GridView1_RowCommand(Object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "UpdateEmail")
{
//Get the index from the argument
int index = Convert.ToInt32(e.CommandArgument);
//Get the row
GridViewRow row = GridView1.Rows[index];
//Do whatever you need with your row here!
}
}
Still, click event does not fire.
Ok, here is my code behind .cs file:
public partial class index : System.Web.UI.Page
{
protected override object LoadPageStateFromPersistenceMedium()
{
return Session["__VIEWSTATE"];
}
protected override void SavePageStateToPersistenceMedium(object viewState)
{
Session["VIEWSTATE"] = viewState;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
Reset();
else
lblMsg.Text = "";
}
protected void Reset()
{
pnlCustSearch.Visible = false;
GridView1.Visible = false;
lblMsg.Text = "";
}
protected void ddlSearchOption_SelectedIndexChanged(object sender, EventArgs e)
{
Reset();
String ddlSelected = ddlSearchOption.SelectedValue;
if (ddlSelected != "")
{
ViewState["ddlSelected"] = ddlSelected;
pnlCustSearch.Visible = true;
SelectLabel(ddlSelected);
}
}
protected void SelectLabel(String choice)
{
switch (choice)
{
case "CustID":
lblEntry.Text = "Enter Customer ID";
break;
case "CustFirst":
lblEntry.Text = "Enter First Name";
break;
case "CustLast":
lblEntry.Text = "Enter Last Name";
break;
case "CustCity":
lblEntry.Text = "Enter City";
break;
default:
lblEntry.Text = "Enter Customer ID";
break;
}
}
protected void btnFind_Click(object sender, EventArgs e)
{
GridView1.Visible = true;
String option = (String)ViewState["ddlSelected"];
String input = txtSearchOptions.Text.Trim();
GridView1.DataSource = DataHandler.GetData(option,input);
GridView1.DataBind();
GridView1.Visible = true;
}
protected void GridView1_RowCommand(Object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "UpdateEmail")
{
//Get the index from the argument
int index = Convert.ToInt32(e.CommandArgument);
//Get the row
GridViewRow row = GridView1.Rows[index];
//Do whatever you need with your row here!
}
}
protected void btnUpdate_Click(Object sender, EventArgs e)
{
String txt = null;
txt = "here";
}
}
When you try to handle events from GridView, you need to use a CommandName and a CommandArgument then handle the RowCommand event from the GridView.
See http://msdn.microsoft.com/... for reference.
ASP.Net page should look like :
<asp:ButtonField runat="server" ID="btnUpdate" Text="Update"
CommandName="UpdateEmail"
CommandArgument="<%# CType(Container,GridViewRow).RowIndex %>" />
In the RowCommand event :
if (e.CommandName == "UpdateEmail")
{
//Get the index from the argument
int index = Convert.ToInt32(e.CommandArgument);
//Get the row
GridViewRow row = GridView1.Rows[index];
//Do whatever you need with your row here!
}
I got it, finally. I had to change <asp:Button/> to
`<asp:ButtonField Text="Update Email" CommandName="UpdateEmail"`
and remove it from ItemTemplate.
But why this was a problem. What I wanted to do is just to display textfield in the same itemtemplate with button?
Actually, the answer was much easier then I thought originally. I just used different values to set session: __VIEWSTATE and VIEWSTATE
protected override object LoadPageStateFromPersistenceMedium()
{
return Session["__VIEWSTATE"];
}
protected override void SavePageStateToPersistenceMedium(object viewState)
{
Session["VIEWSTATE"] = viewState;
}
As soon as I changed it, button was able to fire events.
Thank you

Categories