I want to validate a textbox, so that the Text value of firstNameTextBox differed from nicknameTextBox. I'm using InitialValue property of RequiredFieldValidator, like this -
fieldValidatorInitialValue.InitialValue = firstNameTextBox.Text;
Here is the code:
RequiredFieldValidator fieldValidatorInitialValue = new RequiredFieldValidator();
TextBox firstNameTextBox = new TextBox();
TextBox nicknameTextBox = new TextBox();
protected void Page_Load(object sender, EventArgs e)
{
Button submitButton = new Button();
submitButton.CausesValidation = true;
submitButton.Click += submitButton_Click;
nicknameTextBox.ID = "nickname";
firstNameTextBox.ID = "firstname";
fieldValidatorInitialValue.ControlToValidate = firstNameTextBox.ID;
}
protected void submitButton_Click(object sender, EventArgs e)
{
fieldValidatorInitialValue.InitialValue = nicknameTextBox.Text;
}
However, using this code the validation doesn't work correctly, only after the second click on button. I also tried to put all of the RequiredFieldValidator code to submitButton_Click event handler, however it doesn't work at all in this case, could someone please help me with it?
Try this.you should use CompareValidator instead of RequiredFieldValidator, with Operator="NotEqual"
<asp:CompareValidator runat="server"
ControlToValidate="tbFName"
ControlToCompare="tbLName"
Type="String"
Operator="NotEqual"
ErrorMessage="First and last name cannot be the same" />
Try below code
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
Button submitButton = new Button();
submitButton.CausesValidation = true;
submitButton.Click += submitButton_Click;
nicknameTextBox.ID = "nickname";
firstNameTextBox.ID = "firstname";
fieldValidatorInitialValue.ControlToValidate = firstNameTextBox.ID;
}
}
I think the way you are trying to compare "First name" and "Nick
Name" is unnecessarily complex.
Instead of that you can simply use CompareValidator and achieve the same task on single button click. Here , Add this on your
designer page:
<asp:CompareValidator ID="comNames" runat="server"
ControlToValidate="firstNameTextBox"
ControlToCompare="nicknameTextBox"
ErrorMessage="Error: Name cant be same"
SetFocusOnError="True" Text="*"></asp:CompareValidator>
In case you want to add Validator dynamically, Add CompareValidator
instead of RequiredFieldValidator and add following properties:
ControlToValidate="firstNameTextBox"
ControlToCompare="nicknameTextBox"
ErrorMessage="Error: Name cant be same"
SetFocusOnError="True"
Text="*"
Note: if you are using ValidationGroup for button,use same name of
ValidationGroup for Validator also.
Related
I'm doing a page navigation control. After typing a new number in text box and Enter,
void pageNoTextBox_TextChanged(object sender, EventArgs e)
The above event is called.But I am still getting the old text from the text box in the following statement
newPageNumber = Int32.Parse(pageNoTextBox.Text.Trim());
for example if the textbox had 1 and and I entered 12, what I am getting is 1 in the TextChanged event where as javascript returns new value.
<asp:TextBox ReadOnly="false" CssClass="txtfld_s" ForeColor="white" ID="pageNoTextBox" runat="server" Text="" AutoPostBack="true" CausesValidation="True" OnTextChanged="pageNoTextBox_TextChanged"></asp:TextBox>
This is the text box. Is there any way to get the newly entered text using C#?
Well I think this will do the thing you want.
private void pageNoTextBox_TextChanged(object sender, EventArgs e)
{
TextBox textbox = sender as TextBox;
if(textbox != null)
{
string theText = textbox.Text;
}
}
I have a page with many radio buttons. Can I check if any one of these radio buttons is checked ? and then change the text of that checked radio button ?
I'm using asp.net c# 3.5
I'm using
RadioButton ff = new RadioButton();
RadioButton ff2 = new RadioButton();
RadioButton ff3 = new RadioButton();
RadioButton ff4 = new RadioButton();
in a for loop to create many radio buttons
You can run loop on all the radio button on your page by using jquery on type="radio"
and find checked radio button and change text of that radio button.
Try this code:
$('input[type="radio"]').each(function(){
if($(this).is(':checked')) { $(this).html("yourname") }
});
Assuming that you're using an asp:RadioButton, then one method is to set the AutoPostBack property of the RadioButton to true.
Then in a handler on the server side you can change the text.
Evidently this has a cost.
e.g.
<asp:RadioButton ID="ctrlRadioButton" runat="server" AutoPostBack="True"
oncheckedchanged="ctrlRadioButton_CheckedChanged" Text="Select this" />
Then in your code class
protected void ctrlRadioButton_CheckedChanged(object sender, EventArgs e)
{
ctrlRadioButton.Text = "New Text";
}
Update:
If you create the RadioButtons dynamically:
protected void Page_Init(object sender, EventArgs e)
{
for (int i = 0; i < 4; ++i)
{
RadioButton rb = new RadioButton() { AutoPostBack = true, Text = "Initial text" };
rb.CheckedChanged += RadioButton_CheckedChanged;
Form.Controls.Add(rb); // Or add to a panel if you prefer
}
}
and the handler is
protected void RadioButton_CheckedChanged(object sender, EventArgs e)
{
RadioButton rb = (RadioButton)sender;
rb.Text = "New Text";
}
I have a text box and a RadComboBox like this :
<asp:TextBox ID="txt_inner_emp_num" runat="server" Width="60px"
ontextchanged="txt_inner_emp_num_TextChanged" AutoPostBack="true"></asp:TextBox>
<telerik:RadComboBox ID="rad_ddl_inner_emp_name" runat="server" CausesValidation="False"
CollapseDelay="0" Culture="ar-EG" ExpandDelay="0" Filter="Contains" ItemsPerRequest="100"
MarkFirstMatch="true" Width="380px" EnableAutomaticLoadOnDemand="True" EmptyMessage="-emp name-" ShowMoreResultsBox="True" AutoPostBack="True">
</telerik:RadComboBox>
According to the Telerik Documentation
Set a data source to the RadComboBox. Use either DataSourceID or the
DataSource property to do this and set the DataTextField and
DataValueField properties to the respective fields in the data source.
(Note that when using DataSource you must set the property on each
postback, most conveniently in Page_Init.) Set
EnableAutomaticLoadOnDemand to true.
protected void BindEmployees()
{
rad_ddl_inner_emp_name.Items.Clear();
rad_ddl_inner_emp_name.DataSource = Utilities.GetAllEmployees();
rad_ddl_inner_emp_name.DataTextField = "name";
rad_ddl_inner_emp_name.DataValueField = "emp_num";
rad_ddl_inner_emp_name.DataBind();
}
protected void Page_Init(object sender, EventArgs e)
{
BindEmployees();
}
protected void txt_inner_emp_num_TextChanged(object sender, EventArgs e)
{
rad_ddl_inner_emp_name.ClearSelection();
rad_ddl_inner_emp_name.Items.FindItemByValue(txt_inner_emp_num.Text.TrimEnd()).Selected = true;//Get exception here Object reference not set to an instance of an object.
}
I find rad_ddl_inner_emp_name.Items.Count = 0 !! before set the selection ! How to fix this problem ?
As I'm sure you aware of by now, the radcombox typeahead functionality searches text via client side interaction and not by value, which is why you can't find the values.
What I would suggest is having a secondary object to search by emp_num (assuming that's the value that will always be entered into the textbox).
For example, create a global variable:
private Dictionary<string, string> Emp_Dict = new Dictionary<string, string>();
Then populate this dictionary when you do your binding. The following code assumes an ienumerable type being returned. If not you may have to populate the dictionary differently. Also, for this to work, you have to include (System.Linq).
var dataSource = Utilities.GetAllEmployees();
Emp_Dict = dataSource.ToDictionary(ex => ex.emp_num, ex => ex.name);
rad_ddl_inner_emp_name.Items.Clear();
rad_ddl_inner_emp_name.DataSource = dataSource;
rad_ddl_inner_emp_name.DataTextField = "name";
rad_ddl_inner_emp_name.DataValueField = "emp_num";
rad_ddl_inner_emp_name.DataBind();
So now we need to use the dictionary on the text changed event.
protected void txt_inner_emp_num_TextChanged(object sender, EventArgs e)
{
rad_ddl_inner_emp_name.ClearSelection();
if (Emp_Dict.ContainsKey(txt_inner_emp_num.Text.TrimEnd()))
{
rad_ddl_inner_emp_name.SelectedValue = txt_inner_emp_num.Text.TrimEnd();
rad_ddl_inner_emp_name.Text = Emp_Dict[txt_inner_emp_num.Text.TrimEnd()];
}
}
Now when the text changes in the text box, the radcombobox will update when a valid emp_num is entered into the textbox.
The Problem is that the Items only get loaded when you request them!
Set
EnableAutomaticLoadOnDemand="False"
and it will work!
UPDATE:
if you want to use LoadOnDemand set these two Properties and delete the EnableAutomicLoadOnDemand!
EnableLoadOnDemand="True"
EnableItemCaching="True"
UPDATE 2:
Enable ItemCaching isn´t necessary, but it doesn´t hurt!
You do not need to bind data to RadComboBox on every postback unless you disable the view state.
Filter, MarkFirstMatch and EnableAutomaticLoadOnDemand are not useful in your case as you are loading all employees by yourself.
LoadOnDemand basically is when user starts typing inside ComboBox, ComboBox fires ItemsRequested event and retrieves data via ajax.
<asp:TextBox ID="txt_inner_emp_num" runat="server" Width="60px"
ontextchanged="txt_inner_emp_num_TextChanged" AutoPostBack="true" />
<telerik:RadComboBox ID="rad_ddl_inner_emp_name" runat="server"
CausesValidation="False" Culture="ar-EG">
</telerik:RadComboBox>
protected void Page_Init(object sender, EventArgs e)
{
if (!IsPostBack)
{
rad_ddl_inner_emp_name.DataSource = Utilities.GetAllEmployees();
rad_ddl_inner_emp_name.DataTextField = "name";
rad_ddl_inner_emp_name.DataValueField = "emp_num";
rad_ddl_inner_emp_name.DataBind();
}
}
protected void txt_inner_emp_num_TextChanged(object sender, EventArgs e)
{
string value = txt_inner_emp_num.Text;
if(!string.IsNullOrWhiteSpace(value))
{
value = value.Trim();
if (rad_ddl_inner_emp_name.Items
.FindItemByValue(txt_inner_emp_num.Text.Trim()) != null)
rad_ddl_inner_emp_name.SelectedValue = value;
}
}
Since you don't have any item in rad_ddl_inner_emp_name.Items you can set txt_inner_emp_num.Text as selected in ddl.
First check if rad_ddl_inner_emp_name.Items count > 0 then set desired text selected. Or you can check if rad_ddl_inner_emp_name.Items.FindItemByValue(txt_inner_emp_num.Text.TrimEnd()) is not null.
I have a gridview add a link button "Edit":
<asp:LinkButton ID="btnViewDetails" runat="server" text="Edit" CommandName="Select"></asp:LinkButton>
and
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
using (var dataContext = new NewsStandAloneDataContext(Config.StandaloneNewsConnectionString))
{
DetailsView1.ChangeMode(DetailsViewMode.Edit);
DetailsView1.Visible = true;
var dataList =
dataContext.sp_Name(Convert.ToInt32(GridView1.SelectedValue), Value1);
ScriptManager.RegisterStartupScript(this, GetType(), "show1", "openEditWindow();", true);
DetailsView1.DataSource = dataList;
DetailsView1.DataBind();
}
}
But my details view does not show anything.
Looking at your code you have two different methods in play. In your ViewDetails button you are referencing a command name and argument. In your other block of code you are responding to the changing of the selected row. Two different concepts.
You would want to show the details view from the "ItemCommand" event, and not the selectedindexchanged event.
I have to set a LinkButton's OnClientClick attribute but I don't know what this value is until the LinkButton is bound to. I'm trying to set the value when the repeater binds, but I can't workout how to get the 'boundItem/dataContext' value...
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<asp:LinkButton Text="HelloWorld" ID="Hyper1" runat="server" OnDataBinding="Repeater1_DataBinding" >
</asp:LinkButton>
</ItemTemplate>
</asp:Repeater>
protected void Page_Load(object sender, EventArgs e)
{
var list = new List<TestObject>();
list.Add(new TestObject() {TestValue = "testing1"});
list.Add(new TestObject() { TestValue = "testing2" });
list.Add(new TestObject() { TestValue = "testing3" });
this.Repeater1.DataSource = list;
this.Repeater1.DataBind();
}
public void Repeater1_DataBinding(object sender, EventArgs e)
{
var link = sender as HyperLink;
//link.DataItem ???
}
Is there anyway to find out what the current rows bound item is?
Maybe you need to use ItemDataBound event. It provides RepeaterItemEventArgs argument which has DataItem available
this.Repeater1.ItemDataBound += Repeater1_ItemDataBound;
void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
var dataItem = e.Item.DataItem;
}
I assume you are trying to get the value for the row that is currently being databound?
You can change your function to:
public void Repeater1_DataBinding(object sender, EventArgs e)
{
var link = sender as HyperLink;
string valueYouWant = Eval("TestValue").ToString();
// You could then assign the HyperLink control to whatever you need
link.Target = string.Format("yourpage.aspx?id={0}", valueYouWant);
}
valueYouWant now has the value of the field TestValue for the current row that is being databound. Using the DataBinding event is the best way to do this compared to the ItemDataBound because you don't have to search for a control and localize the code specifically to a control instead of a whole template.
The MSDN library had this as a sample event handler:
public void BindData(object sender, EventArgs e)
{
Literal l = (Literal) sender;
DataGridItem container = (DataGridItem) l.NamingContainer;
l.Text = ((DataRowView) container.DataItem)[column].ToString();
}
(see http://msdn.microsoft.com/en-us/library/system.web.ui.control.databinding.aspx)
As you can see it is a simple demonstration of how to access the data item and get data from it. Adapting this to your scenario is an exercise left to the reader. :)