How to get an Item's Lifetime in Sitecore - asp.net

I would like to show Menu items on page, based on their valid from & to dates. But before that, wanted to test the output. The _Valid to date is set to 3/17/2016 12:00 AM for the 'About us' item.
The output is About us--.
What is the right way to get the Valid from & to dates.
protected void rpMenu_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
var mainItem = (Item)e.Item.DataItem;
if (mainItem != null)
{
Response.Write(mainItem.Name + "-" + mainItem.Fields["Valid to"] + "-");
//this one did not work too
Response.Write(mainItem.Name + "-" + mainItem.Fields["_Valid to"] + "-");
}
}

You can use next constants for getting ValidTo and ValidFrom fields
mainItem.Fields[Sitecore.FieldIDs.ValidFrom] and mainItem.Fields[Sitecore.FieldIDs.ValidTo]
These constants are from Sitecore.Kernel assembly.

Related

How to change Gridview's row color based on a specific cell value? Asp.net

I browsed through dozens of websites and posts now and I can't find anything "right".
All I want is to paint a row with a red color in my Datatable/GridView based on specific cell value.
Please help me out here :( . . .
for (int i = 0; i < TheFinalTable.Rows.Count; i++)
{
TheLevel = myUsers[i, 0];
if (TheLevel == "2" && TheFinalTable.Rows[i][4].ToString() == myUsers[i, 1])
{
Gridview1.Rows[i].ForeColor = System.Drawing.Color.LightGreen;
}
if (TheLevel == "3" && TheFinalTable.Rows[i][4].ToString() == myUsers[i, 1])
{
Gridview1.Rows[i].ForeColor = System.Drawing.Color.Red;
}
}
"MyUsers" is a string array that contains The level and the ID.
Level | id
1 | 2 64
2 | 3 23
"TheFinalTable" contains The following in this order:
Mail, Name, Lastname, phone, ID, Rent, LastLog.
Just noticed it also says "Index was out of range" when it comes to the second if (which it is true).
The main question is this:
How to set different color to a specific row based on the row's one cell value or just by the row number?
Hope to hear from you guys soon.
Take care.
Subscribe to the RowDataBound event of the grid in your page's load method:
this.GridView1.RowDataBound += GridView1_RowDataBound;
Whenever the row is bound to the data, it will call your handler. Here is the event handler where you will do the changing of the background color:
private void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//make sure it is not the header row
if(e.Row.RowType == DataControlRowType.DataRow)
{
// whatever your condition
if(e.Row.Cells[0].Text == "Whatever")
{
e.Row.BackColor = Drawing.Color.Red // This will make row back color red
}
}
}

Session is still the same after edited

