How do I run an if statement in aspx? - c#

I would like to run an if statement but the condition uses a variable from the code behind. How do I call that variable? Side note... I am using a gridview and the variable is in a dataset (dsResult - idnbr colum)
<ItemTemplate>
<% string temp = (Eval("idnbr").ToString());
if (temp.Contains("X")) { %>
<asp:Label ID="Label1" runat="server" Text='<%# (Eval("old_amt").ToString(),"ccTot") %>'></asp:Label>
<% } else { %>
<asp:Label ID="Label2" runat="server" Text='<%# (Eval("new_amt").ToString(),"ccTot") %>'></asp:Label>
<% } %>
</ItemTemplate>

Create c# side method that does it for you:
Than use one of 2 ways:
If you deal with well known entity (saying when GridView bound to ObjectDatasource) you
can just cast it to your entity and pass back:
C#:
protected String MySelectorImpl(Object rowData)
{
MyEntity ent = (MyEntity)rowData;
if(ent.idndr .... )
return ....
else
return ...
}
ASP.Net:
<ItemTemplate>
<asp:Label Text='<%# MySelector(Container.DatatItem) %>' ...
Second case - just use eval syntax
C#:
protected string MySelector(Object condition, Object value1, Object value2)
{
if((String)condition ....) return value1.ToString ....
}
ASP.Net:
<ItemTemplate>
<asp:Label Text='<%# MySelector(Container.DatatItem("idnbr", ... %>' ...
(,

I know this doesn't completely answer your question but why not just do this in the code behind? I'm assuming you're doing something with DataBinding?
string temp = (string)DataBinder.Eval(e.Item.DataItem, "idnbr");
string newAmount = (string)DataBinder.Eval(e.Item.DataItem, "new_amt");
string oldAmount = (string)DataBinder.Eval(e.Item.DataItem, "old_amt");
Label lbl1 = e.Item.FindControl("label1") as Label;
if(temp.Contains("X") {
lbl1.Text = oldAmount;
} else {
lbl1.Text = newAmount;
}

You can read from a property that is declared in the code behind; does this satisfy what you want?
Instead of string temp = ..., you can use this.MyProperty.Contains("X")...

<a href="javascript:onclick= window.location = 'RenewalPaymentGateway.aspx?RPID=<%# Eval("RPID")%>'" title="Pay">
<asp:Label ID="TEMP" Text='<%# If(Eval("PaymentStatus").ToString() = "Paid", "View", "Make payment") %>' runat="server" />
here in label the text view will appear when PaymentStatus=paid or the text will be make payment

Related

Textboxes Causing Problems in ASP.NET C# SQL

I am using a nested Gridview(I have 5 Nested Gridviews).
I have applied a Regular Field validator for these Gridviews.
But once I click the button, commas are generated in the textbox. Due to that whenever I click the button, all the validation get fired.
I have researched lots of articles but have not found one related to this.
Here is the image for the Gridview with the commas generated in the textbox:
HTML Code Part
<%-- First Gridview--%>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
CssClass="gvstyling gridview_width_60" ShowHeaderWhenEmpty="true" EmptyDataText="Record(s) Not Found!"
DataKeyNames="locality" ShowHeader="false" OnRowDataBound="gvLocality_RowDataBound">
<Columns>
<asp:TemplateField ItemStyle-Width="15px">
<ItemTemplate>
<img alt="" style="cursor: pointer" src="../images/plus.png" />
<asp:Panel ID="pnlCompanyName" runat="server" Style="display: none">
<%-- Second Gridview --%>
<asp:GridView ID="gvCompanyName" ShowHeader="false" ShowHeaderWhenEmpty="false" CssClass="gvstyling gridview_width_100"
OnRowDataBound="gvCompanyName_RowDataBound" runat="server"
AutoGenerateColumns="false" EmptyDataText="No Record(s) Found!">
<Columns>
<asp:TemplateField ItemStyle-Width="15px">
<ItemTemplate>
<asp:HiddenField ID="hfRetailer_Id" Value='<%# Eval("retailer_id") %>' runat="server"></asp:HiddenField>
<asp:HiddenField ID="hfLocality" Value='<%# Eval("locality") %>' runat="server"></asp:HiddenField>
<asp:Label ID="lbl" Visible="false" Text='<%# Eval("retailer_id") %>' runat="server"></asp:Label>
<img alt="" style="cursor: pointer" src="../images/plus.png" />
<asp:Panel ID="pnlSellOrderNo" runat="server" Style="display: none">
<%-- Third Gridview --%>
<asp:GridView ID="gvSellOrderNo" ShowHeader="false" ShowHeaderWhenEmpty="false"
CssClass="gvstyling gridview_width_100" runat="server" OnRowDataBound="gvSellOrderNo_RowDataBound"
AutoGenerateColumns="false" EmptyDataText="No Record(s) Found!">
<Columns>
<asp:TemplateField ItemStyle-Width="15px">
<ItemTemplate>
<asp:HiddenField ID="hf_SellOrderNo" Value='<%# Eval("sell_order_no") %>' runat="server"></asp:HiddenField>
<asp:Label ID="lblSellOrderNo" Visible="false" Text='<%# Eval("sell_order_no") %>' runat="server"></asp:Label>
<img alt="" style="cursor: pointer" src="../images/plus.png" />
<asp:Panel ID="pnlProductDetails" runat="server" Style="display: none">
<%-- fourth Gridview --%>
<asp:GridView ID="gvProductDetails" ShowHeader="false" ShowHeaderWhenEmpty="false"
CssClass="gvstyling gridview_width_100" runat="server" OnRowDataBound="gvProductDetails_RowDataBound"
AutoGenerateColumns="false" EmptyDataText="No Record(s) Found!">
<Columns>
<asp:TemplateField ItemStyle-Width="15px">
<ItemTemplate>
<asp:HiddenField ID="HiddenField1" Value='<%# Eval("sell_order_no") %>' runat="server"></asp:HiddenField>
<asp:HiddenField ID="hfProductId" Value='<%# Eval("product_id") %>' runat="server"></asp:HiddenField>
<asp:Label ID="lblProductId" Visible="false" Text='<%# Eval("product_id") %>' runat="server"></asp:Label>
<img alt="" style="cursor: pointer" src="../images/plus.png" />
<asp:Panel ID="pnlWarehouseDetails" runat="server" Style="display: none">
<%-- fifth Gridview--%>
<asp:GridView ID="gvWarehouseDetails" ShowHeader="false" ShowHeaderWhenEmpty="false"
CssClass="gvstyling gridview_width_100" runat="server"
AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblWarehouseId" Text='<%# Eval("c_warehouse_id") %>' Visible="false" runat="server"></asp:Label>
<%# Eval("warehouse_name") %> (<%# Eval("qty") %>)
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="txtQty" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<%-- fifth Gridview --%>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<%# Eval("product_name") %> (<%# Eval("qty") %>)
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<%-- fourth Gridview --%>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<%# Eval("sell_order_no") %>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<%-- Third Gridview --%>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Business Name">
<ItemTemplate>
<%# Eval("business_name") %>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<%-- Second Gridview--%>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-CssClass="gv_item_bg">
<ItemTemplate>
<asp:Label ID="lblLocality" runat="server" Text=' <%# Eval("locality") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<%-- First Gridview --%>
Code Behind File
//Filling Shipping Company Name
private void FillShippingCompanyName()
{
try
{
ArrayList arr = new ArrayList();
cm.ds.Clear();
cm.sp_dataset_execute("spdisplay_Shipping_Comany_Name", arr);
ddlCompanyName.DataSource = cm.ds;
ddlCompanyName.DataValueField = "shipping_code";
ddlCompanyName.DataTextField = "shipping_name";
ddlCompanyName.DataBind();
ddlCompanyName.Items.Insert(0, new ListItem("---- Select Shipping Company ----", "0"));
}
catch (Exception ex)
{
ErrHandler.WriteError(ex.Message.ToString(), "Shipping-Order-FillShippingCompanyName()");
}
finally
{
cm.con.Close();
}
}
private void FillLocality()
{
try
{
cm.ds.Clear();
ArrayList arr = new ArrayList();
cm.sp_dataset_execute("spDisplay_Locality", arr);
gvLocality.DataSource = cm.ds;
gvLocality.DataBind();
}
catch (Exception ex)
{
ErrHandler.WriteError(ex.Message.ToString(), "Shipping-Order-FillLocality()");
cm.con.Close();
}
finally
{
cm.con.Close();
}
}
//Locality Gridview Row Databound (Level 1 Grdview)
common cm1 = new common();
protected void gvLocality_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string Locality = gvLocality.DataKeys[e.Row.RowIndex].Value.ToString();
GridView gvCompanyName = e.Row.FindControl("gvCompanyName") as GridView;
cm1.ds.Clear();
//Binding Company Gridview
ArrayList arr1 = new ArrayList();
arr1.Add("#locality|" + Locality + "");
cm1.sp_dataset_execute("spDisplayCompanyName", arr1);
gvCompanyName.DataSource = cm1.ds;
gvCompanyName.DataBind();
}
}
catch (Exception ex)
{
ErrHandler.WriteError(ex.Message.ToString(), "Recent_activity-gvRecentActivityOuter_RowDataBound()");
cm1.con.Close();
}
finally
{
cm1.con.Close();
}
}
//Comapny Name Gridview Row Databound (Level 2 Grdview)
common cm2 = new common();
protected void gvCompanyName_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string RetailerId = ((HiddenField)e.Row.FindControl("hfRetailer_Id")).Value;
GridView gvSellOrderNo = e.Row.FindControl("gvSellOrderNo") as GridView;
string Locality = ((HiddenField)e.Row.FindControl("hfLocality")).Value;
cm2.ds.Clear();
//Binding Company Gridview
ArrayList arr = new ArrayList();
arr.Add("#retailer_id|" + RetailerId + "");
arr.Add("#locality|" + Locality + "");
cm2.sp_dataset_execute("spDisplay_SellOrderNo", arr);
gvSellOrderNo.DataSource = cm2.ds;
gvSellOrderNo.DataBind();
}
}
catch (Exception ex)
{
ErrHandler.WriteError(ex.Message.ToString(), "Shipping-Order-Page_Load()");
cm2.con.Close();
}
finally
{
cm2.con.Close();
}
}
//Sell Order Gridview Row Databound (Level 3 Grdview)
common cm3 = new common();
protected void gvSellOrderNo_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string SellOrderNo = ((HiddenField)e.Row.FindControl("hf_SellOrderNo")).Value;
GridView gvProductDetails = e.Row.FindControl("gvProductDetails") as GridView;
FillProductDetails(gvProductDetails, SellOrderNo);
}
}
catch (Exception ex)
{
ErrHandler.WriteError(ex.Message.ToString(), "Shipping-Order-gvSellOrderNo_RowDataBound()");
cm3.con.Close();
}
finally
{
cm3.con.Close();
}
}
private void FillProductDetails(GridView gvProductDetails, string SellOrderNo)
{
cm3.ds.Clear();
//Product Details Gridview
ArrayList arr = new ArrayList();
arr.Add("#sell_order_no|" + SellOrderNo + "");
cm3.sp_dataset_execute("spDisplay_ProductDetails", arr);
gvProductDetails.DataSource = cm3.ds;
gvProductDetails.DataBind();
}
//Product Details Gridview Row Databound (Level 4 Grdview)
common cm4 = new common();
protected void gvProductDetails_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string ProductID = ((HiddenField)e.Row.FindControl("hfProductId")).Value;
string SellOrderNo = ((HiddenField)e.Row.FindControl("HiddenField1")).Value;
GridView gvWarehouseDetails = e.Row.FindControl("gvWarehouseDetails") as GridView;
cm4.ds.Clear();
//Product Details Gridview
ArrayList arr = new ArrayList();
arr.Add("#product_id|" + ProductID + "");
arr.Add("#sell_order_no|" + SellOrderNo + "");
cm4.sp_dataset_execute("spDisplay_WarehouseDetails", arr);
gvWarehouseDetails.DataSource = cm4.ds;
gvWarehouseDetails.DataBind();
}
}
catch (Exception ex)
{
ErrHandler.WriteError(ex.Message.ToString(), "Shipping-Order-gvProductDetails_RowDataBound()");
cm4.con.Close();
}
finally
{
cm4.con.Close();
}
}
//Submit Button
protected void btnSubmit_Click1(object sender, EventArgs e)
{
try
{
cm.ds.Clear();
//--Insert Query for Rs_Shipping_Order_Details
string ShippingCode = "SHO" + DateTime.Now.ToString("yyyyMMddHHmmss");
string ShippingGroup = "SG" + DateTime.Now.ToString("yyyyMMddHHmmss");
ArrayList arr = new ArrayList();
arr.Add("#shipping_code|" + ShippingCode + "");
arr.Add("#shipping_Company_code|" + ddlCompanyName.SelectedValue + "");
arr.Add("#is_shipping_delivered|0");
cm.sp_execute("spInsert_Shipping_Order_Detail", arr);
//Locality for loop
for (int i = 0; i < gvLocality.Rows.Count; i++)
{
GridView gvCompanyName = gvLocality.Rows[i].FindControl("gvCompanyName") as GridView;
//Company for loop
for (int j = 0; j < gvCompanyName.Rows.Count; j++)
{
GridView gvSellOrderNo = gvCompanyName.Rows[j].FindControl("gvSellOrderNo") as GridView;
string RetailerId = ((Label)gvCompanyName.Rows[j].FindControl("lbl")).Text;
//Sell Order for loop
for (int k = 0; k < gvSellOrderNo.Rows.Count; k++)
{
//Product Details Gridview
GridView gvProductDetails = gvSellOrderNo.Rows[k].FindControl("gvProductDetails") as GridView;
string SO = ((Label)gvSellOrderNo.Rows[k].FindControl("lblSellOrderNo")).Text;
int retailer_Id = Convert.ToInt32(RetailerId);
//Product Details for loop
for (int l = 0; l < gvProductDetails.Rows.Count; l++)
{
//Warehouse Details Gridview
GridView gvWarehouseDetails = gvProductDetails.Rows[l].FindControl("gvWarehouseDetails") as GridView;
string ProductId = ((Label)gvProductDetails.Rows[l].FindControl("lblProductId")).Text;
//Warehouse Details for loop
for (int m = 0; m < gvWarehouseDetails.Rows.Count; m++)
{
TextBox txtQty = gvWarehouseDetails.Rows[m].FindControl("txtQty") as TextBox;
string LastValue = txtQty.Text.Split(',').Last();
if (String.IsNullOrEmpty(LastValue) == false)
{
string Warehouse_Id = ((Label)gvWarehouseDetails.Rows[m].FindControl("lblWarehouseId")).Text;
int warehouse_id = Convert.ToInt32(Warehouse_Id);
string Qty = LastValue;
//Insert Query for Rs_Shipping_Detail_Mapping
ArrayList arr1 = new ArrayList();
arr1.Add("#shipping_order_code|" + ShippingCode + "");
arr1.Add("#retailer_id|" + retailer_Id + "");
arr1.Add("#sell_order_no|" + SO + "");
arr1.Add("#product_id|" + ProductId + "");
arr1.Add("#c_warehouse_id|" + warehouse_id + "");
arr1.Add("#shipping_group|" + ShippingGroup + "");
arr1.Add("#qty|" + Qty + "");
common cm1 = new common();
cm1.sp_execute("spInsert_Shipping_Detail_Mapping", arr1);
////Generating Pdf for Each Sell Order
//if (m == gvWarehouseDetails.Rows.Count - 1)
//{
// Generate_SellOrderWise_PDf(SO, ShippingCode, ShippingGroup);
//}
}
}
}
}
}
}
Response.Redirect("../final-shipping-order/?SG=" + ShippingGroup, false);
}
catch (Exception ex)
{
ErrHandler.WriteError(ex.Message.ToString(), "Shipping-Order-btnSubmit_Click1()");
cm4.con.Close();
}
finally
{
cm4.con.Close();
}
}
Question :
1. How do I remove the commas from the textboxes?
2. Reason for these commas? (Why are the commas being generated on the button click?)
3. Limit for the Nested Gridview ?
Any help will be appreciated.
When you have duplicate form field names, the values are concatenated together with commas.
So, for example, if you have the following..
<input type="text" name="name" value="">
<input type="text" name="name" value="">
.. your resulting value on Request.Form postback looks like this:
name=,,
That's what's happening.
Here are a few possible solutions to your problem, though I have not tested any of them :)
1) UpdatePanel
From reading, it seems that if you create an UpdatePanel for the offending grid control (<asp:TextBox ID="txtQty" runat="server"></asp:TextBox>) , it removes this problem. Again, I have not tested this
2) Changing DataBind() behavior during Page_Load()
So...
page_load()
{
if(!isPostBack())
{
// DataBind normally
myGridview.DataBind();
}
else
{
//Some intelligent way to remove commas before binding
}
}
... But that doesn't change the fact that the ,,,values are being posted in the first place. And so, if your primarily concerned with the end aesthetic and not behavior, you can just use JS to strip out the commas (as previously suggested hinted at.)
3) JS - Get Rid of the Commas:
(as suggested here)
<script type="text/javascript">
$("[src*=plus]").live("click", function () {
$(this).closest("tr").after("<tr><td></td><td colspan = '999'>" + $(this).next().html() + "</td></tr>")
$(this).attr("src", "images/minus.png");
$("input", $(this).closest("tr").next()).each(function () {
this.value = this.value.substring(',', '');
});
});
$("[src*=minus]").live("click", function () {
$(this).attr("src", "images/plus.png");
$(this).closest("tr").next().remove();
});
</script>
Hope this helps :)
[Edit] - Validation
I would fire off validation using the .keydown() event. In your case, it might look something like this:
// Bind to each input with id='txtQty', in each row, in the "gridview" with id='gvWarehouseDetails'
$("#gvWarehouseDetails tr input[id*='txtQty']").each(function () {
$(this).keydown(function (event) { // <-- specifies the specific input
// Validation logic goes here...
});
});
The Ajax Control Toolkit is a viable solution, however support for it has become non-existent. I'm assuming there is a level of dynamic control on that field. In essence, the grid will display it at certain instances?
Either way, you could add a specific class to the field:
<asp:Textbox id="txtContent" runat="server" CssClass="Validator">
Essentially when the grid adds all of these fields to your page, they'll all have the Validator class. So you can write JavaScript to actually strip the character out of the field, example:
$('.Validator').on('blur', function() {
$(this).replace(',', '');
});
As soon as the focus changes, that field will remove the , from the field as soon as the mouse leaves the , will be removed from the field.
That is one approach, countless other options do exist as well to accomplish this. This solution is pretty easy, agile, and light so it should be adequate.
Update:
The solution I chose shouldn't require a loop over those fields. Simply because blur triggers whenever a change or focus is lost on that field. Since you mentioned the , appears when the user clicks in the field. Otherwise you could do validation on all the fields. All you simply would need to do:
$('.Validator').each(function() {
// Will iterate through each field.
});
So you could essentially use JavaScript yourself to validate those fields, or use a simple library such as Valid8 which will do all client-side validation. No postback, all done client side before sent to the server to process.
Avoid:
Update Panel - These are quite a pain and incredibly inefficient. The way they work basically is by taking your entire page and storing it memory then does an Ajax request and refreshes your page and pulls all the contents out of memory to place on the page. Additionally it makes working with the Asp.Net Page Life Cycle incredibly difficult.
Hardik, how is txtQty.Text bound at first?
Does it come as an empty text box?
You using the code string LastValue = txtQty.Text.Split(',').Last(); to try go get rid of this comma values inserted or the values bound come with commas? I mean, you using the same UI culture from values in the database and the app or do you have to format it before displaying it?
I Don't know what is happening in your code. But If you want to get rid of Comma (',') then I should suggest one thing to you.
Add a reference of AjaxControlToolKit and register it in your aspx page as shown below:
<%# Register TagPrefix="ajaxToolkit" Namespace="AjaxControlToolkit" Assembly="AjaxControlToolkit, Version=[VersionNumber], Culture=neutral, PublicKeyToken=[TokenNumber]" %>
Or You can refer How to install AJAX Control toolkit
Once you have installed AJAX Control Toolkit, Go to your page and in your grid TemplateField, below TextBox txtQty, add FilteredTextBoxExtender as shown below:
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="txtQty" runat="server"></asp:TextBox>
<ajaxToolkit:FilteredTextBoxExtender runat="server" InvalidChars="," FilterMode="InvalidChars" TargetControlID="txtQty" />
</ItemTemplate>
</asp:TemplateField>
By Adding FilterTextBoxExtender, It will not allow characters to be inserted which are mentioned as InvalidChars to the textbox 'txtQty'.

