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
Related
I am using ASP.NET, I have a dropdownlist inside of a grid (radGrid).
What I like to happen is that when the dropdownlist appears, I like it to default to
"Please Select" only if the field that it is binding to is blank. Else, I like to to get the value from the DataSource.
I have the following code:
<asp:DropDownList ID="ddlEroGroup" runat="server" DataSourceID="EroGroupSource" DataTextField="Value" DataValueField="Value" AppendDataBoundItems="true" OnDataBound=" erogroupDropDown_DataBound" Text='<%# Bind("EroGroup") %>'>
</asp:DropDownList>
For the DataSource here is the code:
<asp:SqlDataSource ID="EroGroupSource" runat="server" ConnectionString="<%$ ConnectionStrings:ISQL %>"
SelectCommand="Select Value from LookupValues where Category = 'EroGroup'">
</asp:SqlDataSource>
Here is the code in the code-behind:
protected void ErogroupDropDown_DataBound(object sender, EventArgs e)
{
DropDownList list = sender as DropDownList;
if (list != null)
{
list.Items.Insert(0, new ListItem("Please Select", ""));
}
}
When it does the Binding, if the value is blank, I get an error saying that it could not find the value.
try:
protected void ErogroupDropDown_DataBound(object sender, EventArgs e)
{
DropDownList list = sender as DropDownList;
if (list.Items.Count.equals(0))
{
list.Items.Insert(0, new ListItem("Please Select", ""));
}
}
Use Grid PreRender event for this. May you would need to assign the value to some hidden label and access it inside prerender method and assign it to the dropdown.
<ItemTemplate>
<asp:Label runat="server" ID="lblValue" Text='<%# Eval("YourValue")%>' Visible="false" />
<asp:DropDownList ID="ddlEroGroup" runat="server" DataSourceID="EroGroupSource" DataTextField="Value" DataValueField="Value" AppendDataBoundItems="true" OnDataBound=" erogroupDropDown_DataBound" Text='<%# Bind("EroGroup") %>'>
</asp:DropDownList>
<asp:SqlDataSource ID="EroGroupSource" runat="server" ConnectionString="<%$ ConnectionStrings:ISQL %>"
SelectCommand="Select Value from LookupValues where Category = 'EroGroup'">
</asp:SqlDataSource>
</ItemTemplate>
On code behind:
protected void GridView1_PreRender(object sender, EventArgs e)
{
for(int i=0;i<Gridview1.Rows.Count;i++)
{
Label lblValue = (Label)Gridview1.Row[i].FindControl('lblValue');
DropdownList ddl = (DropdownList) Gridview1.Row[i].FindControl('ddlEroGroup');
ddl.Items.Insert(0, new ListItem("Please Select", ""));
if(lblValue!=null && !String.IsNullOrEmpty(lblValue.Text))
ddl.SelectedValue = lblValue.Text;
}
}
At the beginning I have to say that I tried to find the answer... And yes I'm new in ASP.Net world :)
I would like to use DropDownList in an EditItemTemplate field in GridView. I found I cannot set parametr SelectedValue. It's missing. When I try to set it in code behind it seems to ddlEditPermissions doesn't exists.
<asp:TemplateField HeaderText="opravneni" SortExpression="opravneni">
<edititemtemplate>
<asp:DropDownList ID="ddlEditPermissions" runat="server" DataSource='<%# getPermissions() %>' OnPreRender="ddlEditPermissions_PreRender"/>
</edititemtemplate>
<insertitemtemplate>
<asp:TextBox ID="tbEditPermissions" runat="server" Text='<%# Bind("opravneni") %>'></asp:TextBox>
</insertitemtemplate>
<itemtemplate>
<asp:Label ID="lEditPermissions" runat="server" Text='<%# Bind("opravneni") %>'></asp:Label>
</itemtemplate>
I'm really confused. Could anyone advise me?
You can use RowDataBound of the GridView which gets triggered for every GridViewRow after it was constructed and databound:
protected void gridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowState == DataControlRowState.Edit)
{
var ddlEditPermissions = (DropDownList)e.Row.FindControl("ddlEditPermissions");
// bind DropDown manually
ddlEditPermissions.DataSource = getPermissions();
ddlEditPermissions.DataTextField = "Permission_Name"; // presumed text-column
ddlEditPermissions.DataValueField = "Permission_ID"; // presumed id-column
ddlEditPermissions.DataBind();
DataRowView dr = e.Row.DataItem as DataRowView; // you might need to change this type, use the debugger then to determine it
ddlEditPermissions.SelectedValue = dr["Permission_ID"].ToString(); // presumed foreign-key-column
}
}
<asp:repeater id="rpt" run="server">
<ItemTemplate>
<asp:LinkButton id="Delete" runat="server" OnCommand="Delete_Command"></asp:linkButton>
<asp:label id="lblMessage" run="server">
</ItemTemplate>
</asp:repeater>
Code Behind:
protected void Delete_Command(object sender, CommandEventArgument e)
{
}
how i get the reference to the "lblMessage" in Delete_Command.
Try this:
protected void Delete_Command(object sender, CommandEventArgs e)
{
LinkButton button = (LinkButton)sender;
Label label = (Label)button.NamingContainer.FindControl("lblMessage");
// do something with the label
}
If you:
Have bound the repeater
Have ViewState enabled
Do not re-bind the repeater earlier in the post back
this should work. If not, please verify that the id of the label is indeed exactly the same as in the ...FindControl("lblMessage");. Also make sure that runat="server" is set on all the controls involved.
Edit: One more thing to check: Search the markup file (the .aspx file) and check if there are any other controls that also use the same event in the code behind. If another control is using the same event handler and that control is not in the repeater, the label will not be found.
means are you want find a lable in Delete_Command event?
in aspx
<asp:Repeater ID="rpt" runat="server">
<ItemTemplate>
<asp:LinkButton ID="Delete" runat="server" OnCommand="Delete_Command"></asp:LinkButton>
<asp:Label ID="lblMessage" run="server">
</ItemTemplate>
</asp:Repeater>
in aspx.cs
protected void Delete_Command(object sender, CommandEventArgs e)
{
foreach (RepeaterItem item in rpt.Items)
{
Label lblMessage = item.FindControl("lblMessage") as Label;
if (lblMessage != null)
{
lblMessage.Text = "";
}
}
}
If You want to make it in your way use following code in
protected void Repeater1_ItemCommand(object source, CommandEventArgs e)
{
(((LinkButton)source).NamingContainer).FindControl("lblName")
}
Another approach.. But something that you can buy
aspx
<asp:Repeater ID="Repeater1" runat="server"
onitemcommand="Repeater1_ItemCommand">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%=Eval("Name") %>' ></asp:Label>
<asp:LinkButton runat="server" CommandName="Delete_Command" Text="sd"></asp:LinkButton>
</ItemTemplate>
</asp:Repeater>
.cs
protected void Delete_Command(object sender, CommandEventArgument e)
{
if(e.CommandName != null)// Conditional Check
{
Label label = e.Item.FindControl("lblMessage");
// do something with the label
}
}
i am trying 2 make a quiz in asp.net.
the mcq choices r displayed using radio buttons. in code behind, when i try 2 check if radiobutton is checked, d code under that if statement does not execute.
aspx code:
<ItemTemplate>
<asp:Literal ID="Literal1" runat="server" Text='<%#Eval("ques") %>'></asp:Literal><br />
<asp:RadioButton GroupName="a" ID="RadioButton1" Text='<%#Eval("ch1") %>' runat="server" /><br />
<asp:RadioButton GroupName="a" ID="RadioButton2" Text='<%#Eval("ch2") %>' runat="server" /><br />
<asp:RadioButton GroupName="a" ID="RadioButton3" Text='<%#Eval("ch3") %>' runat="server" /><br />
<asp:RadioButton GroupName="a" ID="RadioButton4" Text='<%#Eval("ch4") %>' runat="server" /><br />
<asp:Label ID="Label1" runat="server" Text='<%#Eval("ans") %>' Visible="false"></asp:Label><br />
<asp:Label ID="Label3" runat="server" Text="Label"></asp:Label><br />
</ItemTemplate>
code behind:
protected void Button1_Click(object sender, EventArgs e)
{
int count = 0;
foreach(RepeaterItem Items in Repeater1.Items)
{
RadioButton r1 = (RadioButton)Items.FindControl("RadioButton1");
RadioButton r2 = (RadioButton)Items.FindControl("RadioButton2");
RadioButton r3 = (RadioButton)Items.FindControl("RadioButton3");
RadioButton r4 = (RadioButton)Items.FindControl("RadioButton4");
Label l3 = (Label)Items.FindControl("Label3");
Label l=(Label)Items.FindControl("Label1");
l3.Text = "hello?";
if (r1.Checked)
{
if(r1.Text==l.Text)
count++;
}
else
{
if (r2.Checked)
{
if(r2.Text==l.Text)
count++;
}
}
// and so on for all 4 options
}
Label2.Visible = true;
Label2.Text = "your score is " + count; //always zero!
}
If you're stepping through the debugger, and your line
if(r1.Text==l.Text)
count++;
isn't executing, then I would guess that the line if (r1.Checked) is evaluating to false.
On your Page_Load() method for this page, are there any databindings or manipulation of these radio buttons? If so, unless you wrap them in a if(!Page.IsPostBack){ ... } conditional then it will wipe out whatever the user did to the radio button, hence r1.Checked would be false.
I hope that might help :) Good luck.
You'll need to do the following:
Set the AutoPostBack on the radio button control to true.
Set the OnItemCommand on the repeater control to "Button1_Click"
Change the signature of the Button1_Click method to protected void Button1_Click(object sender, RepeaterCommandEventArgs e)
That will at least trigger the method in your code behind.
I wanted to disable asp.net validation server controls from browser. I checked online but did not find any way to disable the server side validation; it can be disabled only on the client side using JS/jQuery.
Here is the scenario: I have a checkbox and selecting which displays a set of text boxes. Only if the checkbox is checked, required field validator should fire for the text boxes. I don't want to call a postback on checkbox. Actually those chceck boxes will be generated with jQuery templating so postback is not an option to enable disable validtion.
I would like to know whether there is any way we can enable disable the .CausesValidation property for the controls from browser using some setting? Or is there a way to capture the controls which are to be considered for validation slectively in some event before page_load?
[Update]
Based on Accepted answer, here is my solution:
<form id="form1" runat="server">
<div>
<asp:TextBox ID="textbox1" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="req1" ControlToValidate="textbox1" runat="server"
ErrorMessage="enter text"></asp:RequiredFieldValidator>
<asp:TextBox ID="textbox2" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="req2" ControlToValidate="textbox2" runat="server"
ErrorMessage="enter text for 2"></asp:RequiredFieldValidator>
<asp:CheckBox ID="check1" runat="server" Text="choose" />
<asp:Button ID="submitBtn" runat="server" OnClick="submitBtn_Click" Text="submit" />
<asp:CustomValidator ID="cvBox" runat="server" ErrorMessage="Error" ValidationGroup="prueba"
OnServerValidate="Validarcaja"></asp:CustomValidator>
<asp:ValidationSummary ID="summary" runat="server" />
</div>
</form>
protected void Page_Load(object sender, EventArgs e)
{
req1.Enabled = false;
req2.Enabled = false;
}
protected void submitBtn_Click(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
Page.Validate();
if (Page.IsValid)
{
Response.Write("valid form");
}
else
{
Response.Write("invalid form");
}
}
}
protected void Validarcaja(object source, ServerValidateEventArgs args)
{
if (check1.Checked)
{
req1.Enabled = true;
req1.Validate();
}
}
The solution for me would be to use a CustomValidator with a OnServerValidate method.
In the OnServerValidate method I would check if the checkbox is checked, in that case I would verify if the textboxes are filled. It is not necessary to do any change in the CausesValidation property.
The only condition is not to include the property "ControlToValidate". A CustomValidator does not fire if the textbox is empty that's why.
So the code would be like this:
<asp:ValidationSummary ID="vs" runat="server" ValidationGroup="prueba" />
<asp:CheckBox ID="chb" runat="server" Text="Check" />
<asp:TextBox ID="txbBox" runat="server"></asp:TextBox>
<asp:CustomValidator ID="cvBox" runat="server" ErrorMessage="Error" ValidationGroup="prueba"
OnServerValidate="Validarcaja"></asp:CustomValidator>
<asp:Button ID="btn" runat="server" Text="Prueba" />
And the codebehind:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
Page.Validate();
}
}
protected void Validarcaja(object source, ServerValidateEventArgs args)
{
if (chb.Checked)
{
if (txbBox.Text == String.Empty)
{
cvBox.IsValid = false;
}
}
}