debug message is always the following after pressed next button many times,
it can go from page 1 to page 2 but can not go to page 3
finally i find the problem is
Session["jobsearch"] = js;
it has saved but next time i retrieve this, it is like not saved before
debug message
before js.CurrentPageNo=1
after js.CurrentPageNo=2
js.StartIndex=13
js.PageSize=24
js.TotalPageFound=5
js.CurrentPageNo=2
rowPerPage=12
before js.CurrentPageNo=1
after js.CurrentPageNo=2
js.StartIndex=13
js.PageSize=24
js.TotalPageFound=5
js.CurrentPageNo=2
rowPerPage=12
js.StartIndex=13js.PageSize=24js.TotalPageFound=5js.CurrentPageNo=2rowPerPage=12
js.StartIndex=13js.PageSize=24js.TotalPageFound=5js.CurrentPageNo=2rowPerPage=12
js.StartIndex=13js.PageSize=24js.TotalPageFound=5js.CurrentPageNo=2rowPerPage=12
js.StartIndex=13js.PageSize=24js.TotalPageFound=5js.CurrentPageNo=2rowPerPage=12
next button code
protected void btnNext_OnClick(object sender, EventArgs e)
{
if (Session["jobsearch"] != null)
{
JobSearch js = (JobSearch)Session["jobsearch"];
js.CurrentPageNo++;
js.StartIndex = js.StartIndex + rowPerPage;
js.PageSize = js.PageSize + rowPerPage;
Session["jobsearch"] = js;
if (jobResultsTable.DocumentContent.Contains("Jobs In Engineering"))
{
Session["jobsearch2"] = "Jobs In Engineering";
}
else
{
Session["jobsearch2"] = "Jobs In IT";
}
System.IO.File.AppendAllText(#"D:\Debug.txt", "js.StartIndex=" + js.StartIndex);
System.IO.File.AppendAllText(#"D:\Debug.txt", "js.PageSize=" + js.PageSize);
System.IO.File.AppendAllText(#"D:\Debug.txt", "js.TotalPageFound=" + js.TotalPageFound);
System.IO.File.AppendAllText(#"D:\Debug.txt", "js.CurrentPageNo=" + js.CurrentPageNo);
System.IO.File.AppendAllText(#"D:\Debug.txt", "rowPerPage=" + rowPerPage);
GetJobSearchBOResult(js.StartIndex, js.PageSize, js.JobType, js.JobCountry, js.Keywords);
ShowButton(js.CurrentPageNo, js.TotalPageFound);
ltrPageInfo.Text = "Page " + js.CurrentPageNo + " of " + js.TotalPageFound.ToString() + "<br/> Total Record(s) Found: " + TotalJobFound;
}
}
I'd wager that
(JobSearch)Session["jobsearch"];
is being reset every pageload either in your page's load event-handler or init event-handler.
Remember, those two events fire on every postback.
You might need to check if (!Page.IsPostBack){ /*Only Init jobsearch here */ } in your load/init handlers
I'd set a breakpoint wherever you have code that resets or initializes your session variables, then see if those breakpoints are hit more often than you think.

Compare Validator for two dates

I have two labels and two text boxes, a Compare validator and a button.
I need it to compare two dates (rental date , return date ) and when the rental date is less or equal to return date are the same. No validation message.
While when when the rental date is less than the return date, display an input error message.
The compare validator has been set with :
controltocompare : txtrental,
controltovalidate: txtreturndate,
operator :greater than equal,
type:date,
errormessage: return date must be greater or equal than rental date,
I am not sure how to get the btn to display it ?
You need to set the property "CausesValidation" of your button to "true" to trigger validation on its click.
Make sure the CompareValidator has runat="server"
Create a method to display message.
private void AlertBox(string Msg)
{
string s = "alert('" + Msg + "')";
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "ckey", s, true);
}
find the code to validate and throw alert message.
if (!String.IsNullOrEmpty(txtrental.Text) && !String.IsNullOrEmpty(txtreturndate.Text))
{
DateTime ssSD = Convert.ToDateTime(txtrental.Text);
DateTime qsED = Convert.ToDateTime(txtreturndate.Text);
int chktxtfd1_sd = ssSD.CompareTo(qsSD);
if ((chktxtfd1_sd == 0 || chktxtfd1_sd == -1) )
{
//do something bcoz condition is true
}
else
{
lvflag = false;
AlertBox("date must be greater or equal than rental date");
}
}
If you find it useful, please mark it as your answer else let me know...

Insert a control before another control inside a ItemDataBound event

I tried to Solution suggested here, but it didn't work in my case. using Page.Controls.IndexOf() for any of the elements on my page, when called in the ItemDataBound event method, returns -1.
I need to insert a linebreak based on certain conditions for stuff generated by my Data repeater. Here is the method:
private String lastCharacter = "";
public void users_ItemDataBound(Object Sender, RepeaterItemEventArgs e)
{
HyperLink link = (HyperLink)e.Item.FindControl("micrositeLink");
Tuple<String, String> user = (Tuple<String, String>)e.Item.DataItem;
link.NavigateUrl = "/" + user.Item1;
link.Text = user.Item2;
// makes a break in the data when going from one bunch of data to another.
if (user.Item1.Length >= 2)
{
if (lastCharacter == "")
lastCharacter = user.Item1[1].ToString().ToLower();
else if (lastCharacter != user.Item1[1].ToString().ToLower())
{
HtmlGenericControl lineBreak = new HtmlGenericControl("br");
if (Page.Controls.IndexOf(link) >= 0)
Page.Controls.AddAt(Page.Controls.IndexOf(link), lineBreak);
lastCharacter = user.Item1[1].ToString().ToLower();
}
}
}
The bound data is a list of users in my system with names beginning with a particular letter. My goal is to further sub-divide this data with a line break between groups of data that have the same second letter. For instance:
AaPerson Aarad AaStuff
Aathing
AbItem AbStuff
Acan Achandle
To me, inserting a line break before the elements where the second letter changes is the obvious solution, but other suggestions are also appreciated.
Try using e.Item.Controls.IndexOf instead:
if (e.Item.Controls.IndexOf(link) >= 0)
e.Item.Controls.AddAt(e.Item.Controls.IndexOf(link), lineBreak);

checking field values for null

I've been working through this for a while and I'm missing the obvious. I'm trying to make sure that if a textbox value is left blank an error isn't thrown and instead a simple message is displayed in the textbox. However, what I've got and several other methods I've tried similar to this haven't worked. I can't figure out why this isn't working and what I need to do differently.
Basics:
This is a simple calculator that allows one to enter their waist, neck, and height measurements to use in a formula that calculates their estimated body fat percentage. The calculation works properly unless a field is left blank.
Thanks for any help!
My code:
if (TBWaist.Text == null || TBNeck.Text == null || TBHeight.Text == null)
{
TBBodyFat.Text = "Value missing";
}
else
if (TBWaist.Text != null & TBNeck.Text != null & TBHeight.Text != null)
{
double waist;
double neck;
double height;
waist = Convert.ToDouble(TBWaist.Text);
neck = Convert.ToDouble(TBNeck.Text);
height = Convert.ToDouble(TBHeight.Text);
TBBodyFat.Text = Convert.ToString(String.Format("{0:p2}", ((501.5 / (1.0324 - .19077 * (Math.Log10(waist - neck)) + .15456 * (Math.Log10(height))) - 450) / 100)));
Error Message
This is the error message I get if I leave the waist textbox blank. I get the same error if I leave any of the others blank as well.
Input string was not in a correct format on line 45.
waist = Convert.ToDouble(TBWaist.Text);
I would recommend using the TryParse methods. In this way, a blank, an empty string or something that is not convertible to a string are all treated the same. Second, I would recommend adding RequiredFieldValidators and/or RegularExpressionValidators to each of the text boxes to ensure that the user enters a value and that value is numeric. In this way, the check in your event procedure acts as a last ditch check instead of requiring a PostBack for validation
protected void Button1_Click(object sender, EventArgs e)
{
//Navy Men's Body Fat Formula: %Fat=495/(1.0324-.19077(log(abdomen-neck))+.15456(log(height)))-450
//string outputString = String.Format("At loop position {0}.\n", i);
double waist;
double neck;
double height;
if ( !double.TryParse( TBWaist.Text, out waist )
|| !double.TryParse( TBNeck.Text, out neck )
|| !double.TryParse( TBHeight.Text, out height ) )
{
ErrorMessageLabel.Text = "Please ensure that each value entered is numeric.";
return;
}
var bodyFat = (501.5
/ (1.0324 - .19077 * (Math.Log10(waist - neck))
+ .15456 * (Math.Log10(height))
) - 450 ) / 100;
TBBodyFat.Text = bodyFat.ToString("P2");
}
You should test for more than just null values you have to test for empty as well
use String.IsNullOrEmpty(TBWaist.Text);
How about using a RequiredFieldValidator?
Alternatively, you can check that the value is an empty string and/or null
if (
String.IsNullOrEmpty(TBWaist.Text) ||
String.IsNullOrEmpty(TBNeck.Text) ||
String.IsNullOrEmpty(TBHeight.Text)
)
Try a compare like
if( String.IsNullOrEmpty( TBWaist.Text ) == true )
{
// error case
}
else
{
// do stuff
}
You should use String.IsNullOrEmpty() instead. Your input field values are not null, simply empty, hence the conversion fails.
protected void Button1_Click(object sender, EventArgs e)
{
//Navy Men's Body Fat Formula: %Fat=495/(1.0324-.19077(log(abdomen-neck))+.15456(log(height)))-450
//string outputString = String.Format("At loop position {0}.\n", i);
if (String.IsNullOrEmpty(TBWaist.Text) || String.IsNullOrEmpty(TBNeck.Text) || String.IsNullOrEmpty(TBHeight.Text))
{
TBBodyFat.Text = "Value missing";
}
else
{
double waist;
double neck;
double height;
waist = Convert.ToDouble(TBWaist.Text);
neck = Convert.ToDouble(TBNeck.Text);
height = Convert.ToDouble(TBHeight.Text);
TBBodyFat.Text = Convert.ToString(String.Format("{0:p2}", ((501.5 / (1.0324 - .19077 * (Math.Log10(waist - neck)) + .15456 * (Math.Log10(height))) - 450) / 100)));
}
}

Resources