Using markup in label text or similar element

I have
<asp:Label ID="lbl_ReadOnlyFld" runat="server"></asp:Label> <%=GetGuiLocalString("lbl_ReadOnlyFldDescr")%>
I need the text in some element so I can access it:
For example:
<asp:Label ID="lbl_InputFld" runat="server"></asp:Label><asp:Label ID="lbl_InputFldDescr" runat="server" text=' <%= GetGuiLocalString("lbl_InputFldDescr")%>'></asp:Label>
It just gives me stuff inside ''... any help would be appreciated.
Regards.
<%= is meant to directly output something on the page and can't be used inside other controls.
You should either use <%# and databind the control or set the text in the code behind. Also the other stuff should be inside those tags so it would be:
<asp:Label ID="lbl_InputFldDescr" runat="server" text='<%# " " + GetGuiLocalString("lbl_InputFldDescr")%>' />
and then lbl_InputFldDescr.DataBind(); somewhere in your code behind (provided you don't already databind the page or someting).
ASPX:
<asp:Label ID="lbl_InputFld" runat="server">my name is Jhon</asp:Label>
<asp:Label ID="lbl_InputFldDescr" runat="server" text='<%# " " + GetGuiLocalString("lbl_InputFldDescr")%>'></asp:Label>
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
DataBind();
}
public string GetGuiLocalString(string id)
{
string s = "hello";
Label lbl = (Label)Form.FindControl(id);
if(lbl!=null)
{
if ( ! string.IsNullOrEmpty(lbl.Text))
s = lbl.Text;
}
return s;
}

