Difference between assigning a property and adding a attribute in a asp.net control - asp.net

I am creating ASP.NET textbox controls dynamically. I want to know the difference between assigning the property of the control and adding it as an attribute.
For ex:
I can do:
TextBox txtBox = new TextBox();
txtBox.MaxLength = 100;
or I could do
txtBox.Attributes.Add("maxlength", "100);

The first example is strongly typed, so the compiler will check to make sure that a) MaxLength exists and b) an integer is set for that property.
The second example will work, but the compiler has no way to check to see if the attribute you are adding is correct.

In the end they get translated to the maxlength HTML attribute. TextBox offers a property mostly for convenience.

First one is better because of misspelling or wrong using.
Also first one is more readable.

Related

Dynamically create asp:TextBox that accepts only Numbers

I would like to know if it's possible to create asp.net TextBox from code behind that accepts only numbers. Is there any attribute I can Use?
I have this but If I put "a" it's Ok...
HtmlGenericControl divQta = (HtmlGenericControl)e.Row.FindControl("divQta");
TextBox txtQta = new TextBox();
txtQta.Attributes["type"] = "number";
txtQta.Text = dt.Rows[e.Row.RowIndex][2].ToString();
divQta.Controls.Add(txtQta);
You can set the text box's TextMode property to TextBoxMode.Number:
txtQty.TextMode = TextBoxMode.Number;
See this MSDN page for details.
Note: that enum value is only available since .NET 4.5. And since it makes use of a HTML 5 feature, it might not work in all (older) browsers.

How can I access custom Textbox attributes in ASP.Net?

I am using/abusing CSS classes and custom html attributes to provide default data to a set of textboxes. The code-front for this looks like the following (with some supporting javascript to handle checking/setting the default data when the field is blank):
<asp:TextBox ID="TXT_LenderName" class='defaultText' data-default='Institution Name' runat="server"></asp:TextBox>
This works.
I am working on the code-behind to process this form. I would like to be able to compare the value of the TXT_LenderName.Text to the value of the data-default attribute, but I haven't been able to find a way to get the value of a custom html attribute. Suggestions?
This is tested and worked
string customAttrDataDefault = TXT_LenderName.Attributes["data-default"];
txtpassword.Attributes.Add("value","Password value");
try this:
TXT_LenderName.Attributes["AttributeName"]= value;//here get or set the value.
If the control, like the TextBox control inherits from the System.Web.UI.WebControls.Control class then it should have an Attributes property which is a name value pair collection of the control's attributes.

ASP.NET dynamic controls and validators - Unable to find control id '...' referenced by the 'ControlToValidate' property of '...'

I have seem many forum posts / responses on this subject but I am no closer to a solution.
I am loading a repeating data structure from the DB into UpdatePanel controls in an event handler. The number of repeats varies so controls are all created and added to a container panel dynamically. The user has the ability to edit the data so I am also dynamically creating validator controls (RegularExpressionValidators)
The problem is in setting the ControlToValidate property of the validator. No matter how I set this I get the Unable to find control id '...' referenced by the 'ControlToValidate' property of '...' error response from the server which is then raised by ASP.NET AJAX JS.
The short version of the control adding code looks like this:
TextBox licenseCode = new TextBox();
licenseCode.ID = this.getNextId(); // generated ID contains only [A-Za-Z], [0-9], :, -, .
licenseCode.MaxLength = 50;
this.purchaseEdit.Controls.Add(licenseCode); // this.purchaseEdit is an asp:Panel
RegularExpressionValidator licenseCodeVal = new RegularExpressionValidator();
licenseCodeVal.ControlToValidate = licenseCode.ClientID;
licenseCodeVal.ID = this.getNextId();
licenseCodeVal.ValidationGroup = this.purchaseEditSave.ValidationGroup; // save button within the panel
licenseCodeVal.ValidationExpression = #"^.{1," + licenseCode.MaxLength.ToString() + "}$";
licenseCodeVal.ErrorMessage = "Between 1 and " + licenseCode.MaxLength.ToString() + " chars.";
this.purchaseEdit.Controls.Add(licenseCodeVal);
As you can see both controls are added to the same container, the validator is added after the TextBox, and the ControlToValidate property is currently set to the ClientID of the TextBox. I have tried the ID value too but no joy.
The really irritating thing is that if I don't add the validator, and using a breakpoint inspect the ClientID of the TextBox, I can inspect the DOM of the updated page and find the ID attribute of the TextBox:
<input type="text" id="ctl00_ContentBody_PCTL::4890cc3a-8d07-4dee-aa9f-bdd8735fcaf8::licCode"... />
As far as I can tell I'm not doing anything wrong, so why am I getting this error??
Any suggestions much appreciated.
You should not use the ClientID but the ID of the TextBox.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.basevalidator.controltovalidate.aspx
"I have tried the ID value too but no joy."
But you didn't get an exception and only the validation didn't work?!
My suggestion is to wrap the control and the validator in an UserControl and add this dynamically to your container-control. On this way you can use fix ID's because they all have distinct NamingContainers.
The code will be cleaner. Encapsulation also increases reusability.
ARGH so I finally figured this thing out - it came down to special characters in the ID. I was having an issue with a JQuery selector which contained ':' and figured I should just check if that was causing the validator issues - it was.
In the end I created my GUIDs without any hyphens and replaced ':' with '_' and the problem went away. This question helped.
I haven't seen anything from MSDN saying certain characters are not permitted in IDs, but then I tend to refer to MSDN with specific problems after jumping in, so maybe there is something on there.. See comment below

