Parse Value from repeater - c#

<asp:Repeater ID="repeater" runat="server" OnItemDataBound="repeater_ItemDataBound">
<HeaderTemplate>
<ul class="sf_newsList">
</HeaderTemplate>
<ItemTemplate>
<asp:Literal ID="Publication_Date" runat="server" Text="{0}" />
...
Ok so i have a date coming back from the source, i need to strip this date into day and month as it currently
comes back like "march 12 2012".
once parsed into a day and a month string i want to then pass it back into
<asp:Literal ID="Publication_Day" runat="server" Text="{0}" />
now ive tried some things such as
protected void repeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
string newsdate = "";
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Literal ltDate = (Literal)e.Item.FindControl("Publication_Date");
newsdate = ltDate.Text;
//do parse code
Literal ltDay = (Literal)e.Item.FindControl("Publication_Day");
ltDay.Text = newsdate;
}
}
but when i step through the publication_date is only returning {0} as a string not the date.
i know the source is fine, as if i just put the date on the template is shows up on the front end.
Any ideas what im doing wrong?

It is returnin {0} because it is on the Text property of Literal.
You could use the DataBinder.Eval to read the column of your DataSource from e.Item.DateItem. Since you know what is the column you want to read you could get the DateTime object direct from datasource, for sample:
// get the dateTime from datasource
DateTime datePublication = DateTime.Parse(DataBinder.Eval(e.Item.DataItem, "DatePublicationColumn").ToString());
// show the day name
ltDay.Text = datePublication.ToString("dddd");
Where I add DatePublicationColumn, you specify the column.

Related

query string on link button

In a GridView I have the list of 2 bed and breakfasts (ShowAllBeb.aspx) which are in DB, one with idname = 0 and the other with idname = 1. I've created LinkButtons that will refer to the B&B detail (DisplayBeb.aspx)
Code aspx:
<asp:LinkButton ID="Label4" runat="server" Text='<%# Eval("name") %>'
ForeColor="#0066cc"
PostBackUrl='<%# "~/site/DisplayBeb.aspx?idname={0}" + Eval("name") %>'>
</asp:LinkButton>
code aspx.cs:
using (dcDataContext dc = new dcDataContext())
{
DataListBeb.DataSource = from beb in dc.beb
select beb;
string fullname1 = Request.QueryString["idname"];
DataListBeb.DataBind();
With this code, if I click on all 2 B & Bs, the detail page of the idname = 0 comes out for both of them. How can I make the other detail page of the B&B visible?
It looks like the query string itself is correct, so you're focusing on the wrong place for the problem. You are successfully getting the query string value:
string fullname1 = Request.QueryString["idname"];
You're just not using that value for anything. I suspect you probably want to use it in a where clause on your query:
string fullname1 = Request.QueryString["idname"];
DataListBeb.DataSource = from beb in dc.beb
where beb.name == fullname1
select beb;
or:
string fullname1 = Request.QueryString["idname"];
DataListBeb.DataSource = dc.beb.Where(b => b.name == fullname1);
Of course I don't know what your beb model looks like or what its properties are called, so beb.name was entirely a guess based on the use of Eval("name") above. Simply use whatever property is appropriate in your query.

Unable to retrieve date input value C# Web Forms

Here is what I can see when I do e.Item.FindControl for the TextBox I'm trying to get the value for
I have 2 date inputs in a list view and I am trying to retrieve their values but always get an empty string.
If I set the value in the front end then it comes through to the code behind but if I edit the field the original value is returned.
I am able to get the values from and controls without an issue.
I've tried using asp:TextBox and html
<asp:TextBox ID="editArrivalFrom" name="editArrivalFrom" TextMode="Date" runat="server" OnTextChanged="editArrivalFrom_TextChanged"></asp:TextBox>
<input type="date" id="editArrivalTo" name="editArrivalTo" runat="server" />
var arrivalFrom = (TextBox) e.Item.FindControl("editArrivalFrom");
if (!String.IsNullOrWhiteSpace(arrivalFrom.Text))
var arrivalTo = (HtmlInputGenericControl) e.Item.FindControl("editArrivalTo");
if (!String.IsNullOrWhiteSpace(arrivalTo.Value))
I've also tried using Request.Form, all of the below return null:
var test = Request.Form[arrivalFrom.UniqueID];
var test2 = Request.Form[arrivalFrom.ClientID];
var test3 = Request.Form["editArrivalFrom"];
There is also no sign of either of the inputs in Request.Form.AllKeys
The asp control doesn't show up in the designer.cs file and adding it only results in it being null anyway.
Any suggestions would be much appreciated I've been pulling my hair out for hours.
Relevant code for the form update is below. Please note that all of this is contained within an update panel
<asp:ListView ID="MarkupRuleList" runat="server"
OnItemCommand="MarkupRuleList_OnItemCommand">
<EditItemTemplate>
<asp:LinkButton ID="btnUpdate" CssClass="lstview_record_bttn button-spacing-7" Text="Update" CommandName="Update" CommandArgument='<%# Eval("Id") %>' runat="server" />
</EditItemTemplate
protected void MarkupRuleList_OnItemCommand(object sender, ListViewCommandEventArgs e)
{
int markupId = 0;
int.TryParse(e.CommandArgument.ToString(), out markupId);
var markup = new MarkupRuleDTO();
switch (e.CommandName)
{
case "Update":
// GetMarkupRuleFromPage contains all of the code from the top of this post
markup = GetMarkupRuleFromPage(e, markupId);
break;
}
}
Edit: Solved by ditching the date input and using regular textbox, then performing the following onkeyup JS function
function dateInputHandler(item, event) {
// key code 8 == backspace
if (event.keyCode != 8) {
// insert forward slashes after days and months
if (item.value.length == 2 || item.value.length == 5) {
item.value = item.value + '/'
}
// remove double slashes and prevent length exceeding 10 characters
// format should be dd/mm/yyyy
if (item.value.endsWith("//") || item.value.length > 10) {
item.value = item.value.slice(0, -1);
}
}
}
You may be better off casting the sender object rather than the EventArgs object.
var x = ((TextBox)sender).Text;
But you can access the control directly (or should be able to).
var x = editArrivalFrom.Text;
And to get from the form, use the correct variable name:
var x = Request.Form[editArrivalFrom.ClientID];

If inside html code with entity framework

I am using asp.net webform 4.5.1 code first with entity framework. I used one repeater and bind it to my entity class. I want use if statement to decide show one DIV in this repeater or not. my code is :
<asp:Repeater ID="ProductRepeater" runat="server"
ItemType="Models.Product"
SelectMethod="ProductRepeate_GetData">
<ItemTemplate>
<% if(Item.Rank > 5 && Item.X != null && Item.Y != null){%>
<div>I want show this div just if my if statement is True</div>
<%}%>
<div >
<%# Item.Name%>
</div>
</ItemTemplate>
</asp:Repeater>
I want show the first div just when the result of if statement is True. the error is : The name 'Item' does not exist in the current context
This isn't the kind of calculation that you would want to include inline; not only will it be very difficult to read, it will also be very difficult to debug.
Instead, create a label <asp:Label ID="outputLabel" runat="server" ></asp:Label> and set the value of the label from the ItemDataBound Event on the repeater.
protected void ProductRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
RepeaterItem item = e.Item;
Label output = (Label)item.FindControl("outputLabel");
Product product = (Product)item.DataItem;
if (product.Rank > 5 && product.X != null && product.Y != null)
{
output = "I want show this div just if my if statement is True";
}
else
{
output = product.Name;
}
}
I know you already got an answer, you can do it in markup also like this:
<%# (Item.Rank > 5 && Item.X != null && Item.Y != null)? "<div>I want show this div just if my if statement is True</div>" : "" %>

