pass control the value of input - asp.net

Perhaps the topic name was chosen incorrectly, I will try to formulate my question. Is it possible to pass to the control an input value that has id = "dateToWork". Tried something like this
<CTR:datePickerKolibri3 ID="KolibriDatePicker1" runat="server" InToField="dateArrival" DayAfter=<% $(#dateToWork).val()%>/>

Hi to do what you want i think, me i create a usercontrol with the control and i add properties.
In your case i do that :
Create a new usercontrol
Add inside
In UserControl.ascx.designer set datePickerKolibri3 to public
Add in code behind of the USerControl :
Private p_datetowork As String
Public Property Datetowork As String
Get
Return p_datetowork
End Get
Set(value As String)
p_datetowork = value
End Set
End Property
And put your UserControl in the page you want and you can pass and access to the properties Datetowork
<CTR:UserControl ID="myUserControl" runat="server" Datetowork="my_date" >
or in Code behind :
myUserControl.Datetowork = "my_date"
If i underdstand your problem :D

Related

Get Hidden Field in Code Behind

I have been looking at answers here and other places but so far have not found exactly how to do this.
I have the following definition for a hidden field in my .aspx page:
<asp:HiddenField ID="hfAddressChange" runat="server" />
I set the value in a javascript function on the client:
function confirmAddressChange()
{
if (typeof document.forms[0].hfAddressChange.valueOf ==="undefined")
{
var res = (confirm('"Update Contact Addresses to Rich?"')==true);
document.forms[0].hfAddressChange.valueOf = res;
}
}
Basically I only want to set the value once.
Now I want to check the value in the code behind:
If hfAddressChange.Value <> String.Empty Then
Dim x As String = "Do Something here"
End If
However, even though I have verified that the value IS being set in the js function, it is always an empty string when it gets to my code behind.
Anyone see what the heck I'm doing wrong?
document.forms[0].hfAddressChange.valueOf = res;
The property is value, not valueOf. (And it won't be undefined earlier, either; just check !document.forms[0].hfAddressChange.value.)

In ASP.NET, trying to find the assigned visibility value of a control that may be inside an invisible container

I am trying to find out whether a particular control on an asp.net page has had it's "Visible" property assign to true or false. The problem is that the visible property crawl up the list of parents and if any of them show as invisible, the queried control will also show as invisible. I need to know what the control itself has been set to.
I did some searching and found the post How to get the set/real value of the Visible property in Asp.Net which offered the following solution
public static bool LocalVisible(this Control control){
var flags = typeof (Control)
.GetField("flags", BindingFlags.Instance | BindingFlags.NonPublic)
.GetValue(control);
return ! (bool) flags.GetType()
.GetProperty("Item", BindingFlags.Instance | BindingFlags.NonPublic)
.GetValue(flags, new object[] {0x10});
}
But when I tried it, it returned an "Ambiguous Match Found" error on GetProperty.
Can someone point out what I'm doing wrong, or show another way of getting what I want?
I had the same problem (two years later). This is the answer that I just wrote in the topic that you refer to:
In case someone tries to get Jørn Schou-Rode's code working in VB.NET, here is the code that works for me. When I simply translate his code in VB, I get an "Ambiguous match found" exception, because there are 3 flavors of the flags "Item" property.
<Extension()>
Public Function GetLocalVisible(ctl As Control) As Boolean
Dim flags As Object = GetType(Control).GetField("flags", BindingFlags.Instance Or BindingFlags.NonPublic).GetValue(ctl)
Dim infos As PropertyInfo() = flags.GetType().GetProperties(BindingFlags.Instance Or BindingFlags.NonPublic)
For Each info As PropertyInfo In infos
If info.Name = "Item" AndAlso info.PropertyType.Name = "Boolean" Then
Return Not CBool(info.GetValue(flags, New Object() {&H10}))
End If
Next
Return ctl.Visible
End Function

Css the feedback label red or green depending on the outcome

I'm CSSing my project and would like to customize the font color for the feedback label. My project is built in 3 layers (DAL, BLL, normal page). In the BLL I catch exceptions and I guess this is where I would add the CSS stylesheet reference. Unfortunately, I can't get it to work, this is what it looks like.
BLL
Public Function deleteCustByCustID(ByVal CustID As Integer) As Boolean
If dataCust.DeleteCust(Cust) Then
Throw New Exception("The customer was removed.")
Return True
Else
Throw New Exception("The customer wasn't removed. Please try again.")
Return False
End If
End Function
ASPX.vb page
Try
bllCust.deleteCustByCustID(CustID)
Catch ex As Exception
lblFeedback.Text = ex.Message
End Try
I have my CSS pages stored in a CSS folder. I would like to assign the font color lime to a success and the font color red to a failure.
Any help is much appreciated!
Another option: if you have assigned an ID value to the markup for your "feedback" area, and if you added a runat="server" to that element, you can access the CssClass property in your code-behind file.
By way of example:
Markup
<div id="Feedback" runat="server"></div>
Code
Me.Feedback.CssClass="error"
Then you can use the CSS rules denoted by #rockerest in his answer.
EDIT:
Okay, I looked at your code again, and I see a big problem: you should NEVER use exceptions as a method of controlling program flow. That is probably error #1.
A not-too-uncommon method of returning a more meaningful result from your methods is to encapsulate a result object. Here is a simple example:
Public Class Result
Public IsValid As Boolean
Public Message As String
Public Sub New(ByVal isValid As Boolean, ByVal message As String )
IsValid = isValid
Message = message
End Sub
End Class
You would amend your current function to return a Result object instead of Boolean, and assign the values of the Result object depending on your query results:
Public Function deleteCustByCustID(ByVal CustID As Integer) As Result
Dim result as New Result
If dataCust.DeleteCust(Cust) Then
result = new Result( true, "The customer was removed." )
Else
result = new Result( false, "The customer wasn't removed. Please try again." )
EndIf
Return result
End Function
Then, in whatever code calls the deleteCustByCustID method, you assign the Message property to the content of the feedback area and the CssClass that matches the IsValid state.
Make sense?
EDIT 2:
Okay, assuming you have a CSS class for errors, ".error" and a CSS class for, uh, not errors, ".success". Then, let's pretend the following snippet was inside an event handler or somesuchthing:
Dim result As new Result = deleteCustByCustID( 42 )
Now you have a Result object that has a IsValid state value (it will be either true or false) and a Message string value. Your next step is to apply the message to the feedback element's (I'll assume here that you use an ASP.NET Label control) Text property, and then, based on the value of result.IsValid, assign the correct class to the label's CssClass property:
myFeedbackLabel.Text = result.Message
If result.IsValid Then
myFeedbackLabel.CssClass = "success"
Else
myFeedbackLabel.CssClass = "error"
EndIf
HTH.
The best answer here would be to define two classes in your main stylesheet like so:
.okay{
color: lime;
}
.error{
color: red;
}
And then simply set the correct variable in your BLL: "okay" for the first part of your if statement, and "error" for the else part. In the page, just use that variable as part of the class definition for the message:
Try
bllCust.deleteCustByCustID(CustID)
Catch ex As Exception
lblFeedback.Text = ex.Message
lblFeedback.cssClass = lblFeedback.cssClass + " " + [THE VARIABLE WORD HERE]
End Try
This should do what you're wanting.

ASP.NET EnqityDataSource WhereParameters, creates new property

I am trying to populate GridView, using EntityDataSource(code behind), I need to able to sort GridView. However when I sort i get error:
A property with name 'aspnet_Users.UserId1' does not exist in metadata for entity type
So I beleive it is because I generate where parameter in code behind:
ActiveEnqDataSource.WhereParameters.Add(new SessionParameter("aspnet_Users.UserId", TypeCode.Object, "UserName"));
Full code is :
ActiveEnqDataSource.ConnectionString = db.Connection.ConnectionString;
ActiveEnqDataSource.DefaultContainerName = "Entities";
ActiveEnqDataSource.EntitySetName = "Enquiries";
ActiveEnqDataSource.Include = "UserCars.CarModel.CarMake, Category, aspnet_Users";
ActiveEnqDataSource.EnableUpdate = true;
ActiveEnqDataSource.EnableInsert = true;
ActiveEnqDataSource.EnableDelete = true;
ActiveEnqDataSource.AutoGenerateWhereClause = true;
ActiveEnqDataSource.WhereParameters.Add(new SessionParameter("aspnet_Users.UserId", TypeCode.Object, "UserName"));
Any suggestions? Thank you very much! The gridview itself renders perfectly, only thing I cannot sort it, any "whereParameters" I add, Add 1 to the property e.g UserId1,EnquiryStatus1, ProdauctName1. etc...
I got a similar error because I was adding the where clause each time the page was posted back. Dropping my code that generated the where clause inside an IsPostback statement fixed the problem:
if (!IsPostBack) {
// code to add where parameters
}
I got the same error when I used markup to define a Where parameter AND then I added the same parameter in code. Somewhere along the line, the 1 at the end of the parameter name was added.

Eval versus DataField in ASP:Datagrid

I have this really random problem with is bugging me. It works at the end of the day but the problem took some time to figure out and was wondering why this happens so if anyone shed some light on the subject I would be really grateful. Here is the problem
I have the following two columns on my datagrid
<asp:boundcolumn
datafield="contentsection.Id"
headerstyle-cssclass="dgHead"
headertext="Section"
itemstyle-cssclass="dgItem" />
and
<asp:templatecolumn>
<itemtemplate><%#Eval("contentsection.Id") %></itemtemplate>
</asp:templatecolumn>
The first column gives me the error of:
A field or property with the name 'contentsection.Id' was not found on the selected data source
but the second on runs fine. Any ideas or theories as to why this is happening ?
The way that I call and bind my data is like so:
Page Load Code Behind
ContentList.DataSource = ContentBlockManager.GetList();
ContentList.DataBind();
The GetList() function it is overloaded and by default passed a 0
public static List<ContentBlockMini> GetList(int SectionId)
{
List<ContentBlockMini> myList = null;
SqlParameter[] parameters = { new SqlParameter("#ContentSectionId", SectionId) };
using (DataTableReader DataReader = DataAccess.GetDataTableReader("dbo.contentblock_get", parameters))
{
if (DataReader.HasRows)
{
myList = new List<ContentBlockMini>();
}
while (DataReader.Read())
{
myList.Add(FillMiniDataRecord(DataReader));
}
}
return myList;
}
and my filling of the data record. The ContentSection is another Object Which is a property of the ContentBlock object
private static ContentBlockMini FillMiniDataRecord(IDataRecord DataRecord)
{
ContentBlockMini contentblock = new ContentBlockMini();
contentblock.Id = DataRecord.GetInt32(DataRecord.GetOrdinal("Id"));
contentblock.Name = DataRecord.GetString(DataRecord.GetOrdinal("Name"));
contentblock.SEOKeywords = DataRecord.IsDBNull(DataRecord.GetOrdinal("SEOKeywords")) ? string.Empty : DataRecord.GetString(DataRecord.GetOrdinal("SEOKeywords"));
contentblock.SEODescription = DataRecord.IsDBNull(DataRecord.GetOrdinal("SEODescription")) ? string.Empty : DataRecord.GetString(DataRecord.GetOrdinal("SEODescription"));
if (DataRecord.GetInt32(DataRecord.GetOrdinal("ContentSectionId")) > 0)
{
ContentSection cs = new ContentSection();
cs.Id = DataRecord.GetInt32(DataRecord.GetOrdinal("ContentSectionId"));
cs.Name = DataRecord.IsDBNull(DataRecord.GetOrdinal("ContentSectionName")) ? string.Empty : DataRecord.GetString(DataRecord.GetOrdinal("ContentSectionName"));
contentblock.contentsection = cs;
}
return contentblock;
}
There you go that is pretty much the start to end.
Databinding can only access "top level" properties on an object. For example, if my object is
Company with simple properties CompanyId and Name and a child object for Address, databinding can only access CompanyId and Name, not Company.Address.City.
Eval can access child object properties if you import the namespace using an #Import page directive.
The "Bind" marker is a two-way bind and is made using the default namespace attached to the datasource of the object. This can't be overridden, and because of this tightly coupled connection the namespace should be left off as assumed (since it's dynamically pulled from the datasource).
Eval is a one-way binding that can be used with any namespace that will fulfill a proper evaluation. Dates, strings, method calls, etc. The namespace provided in your example just provides eval with a marker on where to get the data relevant.
The key here is the nature of the binding. Eval is a "fire and forget" sort of binding where as Bind is more rigid to facilitate the two-way.
The DataField property approach isn't complicated enough to support dot notation; it expects a direct reference in your underlying data source; it takes that field and checks the data source, which it can't find it by the exact string.
The second approach, eval, is more dynamic, but actually I wasn't sure if it supported dot notation... learn something everyday.
HTH.
It's necessary take a look to your DataSource, but you can do a simple test: convert the first column to a template column a try to Run.
In EntityFramework is possible Eval Properties using code like this: <%#Eval("Customer.Address.PostalCode") %>.
I dont know if it is your case, but if you provide more details about how to retrieve the DataSource we can help you.

Resources