How to conditionally make a DetailsView field read-only?

Say I have a DetailsView with a bunch of fields, and I want only certain kinds of users to edit a few of them. They're too few to split them into another DetailsView, so what I'm thinking is to find some way to only allow a user to edit them based on some code-behind logic, effectively making them read-only at will.
I feel it's important to mention that the fields are both TemplateFields, not normal BoundFields with ReadOnly properties.
Any ideas? For some reason the required functions don't jump at me from reading the documentation.
Oh and I need eveyone to see their specific values, I just want to restrict edit access to them.
Hrm apparently it was as simple as setting the EditItemTemplate property of the fields in question to null. Seems to be working fine so far!
Edit: A short code sample showing how I did it:
foreach (DataControlField field in dvDRDetails.Fields)
if (!fieldstoignore.Contains(field.HeaderText))
if (field is TemplateField)
((TemplateField)field).EditItemTemplate = null;
else if (field is BoundField)
((BoundField)field).ReadOnly = true;
Where fieldstoignore is an array of field headers that I always have set as editable. The rest fall in two categories: TemplateField that require the hack I discussed above and BoundField that have a ReadOnly property I can set.

Custom ListView to show EmptyDataTemplate and InsertItemTemplate at the same time

It is known that the ListView control can't display both an EmptyDataTemplate and a InsertItemTemplate at the same time.
For my design style I need to be able to show both. I want to be able to show that no data exist and at the same time show a form to add new data.
I've already implemented various solutions, such as putting a PlaceHolder in my LayoutTemplate and then manually showing or hiding this PlaceHolder in the code-behind, depending on if there is data or not.
However, I would like a control that has this built-in capability in order to keep my code-behind light.
I believe there are only two ways to achieve what I want:
First way (preferred) is to write that custom control myself. I was thinking of deriving from ListView and overriding the function responsible for disabling the EmptyDataTemplate, but I have no experience with custom controls. And I'm not even sure it will work in the end.
Second way is to use a custom control found or purchased somewhere. I have not been able to find such control that has the same base capabilities as the ListView.
Has anybody any idea how to solve #1 and maybe #2?
Thank you.
Here is what I ended up doing:
public class MyListView : ListView
{
protected override int CreateChildControls(IEnumerable dataSource, bool dataBinding)
{
int itemCount = base.CreateChildControls(dataSource, dataBinding);
if (this.InsertItemPosition != InsertItemPosition.None && itemCount == 0)
{
CreateEmptyDataItem();
}
return itemCount;
}
}
Works great!
I would go for your option 1: Create a custom control
Because you haven't specified a programming language I made one in VB.NET:
Public Class CustomListView
Inherits ListView
Public Sub CheckEmptyData() Handles Me.PreRender
If Me.Items.Count = 0 Then
Dim label As New Label
label.Text = "No data found <br/>"
Me.Controls.AddAt(0, label)
End If
End Sub
End Class
Just tested it and works perfectly, it can just replace an existing ListView.
As you can see it checks if there is any data and if not it inserts a label with the text "No data found". I haven't found an easy way to use the EmptyDataTemplate for this, that would be a better option but this might already work for you.
Another option is to hide the InsertItem (InsertItemPosition.None) if there is no data, and add a Button "Insert" to the EmptyDataTemplate that enables the InsertItemTemplate and therefore hides the EmptyDataTemplate.
I don't understand much of your requirement without a screen shot of what you are actually trying to achieve. Anyway, you may be able to achieve this interface with a combination of ListView+FormView or ListView+ a User Control. If you can provide any more info I may help further.

Resources