How to use web page scheduler in C#.net

In one .aspx webpage I have 2 contacts details in two different <div> like below
<div id="primaryContact">
Name - betty quay
Cell - 9867452389
designation - Build
</div>
<div id="secondryContact">
Name - francesco maitire
Cell - 9867452389
designation - Build
</div>
Here I want to show each div on alternate day of a week.
How can I do so, using ASP.NET or Javascript?
You can do it in C# like this:
protected void Page_Load(object sender, EventArgs e)
{
ShowContactAlternate();
}
private void ShowContactAlternate()
{
if ((int)DateTime.Now.DayOfWeek % 2 == 0)
primaryContact.Visible = true;
else
secondaryContact.Visible = true;
}
Also make sure that you change your markup to something like this and add runat="server and Visible="False" attributes to divs":
<div id="primaryContact" runat="server" Visible="False"> Name - betty quay Cell - 9867452389 designation - Build </div>
<div id="secondryContact" runat="server" Visible="False"> Name - francesco maitire Cell - 9867452389 designation - Build </div>
EDIT:
If you want to alternate every week you can do it like this probably:
Create this helper function:
private int GetWeekOfYear(DateTime date)
{
return CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(date,
CalendarWeekRule.FirstFourDayWeek,
DayOfWeek.Monday);
}
And you can use it in your if statement inside ShowContactAlternate line this:
if (GetWeekOfYear(DateTime.Now) % 2 == 0)
As every year has 52 weeks you have to be sure that you don't run in to trouble every new year. It shouldn't be a problem to solve.

populate CheckBoxList from query using FindByValue

I have an asp.net chckebox list:
<asp:EntityDataSource ID="GradeLevelEntityDataSource" runat="server"
ConnectionString="name=NewCourseRequestDataEntities"
DefaultContainerName="NewCourseRequestDataEntities" EnableFlattening="False"
EntitySetName="grade_levels" OrderBy="it.grade_level_index">
</asp:EntityDataSource>
<asp:CheckBoxList ID="GradeLevelCheckBoxList" runat="server" cssClass="horizontalcontrols"
DataSourceID="GradeLevelEntityDataSource"
DataTextField="grade_level_description" DataValueField="grade_level_id" AutoPostBack="True"
OnSelectedIndexChanged="CollegeInstitutionsListboxChange"
RepeatDirection="Horizontal" RepeatLayout="Flow">
</asp:CheckBoxList>
A user can return to the page, it gets the record ID, pulls the record data, and should check the appropriate checkboxes:
CheckBoxList grades = (CheckBoxList)FindControl("GradeLevelCheckBoxList");
foreach (request_grade_college r in CurrentRequest.request_grade_college)
{
ListItem grade = grades.Items.FindByValue(r.grade_level_id.ToString());
if (grade != null)
{
grade.Selected = true;
}
}
the portion of the code r.grade_level_id.ToString() does return the correct GUID, as type String. However, ListItem grade remain null, so none of the GradeLevelCheckboxList get checked.
What am I missing please?
I think that the data is not yet bound when you try to access it using Items.FindByValue(), try calling
grades.DataBind();
before the foreach loop.
Please make sure the listbox item's Value property has the correct value, if Item's Text and Value are different.
Also, Value Property and grade_level_id are exactly of same case and with trimmed spaces.

Categories