If inside html code with entity framework - c#

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>" : "" %>

Related

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];

Checking to see if DropDownList selected index has a value

In my C# web application, I have three textboxes, three drop down lists, and one button.
The button is suppose to run a SQL string that will take the values of whatever is in typed in the textboxes, whatever is selected, and be inserted into the database. The values inserted may not be null so I don't want any blank entries. By default, I have the DropDownList like so in the source:
<asp:DropDownList ID="ReadDrop" runat="server">
<asp:ListItem></asp:ListItem>
<asp:ListItem Value="1">Yes</asp:ListItem>
<asp:ListItem Value="0">No</asp:ListItem>
</asp:DropDownList>
So there is a blank entry (default), and then the yes/no. There are three of these drop down lists in the application. In my C# code, I have the following to prevent the button from firing if there is a blank entry:
if (UsernameBox.Text != "" & FirstNameBox.Text != "" & LastNameBox.Text != "" /* check for blank dropdownlist? */)
My current issue is that I don't know how to check the dropdownlist for a blank entry. My guess would have been to check to see if ReadDrop.Text is blank, but I am relatively inexperienced in ASP.NET and am wondering if there is a "proper" way to do this.
Thanks!
You could use SelectedIndex > 0:
if (UsernameBox.Text != "" & FirstNameBox.Text != "" & LastNameBox.Text != "" && ReadDrop.SelectedIndex > 0)
{
// ...
}
Note that the SelectedIndex is -1 if no item is selected and yes/no have 1/2.
Another option is to use the SelectedItem:
ListItem selectedItem = ReadDrop.SelectedItem;
if(selectedItem != null && !String.IsNullOrEmpty(selectedItem.Text))
{
// ...
}
However, i think that you actually want to prevent that the user selects no item, or in other words, validate that he selects something. Then use a RequiredFieldValidator, you have to set the InitialValue to "":
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ErrorMessage="Select Something" ControlToValidate="ReadDrop"
InitialValue=""></asp:RequiredFieldValidator>
You could assign a different Value to your empty item and change the InitialValue appropriately:

Display content in Repeater

I must have done so that I can print anything into my Repeater, but it is such that I can not really for it to write the content that I really want to do.
I have written the code like this
forum.aspx
<asp:Repeater ID="RepeaterKommentar" runat="server">
<ItemTemplate>
<div class="kommentarBox">
<%--print content here--%>
</div>
</ItemTemplate>
</asp:Repeater>
forum.aspx.cs
var UsersKommentar = from KommentarA in db.forumkommentars
join BrugereA in db.brugeres on KommentarA.brugerid equals BrugereA.Id
where KommentarA.forumid == getid
orderby KommentarA.Id descending
select new
{
UserName = BrugereA.fornavn + " " + BrugereA.efternavn
};
RepeaterKommentar.DataSource = UsersKommentar;
RepeaterKommentar.DataBind();
The problem, is I'm not entirely sure how to access the object of Enumerable through my data source.
I'm not sure what data exist within your object, but you've bound it to the repeater and called data bind. So all you need to do now is call:
<%# Eval("...") %>
The ... would represent the name of the column, or property.

How to set conditions based on Eval() value?

I have this code
<div class="result correct"><%# Eval("QandAID") %></div>
and I am wondering how I can set conditions on the value, I.e if the eval value is 2 change div class to "result incorrect" else leave as "result correct". That's also part of the question if anyone knows how to do that (change the div class based on the condition), then that would be a bonus.
Oh and I have that code inside a repeater bound to a dataset.
Define a property in the Page class:
public int MyValue { get; set; }
Then access it in the page this way:
<div style='width: <%=MyValue %>px'></div>
This example should answer indirectly your question and open up some more possibilities on how to put values into HTML that may or may not be bound to a DataRow.
Another example:
<%# Eval("QandAid") == 2 ? "result incorrect" : "result correct" %>
Or:
<div class='<%# Eval("QandAid") == 2 ? "class1" : "class2" %>'>
This should happen outside of the markup. Make the class a property of your model and set it based on your condition:
class YourModel {
public int QandAID { get; set; }
public string ValidityClass {
get {
return QandAID == 1 ? "correct" : "incorrect";
}
}
}
Then your repeater template becomes something like this:
<div class='result <%# Eval("ValidityClass") %>'><%# Eval("QandAID") %></div>

Unable to get value of the property 'length': object is null or undefined - Javascript Error

In my user control, there is a GridView.
When I check checkbox in the header of the GridView, I want to select all checkboxs.
My user control can be use more than once in a page.
So I try like this.
My GridView
<asp:GridView ID="GridView" runat="server">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkHeader" runat="server" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkEach" runat="server" />
</ItemTemplate>
.
.
This is my C# codes
CheckBox chkAll = gvAttachment.Controls[0].Controls[0].FindControl("chkHeader") as CheckBox;
if (chkAll != null)
{
chkAll.Attributes.Add("onclick", "SelectAllChkBox('" + chkAll.ClientID + "','" + GridView.ClientID + "');");
}
This is my javascript
function SelectAllChkBox(value , grid) {
for (var i = 1; i < grid.all.length; i++) {
grid.all[i].checked = value.checked;
}
}
But I got this error.
Unable to get value of the property 'length': object is null or undefined
What is wrong with my Code ?
The parameter grid is the id (a string) of the grid view which means you don't have an "all". length works on the "grid" though. You are not passing an object from c#.
You'll need to find all the check boxes client-side and set checked based on a true or false value.
An array starts from 0:
function SelectAllChkBox(value , grid) {
for (var i = 0; i < grid.all.length; i++) {
grid.all[i].checked = value.checked;
}
}
try this function
function SelectAllChkBox(value , grid) {
var n = document.getElementById("grid").rows.length;
for (var i = 0; i < n; i++) {
grid.all[i].checked = value.checked;
}
}

Categories