Hi anybody know how to use databinder.eval in c#
Actually I've tried this
LinkButton lnkName = new LinkButton();
lnkName.CommandArgument = DataBinder.Eval("object","<%#COURSE_ID%>");
it is showing error. Whats the wrong with this?
You can't use Eval in the code behind of an aspx page.
this:
lnkName.CommandArgument = DataBinder.Eval("object","<%#COURSE_ID%>");
should be this:
lnkName.CommandArgument = YOUR_OBJECT_PROPERTY_HERE;
To fill in YOUR_OBJECT_PROPERTY_HERE you either need to specify the object.property etc like normal in C# code, or you'll have to use reflection to get the property value from the object (which is what eval does for you).
Here is a link showing how to use reflection to get the property information from an object. You can use it to duplicate how eval works if you need to: https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-6099345.html
Link to DataBinder Eval Method: http://msdn.microsoft.com/en-us/library/4hx47hfe.aspx
How the DataBinder Eval Method works (and why the author thinks it should be avoided) http://weblogs.asp.net/jgalloway/archive/2005/09/20/425687.aspx
For Example in design page you can use like:
<asp:Button ID="btnEdit" CommandName="Edit"
CommandArgument='<%# DataBinder.Eval(Container, "RowIndex") %>'
CssClass="cursor_hand" runat="server" Text="Edit" />
Code Behind:
int rowIndex = int.Parse(e.CommandArgument.ToString());
if (e.CommandName.Equals("Edit"))
{
//do something
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowIndex > -1)
{
string h = DataBinder.Eval(e.Row.DataItem, "ColumnName").ToString();
}
}
You should use Eval expression and <% %> in *.aspx code not with C# code.
Related
can we pass multiple eval field in one command argument.
my code is here
<asp:TemplateField HeaderText="Details" SortExpression="source">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CommandArgument='<%#Eval("source") %>' CommandName="Download" Text='<%#Eval("source") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
I want to be pass many Eval field in single command argument with command name
if possible please show any reference.
If this is what you are asking as you didnt provide any code snippet i'm assuming like this
CommandArgument='<%#Eval("ScrapId")+","+ Eval("UserId")%>'
In code behind you can use retrieve values like this
protected void GridViews_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Comment")
{
string[] commandArgs = e.CommandArgument.ToString().Split(new char[] { ',' });
string scrapid = commandArgs[0];
string uid = commandArgs[1];
}
}
You can do something like
<%# Eval("Param1").ToString() + Eval("Param2").ToString() %>
with asp.net c# I get the code of a country with bind :
<asp:Label runat="server" Text='<%# Bind("h_country") %>' ID="Label1"></asp:Label>
this return code of country like usa, tr, eg, il.
I need to put if conditions and I try to do it like this:
<asp:Label runat="server" Text='<%# if(Bind("h_country")=="usa") resonse.write("United States"); %>' ID="Label1"></asp:Label>
note: I'm using GridView and template.
I tried alo at code behind to get the value of country like this:
String s = Lable1.Text;
but also not workes!
how can I get it as a variable and use if condition ?
You need to use find control if thus label is within the gridview and then get the sting from label.
You probably want to handle this in the code behind
<asp:Label runat="server" Text='<%# GetCountry(Eval("h_country")) %>' ID="Label1"></asp:Label>
code behind
public string GetCountry(object country)
{
if (county.ToString() == "usa")
return "United States";
}
It would be better if you had a lookup so you don't have to have a lot of if statements
This is how you can do conditional checks in the markup while binding. Try something like below but I would not advise doing this kind of conditional checks and response.write at the template level but do it in code behind.
<asp:Label runat="server" Text='<%# Bind("h_country") == "usa" ? "United States" : (string)Bind("h_country") %>' ID="Label1"></asp:Label>
And this is how you can do it at code behind. Use the databound event to find the Label1 and set the appropriate text in there.
You need to define OnRowDataBound="gvTest_DataBound for the gridview in the markup
protected void gvTest_DataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lblCountry = (Label)e.Row.FindControl("Label1");
if (lblCountry.text == "usa"){
// do something here
}
else {
// do something otherwise
}
}
}
In my aspx page, I have,
<asp:ListView ID="listview1" runat="server" DataSourceID="dtasrc_load">
<ItemTemplate>
<h4>
<asp:Label ID="lbl_titlename" runat="server" Text='<%#Eval("abt_vch_Title") %>'></asp:Label>
</h4>
<asp:LinkButton runat="server" OnClick="Content_Load" class="btn">Edit</asp:LinkButton>
<asp:HiddenField ID="hiddenID" runat="server" Value='<%#Eval("abt_int_ID") %>' />
</ItemTemplate>
</asp:ListView>
I need to access the value in the hidden field control so that I can pass that value to the database on the linkbutton click event. Below is where I've gotten so far.
protected void Content_Load(object sender, EventArgs e)
{
HiddenField hd = new HiddenField();
HiddenField myhiddenfield = new HiddenField();
myhiddenfield = (HiddenField)listview1.FindControl("hiddenID");
int myID = Convert.ToInt32(myhiddenfield.Value);
I get a run-time error as "Object not referenced to instance of an object". The value seems to be null.
Can anyone tell me why I am getting this? What should I do?
give your linkbutton an id
<asp:LinkButton runat="server" OnClick="Content_Load" class="btn"
id="editlinkbutton">Edit</asp:LinkButton>
and change your code to this
protected void Content_Load(object sender, EventArgs e)
{
LinkButton editlinkbutton = sender as LinkButton;
HiddenField myhiddenfield = editlinkbutton.NamingContainer.FindControl("hiddenID") as HiddenField;
int myID = Convert.ToInt32(myhiddenfield.Value);
}
edit: maybe linkbutton doesnt have to have an id, not sure. my linkbuttons usually have id's :)
I recently had a similar issue. Try not to look for System.Web.UI.WebControls.HiddenField, but rather for System.Web.UI.HtmlControls.HtmlInputHidden-class, here.
Additionally, you should be more cautious, rather use
System.Web.UI.HtmlControls.HtmlInputHidden hi =
listview1.FindControl("hiddenID") as ystem.Web.UI.HtmlControls.HtmlInputHidden;
if(hi != null)
...
I have two repeaters that looks like this :
Arrange By: Name | Age | Area
what I want to do now is to populate the second repeater from the database with the alphabet, and if the age was clicked then the second repeater gets populated from the database with some age ranges!
I already implemented my idea by placing a hyperlink in the first repeater, that passes -using it's NavigateUrl property- a url for the same page but with some querystring values!
I've been told that querystrings are used for passing values from one page to another, not the same page...and also I wanted to use some AJAX (script manager and update panel) but turns out that I have to use some server control within my repeater instead of html controls so it could be able to post back to the server
I hope you'd help me with a good implementation for passing the value from repeater1 to repeater2 and if you think that I've stated anything wrong Please Corret Me!
Thanks in advance :)
EDIT
my.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
string commandString1 = "SELECT [arrange_by_id], [arrange_by] FROM [arrange_by]";
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["testConnectionString"].ConnectionString))
{
using (SqlCommand cm = new SqlCommand(commandString1, cn))
{
cn.Open();
using (SqlDataReader dr = cm.ExecuteReader())
{
ArrangeBy_rpt.DataSource = dr;
ArrangeBy_rpt.DataBind();
}
}
}
}
void arrange_lnkbtn_command(object sender, CommandEventArgs e)
{
Label1.Text = (e.CommandArgument).ToString();
}
my.aspx
<asp:Repeater ID="ArrangeBy_rpt" runat="server">
<ItemTemplate>
<asp:LinkButton id="arrange_lnkbtn" OnCommand="arrange_lnkbtn_command" CommandArgument='<%#Eval("arrange_by_id") %>' runat="server">
<%# Eval("arrange_by") %>
</asp:LinkButton>
</ItemTemplate>
<SeparatorTemplate> | </SeparatorTemplate>
</asp:Repeater>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
Compilation Error
Compiler Error Message: CS1061: 'ASP.sortingcontrol_ascx' does not contain a definition for 'arrange_lnkbtn_command' and no extension method 'arrange_lnkbtn_command' accepting a first argument of type 'ASP.sortingcontrol_ascx' could be found (are you missing a using directive or an assembly reference?)
Line 4: <asp:Repeater ID="ArrangeBy_rpt" runat="server">
Line 5: <ItemTemplate>
Line 6: <asp:LinkButton id="arrange_lnkbtn" OnCommand="arrange_lnkbtn_command" CommandArgument='<%#Eval("arrange_by_id") %>' runat="server">
Line 7: <%# Eval("arrange_by") %>
Line 8: </asp:LinkButton>
There's nothing wrong per se with passing data to the same page using the querystring, though it shouldn't be used for sensitive data that the user might change by "hacking" the URL. However, it's not the standard way of doing things in ASP.NET WebForms, since it won't postback the values of any other controls on the page (and hence they won't retain their state without you manually having to re-populate them on every page load). But if this is not a problem for you, feel free to stick with querystring.
Howecer, generally you would use a server-side control like an asp:Button or an asp:LinkButton and then handle their OnClick event. However, to pass data with one you can use the CommandName and CommandArgument properties of the button and then handle the OnCommand event.
<asp:LinkButton id="LinkButton1"
Text="Click Me"
CommandName="Age"
CommandArgument="18"
OnCommand="LinkButton_Command"
runat="server"/>
In code-behind:
void LinkButton_Command(Object sender, CommandEventArgs e)
{
var data = GetData(e.commandArgument); // implement a method that gets your data filtered by the argument passed from the button
Repeater2.DataSource = data;
Repeater2.DataBind();
}
I like to handle and compare a lot of date times in my repeater even I have to work more than one time with the same.
It's a bit ugly, to cast everywhere the Eval("MyDate") like ((DateTime)Eval("MyDate")) to substract 2 datetimes or to compare it, even if you have to do this more than in one operation.
I thought of saving all the evals in a var at start of the repeater?
DateTime mydt1 = Eval("myDate");
DateTime mydt2 = Eval("mydate");
after that, it's easy to do any operations in the whole repeater. Hope you understand my idea. Is this possible? I tried short but everytime errors.
mydt1 - mydt2....
Thank you and best regards.
You could call a method on the code behind page from the repeater using the DateTimes as arguments. The casting logic can be done in the code behind if the goal it to create a cleaner looking aspx page.
Example ASPX:
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<asp:Literal
ID="Literal1"
runat="server"
Text='<%# DateFoo(Eval("myDate1"), Eval("myDate2")) %>' />
</ItemTemplate>
</asp:Repeater>
Example C# code behind:
protected string DateFoo(Object o1, Object o2)
{
DateTime? dt1 = o1 as DateTime?;
DateTime? dt2 = o2 as DateTime?;
// Do logic with DateTimes
return "string";
}
If you want to add more logic to your repeater I would suggest you move the binding logic to the code behind:
ASPX:
<asp:Repeater id="myRepeater" runat="server">
<ItemTemplate>
<asp:Literal id="myLiteral" runat="server" />
</ItemTemplate>
</asp:Repater>
CS:
protected override void OnInit(EventArgs e)
{
myRepeater.ItemDataBound += myRepeater_ItemDataBound;
base.OnInit(e);
}
void myRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
// this method will be invoked once for every item that is data bound
// this check makes sure you're not in a header or a footer
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
// this is the single item being data bound, for instance, a user, if
// the data source is a List<User>
User user = (User) e.Item.DataItem;
// e.Item is your item, here you can find the controls in your template
Literal myLiteral = (Literal) e.Item.FindControl("myLiteral");
myLiteral.Text = user.Username + ", " + user.LastLoginDate.ToShortDateString();
// you can add any amount of logic here
// if you need to use it, e.Item.ItemIndex will tell you what index you're at
}
}
I hate evals with a passion.
This is why I use this code to be rid of them forever and go back to strong typing:
public static class DataItemExtensions
{
public static T As<T>(this IDataItemContainer repeater) where T : class
{
return (T)repeater.DataItem;
}
public static dynamic AsDynamic(this IDataItemContainer repeater)
{
return repeater.DataItem;
}
}
Then use it like this:
<asp:Repeater runat="server" DataSource="<%# this.MyObjectCollection %>">
<ItemTemplate>
<%# Container.As<MyObject>().DateTime %>
</ItemTemplate>
</asp:Repeater>
Note that if you use the Datasource like I did, you need to use this.DataBind() on the page.