Convert a string to value of control - asp.net

I have a string str = "txtName.Text" (txtName is name of textbox control)
How to display value of textbox without is value of string str (use C#)
Let me a solution.
Thanks a lot !

Probably the easiest thing to do would be to extract the control id like this:
String controlId = str.Substring(0, str.IndexOf('.'));
Then use the Page.FindControl method to find the control and cast that as an ITextControl so that you can get the Text property value:
ITextControl textControl
= this.FindControl(controlId) as ITextControl;
if (textControl != null)
{
// you found a control that has a Text property
}

I assume that the question is: How to get value of textbox control given its ID as a string.
Use FindControl method.
Example:
TextBox myTextBox = FindControl("txtName") as TextBox;
if (myTextBox != null)
{
Response.Write("Value of the text box is: " + myTextBox.Text);
}
else
{
Response.Write("Control not found");
}

If by "value" you mean "numeric value", then you can't - text boxes contain strings only. What you can do is get the string like you did, and parse that string into a number.
You can use int.Parse() or double.Parse() (depending on the type), or TryParse() for a safer implementation.

Related

Property to check whether a row in grid view has been modified

Is there a simple property or method to check whether a row changed or column value has been changed in my grid view. I also want to get the index of modified/changed row
You can add it to the gridview like this
<asp:GridView Name="gridview1" OnRowUpdating="GridViewUpdateEventHandler" />
If I remember correctly there is an abundance of tutorials for gridviews and how to manipulate data.
No, there is no simple property for that. But...
Here is a method for that on MSDN
You'll have to modify it for your data and your control names to verify, but it's all there, straight from the keyboard of Microsoft.
protected bool IsRowModified(GridViewRow r)
{
int currentID;
string currentLastName;
string currentFirstName;
currentID = Convert.ToInt32(GridView1.DataKeys[r.RowIndex].Value);
currentLastName = ((TextBox)r.FindControl("LastNameTextBox")).Text;
currentFirstName = ((TextBox)r.FindControl("FirstNameTextBox")).Text;
System.Data.DataRow row =
originalDataTable.Select(String.Format("EmployeeID = {0}", currentID))[0];
if (!currentLastName.Equals(row["LastName"].ToString())) { return true; }
if (!currentFirstName.Equals(row["FirstName"].ToString())) { return true; }
return false;
}

Basic server control

I'm looking at server controls for the first time, and I've a question about this code:
[Bindable(true)]
[Category("Appearance")]
[DefaultValue("")]
[Localizable(true)]
public string Text
{
get
{
String s = (String)ViewState["Text"];
return ((s == null) ? "[" + this.ID + "]" : s);
}
set
{
ViewState["Text"] = value;
}
}
I do not understand why this control returns the [id] or the text that is set. I do not see how this makes any sense. Is this just for demonstration or is there a reason for returning the id?
Thanks
It looks like an example that will show the controls ID if the controls .Text property has not been set.
This is a bit of a "debug" procedure to show that the control is actually rendering even though it hasn't got any data set in it's Text property.
Makes no sense to me. If I'm asking for text, then I expect if there is no text to get either an empty string or null.
If there's nothing been set for the Text property, in ViewState with other words, then this.ID gets returned.
There's not really a meaning for it but it'll show some text in the Property pane of Visual Studio and on the designer.

Dynamic data asp.net Query String parameter

Is there a way to define my own querystring parameter in Dynamic data rather then using something like
Edit.aspx?AccountID=1
I want to use something like this
Edit.aspx?id=1
I found a solution for this problem
I simply added this on the pageload method of my edit page template
string id = String.Empty;
if(Request.QueryString["id"] != null ){
id = Request.QueryString["id"].ToString();
DetailsDataSource.WhereParameters.Clear();
DetailsDataSource.WhereParameters.Add("AccountID", DbType.Int32, id);
}

How can I rewrite the ErrorMessage for a CustomValidator control on the client?

I have a CustomValidator that is validating a telephone number for several different telephone numbering schemes. The client-side javascript looks like this:
validatePhoneNumber(sender, args) {
cleanNumber = args.Value.replace(/\D/, "");
country = $("#" + CountryID).get(0).value;
switch (country) {
case "North America":
args.IsValid = validateNAPhoneNumber(cleanNumber);
if (!args.IsValid) sender.errormessage = "* Not a NA Phone #";
break;
case "UK":
args.IsValid = validateUKPhoneNumber(cleanumber);
if (!args.IsValid) sender.errormessage = "* Not a UK Phone #";
break;
...
}
}
The actual validation takes place properly, and the CustomValidator has the correct IsValid property at all times. The sender.errormessage, however, seems to be rewritten just after this function call to it's default value. How can I change the errormessage value, and make it "stick"?
function dateofbirth(sender, args) {
var dtcDOB = document.getElementById('<%= dtcDOB.ClientID %>');
var dob = new Date(dtcDOB.value);
var currDate = new Date();
if (dtcDOB.value == "") {
args.IsValid = false;
sender.textContent = "Provide DOB.";
return;
}
args.IsValid = true;
}
Try sender.textContent = "your err msg".
It worked for me.
The best way to change the error message of a validator control with image is:
sender.innerHTML = "YOUR HTML WITH ANYTHING COME HERE"
To change the error message, do it like this:
if (!args.IsValid) document.getElementById('<%= cstPhoneNumber.ClientID %>').errormessage = "* Not a NA Phone #";
To change the text, do this:
if (!args.IsValid) document.getElementById('<%= cstPhoneNumber.ClientID %>').innerHTML = "* Not a NA Phone #";
cstPhoneNumber should be replaced by the name of your validation control.
It looks like your using jquery so you could set the error message like this:
$(sender).text("* Not a NA Phone #");
Edit:
Sorry for the delay but I was away on vacation.
I was playing a round with a simple page and I think I understand how this works.
When you set the errormessage on the sender in the client side validation function you are setting the equivalent of the ErrorMessage property.
This is different from the Text property. The ErrorMessage sets the text displayed in the Validation summary, while the Text property is the text displayed in the validator control. Note that if you only set the ErrorMessage property (on the server) then the ErrorMessage will be copied into the Text property.
What this means is that when you set sender.errormessage your actually setting the text that is displayed in the validation summary.
Hopefully this will help clear it up. However, I still haven't seen a way to change the Text property from the client side validation function. I am also not sure why your sender object is not the validator object.
sender.innerText = "Your message" will work.
I think the problem is that there is no 'errormessage' property on the client side. The custom validator renders a <span> tag to display the error message with an id corresponding the id property of the custom validator control. To set the text displayed when validation fails you need to do somthing like this.
...
case "North America":
args.IsValid = validateNAPhoneNumber(cleanNumber);
if (!args.IsValid)
document.getElementById(sender.id).innerText = "* Not a NA Phone #";
break;
...
Just remove all instances of Text and ErrorMessage in the custom validator tag definitions
then use
$(#id_of_custom_validation_control).text("custom error message");
Then with this, you can use one custom validator control and handle multiple error conditions
E.g
if(error1){
$(#id_of_custom_validation_control).text("custom error message1");
}else $(#id_of_custom_validation_control).text("custom error message2");
Hope this helps
Expanding #Andy response, using jQuery:
Change the text message (show in the form):
$('#<%=this.[Validator].ClientID%>').text('Text to show');
Change the error message (for the Summary control):
$('#<%=this.[Validator].ClientID%>').attr('errormessage', 'Text to show');
Replace [Validator] for your validator's name.
Try this...
Use sender.textContext in the Javascript for the error message and setup your CustomValidator as such:
<asp:CustomValidator ID="cvdPhoneNumber" runat="server" Display="Dynamic" ForeColor="Red" ControlToValidate="txtPhoneNumber" ClientValidationFunction="validatePhoneNumber" ErrorMessage="" />

How to create an ASP.NET custom control with a dash in the name?

I want to set up an ASP.NET custom control such that it has a custom name, specifically, with a hyphen within it, so it might look like this in markup:
<rp:do-something runat="server" id="doSomething1" />
I don't mind if this syntax requires setting up a tag mapping in web.config or something to that effect, but the tagMapping element doesn't quite match up for what I'd like to do.
I wouldn't think this is possible due to the restrictions on class namings. I don't believe you can refer to a control class in markup without refering to it by name
Is there a specific reason you need the hyphen?
John, you're right. I did some searching in Reflector and it looks like it doesn't get there:
Type ITagNameToTypeMapper.GetControlType(string tagName, IDictionary attribs)
{
string str;
string str2 = this._nsRegisterEntry.Namespace;
if (string.IsNullOrEmpty(str2))
{
str = tagName;
}
else
{
str = str2 + "." + tagName;
}
if (this._assembly != null)
{
Type type = null;
try
{
type = this._assembly.GetType(str, true, true);
}
Implemented in System.Web.UI.NamespaceTagNameToTypeMapper, System.Web.
#Jonathan: I have a specific business reason for wanting to do it this way. Oh well.

Resources