Aspx C#: How to get result of Eval(...) in grid_HtmlRowCreated?

I'm trying to use a parameter from .aspx in C# code inside grid_HtmlRowCreated method.
I tried it by setting a text in a label in .aspx and then fetch that text from the label.
It worked:
aspx
<dx:ASPxLabel runat="server" ID="cl" Text="Some text"/>
...
protected void grid_HtmlRowCreated(object sender, ASPxGridViewTableRowEventArgs e)
{
if (e.RowType == DevExpress.Web.ASPxGridView.GridViewRowType.Data)
{
...
string id;
if (comments_grid != null && expIDControl != null)
{
id = ((DevExpress.Web.ASPxEditors.ASPxLabel)expIDControl).Text;
System.Windows.Forms.MessageBox.Show( id );
}
}
But when I set the value like:
<dx:ASPxLabel runat="server" ID="cl" Text='<%# Eval("Id") %>'/>
then id is empty and when I set
<dx:ASPxLabel runat="server" ID="cl" Text='<%# Eval("Id") %> + " test"'/>
then id is literally <%# Eval("Id") %> test
Thank You for any ideas...
EDIT: That works as well, the code just need to be in HtmlRowPrepared, not in HtmlRowCreated. Thanks guys!
You can write a method on the class (.aspx.cs) that will concatenate.
Going from memory:
Text='<%# ConcatSomething (Eval("Id") , "Peanut" ) %> '/>
and then
public object ConcatSomething(object x , object y)
{
return Convert.ToString(x) + Convert.ToString(y);
}
or maybe
public object ConcatSomething(string x , string y)
{
return x + y;
}
You'll have to play with it. I've done it a thousand times on data_binding.
The stinker is the "object" stuff.
And you'll have to code for null values (coming in) if you may have some.
I just copied this from my current project , I have the same Grid with Item template and the correct way to do it is :
<dx:ASPxLabel runat="server" ID="cl" Text='<%# DataBinder.Eval(Container.DataItem, "Id") %>' />
regards

How to set ImageUrl based on the value of a field in a gridview

I have the following line of code which evaluates whether the value is true or false, if its true it will show an image if its false it shows a different one.
<itemTemplate>
<img alt="" id="Img1"
src='<%# MyAdmin.GetCheckMark((bool)DataBinder.Eval(Container.DataItem, "ShowImg"))%>'
runat="server" /></ItemTemplate>
Can I customize the Eval part in the back end code in c# and then pass a different variable to it for example in C# I want to do
bool ImgFlag = false;
if(Entity.ShowImg == false && Entity.SomethingElse == true)
{
ImgFlag = true;
}
else if(Entity.ShowImg == false && Entity.SomethingElse == false)
{
ImaFlag = false;
}
else
{
ImgFlag = true;
}
And then I want to use ImgFlag instead of ShowImg in my GridView on each row, so ImgFlag will determine which flag to show..
Or is there a better way?
The issue is that that eval depends now on two things.. not one as before.
Thank you
This does the trick
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:Image runat="server" ImageUrlt='<%#(bool)Eval("bit_field")? "first.jpg":"second.jpg" %>'>
</asp:Image>
</ItemTemplate>
Or this
<asp:TemplateField HeaderText="YourField">
<ItemTemplate>
<asp:ImageButton runat="server" ImageUrl="True.jpg" Visible='<%# (bool)Eval("bit_field") %>' />
<asp:ImageButton runat="server" ImageUrl="False.jpg" Visible='<%# !(bool)Eval("bit_field") %>' />
</ItemTemplate>
Found in this question
Eval actually returns a property, so you can just call it twice for different properties.
Kind of
MyAdmin.GetCheckMark2((bool)DataBinder.Eval(Container.DataItem, "ShowImg"),
(bool)DataBinder.Eval(Container.DataItem, "SomethingElse"));
may help

Eval(), can only be used in the context of a databound control Error. Why it happens? What can I do about it?

I am getting the following error, Using asp.net and nHibernate.
Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control.
I have this listview
<asp:ListView ID="CurrentHourList" runat="server" ItemPlaceholderID="itemPlaceholder">
<LayoutTemplate>
<asp:PlaceHolder ID="itemPlaceholder" runat="server"></asp:PlaceHolder>
</LayoutTemplate>
<ItemTemplate>
<asp:ImageButton ID="DeleteDateButton" CausesValidation="false" runat="server" CommandName="Delete"
ImageUrl="img/delete.png" />
<span style="display: none">
<asp:Label ID="Id" runat="server" Text='<%# Eval("Id") %>'></asp:Label></span>
<asp:Label ID="Date" Text='<%# Eval("Date", "{0:dd MMM yyyy}") %>' runat="server"></asp:Label>
<asp:DropDownList ID="MedicalType" runat="server" SelectedValue='<%# Eval("MedicalType.Id") %>'>
<asp:ListItem Text="Paid" Value="1"></asp:ListItem>
<asp:ListItem Text="Unpaid" Value="2"></asp:ListItem>
<asp:ListItem Text="Special" Value="3"></asp:ListItem>
</asp:DropDownList>
Half-Day:<asp:CheckBox ID="HalfDay" runat="server" Checked='<%# Eval("IsHalfDay") %>' />
<br />
</ItemTemplate>
</asp:ListView>
and this in my code behind
private void BindData(string id)
{
MedLeaveHelper = new MedicalLeaveHelper();
DTO.MedLeaveDTO dto = MedLeaveHelper.GetMedicalRequest(id);
if (dto != null)
{
EnableForm();
this.RequestId.Text = dto.Id.ToString();
this.ddlEmployeeName.SelectedItem.Text = dto.User;
this.Note.Text = dto.Note;
this.CurrentHourList.DataSource = MedLeaveHelper.MakeMedicalDays(id);
this.CurrentHourList.DataBind();
}
MakeMedicalDays(id) simply looks like this. MedicalDays is a IList
internal IEnumerable MakeMedicalDays(string id)
{
int theId = 0;
if (int.TryParse(id, out theId))
{
MedicalRequest r = MedicalRequest.Get(theId);
return r.MedicalDays;
}
return null;
}
When I get to the DataBind() call the error shows up. I've poked around on the tubes but nothing concrete is jumping out at me. I've tried changing the syntax to something like this
DataBinder.Eval(Container.DataItem,"id")
and the error goes away but no data makes it into my ListView either.
as I understand it DataBinder.Eval uses reflection to determine my datatype, but I am not sure how to troubleshoot this issue. Any help you could provide would be great.
Thanks
Jim
Not sure if the problem is in your listview. I tried a simple repro using the following databinding code - which worked fine with the ASPX you included above:
this.CurrentHourList.DataSource = new[] { new { Id = 1, Date = DateTime.Now, MedicalType = new { Id = 1 }, IsHalfDay = false }, new { Id = 1, Date = DateTime.Now, MedicalType = new { Id = 1 }, IsHalfDay = false } };
this.CurrentHourList.DataBind();
Is it possible that the binding error is coming from a different control (ie. not inside of the listview?)
If you need to use declarative databinding on a control or property which doesn't support it, you can also look into building your own custom expression builder.

Categories