C# Change dynamically NavigateUrl HyperLinkField - c#

In my code i create a HyperLinkField object. Depending on a database field value, i want to set the NavigateUrl property. This is my problem, i don't know how.
With:
objHF.DataNavigateUrlFields = new[] { "id", "Stype" };
i get my database field. Now i want to check the Stype value. Depeding on this value i want to set the page where to navigate to. How can i do this??
At the end i set my datasource to the gridview and after that i call the bind() method.
I hope someone can help me out

Make the HyperLinkField a TemplateField, and set the NavigateUrl of the resulting HyperLink (in markup) to something like
<%# myUrlFunction(Eval("id"), Eval("stype")) %>
Next create a corresponding function in the .cs file:
private string myUrlFunction(object id, object stype)
{
return "mypagename.aspx?whatever=" + id.ToString() +
"&youwanttodo=" + stype.ToString();
}

try this way
<%# this.myUrlFunction(Eval("id"), Eval("stype")) %>
this is worked

Related

Is there an ASP.NET databindable control (like Repeater), which only expects a single item?

I'm trying display lots of properties from a business object on a Web Form. I could of course, create loads of labels and assign all the values in code-behind, but I feel there must be a less verbose way.
What I want is something like an asp:Panel but where you can specify a datasource. It doesn't seem like Panels support any kind of databinding.
What I'd like is something like this
// C#
panel.DataSource = theCompany;
panel.DataBind();
Then:
// ASPX
<asp:Panel runat="server">
Name: <%# Eval("Name") %>
Phone: <%# Eval("Phone") %>
...
</asp:Panel>
..but I can't find anything which will allow me to work in this way.
I thought I might be able to use asp:FormView but this just gives the error "Data source is an invalid type. It must be either an IListSource, IEnumerable, or IDataSource."
A caveat is that I do not want to call a global DataBind() (this has caused us no-end of problems in the past) - I would like the databind to be constrained to a particular part of the page.
It seems you can do this using a Panel, but you have to assign your business object to a page property first, as there's no way to set the business object as a "DataSource" for the panel (as you would for a Repeater control, for instance).
Once the object is assigned as a page property, you can then use the following syntax in the .aspx to access the properties of that object, without needing to manually assign each item to control values in code behind:
<%# Company.Name %>
You don't need to databind (although you can). What you need is a simple expression evaluator. Add a property to your code behind like this
public string Test { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
Test = "<script>alert('test');</script>";
}
Then use it to render code directly to the page like this
The value: <%: Test %>
Note that the <%: syntax escapes the input. If you wish to NOT escape the input then you can use <%= syntax. Note that you don't need to have a string object you can access any properties you like for example
The value lenght: <%: Test.Length %>
Use The below:
<asp:DetailsView runat="server">
Name: <%# Eval("Name") %>
Phone: <%# Eval("Phone") %>
</asp:DetailsView>
Use DetailsView. You can add it from the Toolbox. It's for Single Row Data Presentation.
<asp:DetailsView runat="server">
Name: <%# Eval("Name") %>
Phone: <%# Eval("Phone") %>
</asp:DetailsView>
Why not using DetailsView. Its perfect for what you want. Showing single row of data only and that too in two column form.
I suggest using a standard Repeater, databound with an array containing a single item.
Repeater.DataSource = new [] { theCompany };
Repeater.DataBind();
Advantage over databinding to a Panel: you can still use the ItemType attribute, and have access to the nice strongly typed Item object and don't have to go about using Eval, i.e.:
<asp:Repeater runat="server" Id="Repeater" ItemType="CompanyViewModel">
<ItemTemplate>
Name: <%# Item.Name %>
Phone: <%# Item.Phone %>
</ItemTemplate>
</asp:Repeater>
(Replace "CompanyViewModel" with the Type of your: "theCompany".)
You can also try experimenting with DetailsView, but it's not as malleable as a Repeater.
Create your own user control that shows the properties of the objects. You can use reflection to read property names and values and display in control.
Create a property for your object in your user control. Inside user control code behind write function Show() with below code.
//Build html strin from all propeties
PropertyInfo[] properties = yourObject.GetType().GetProperties();
string lbl = "<label>{0}</label>";
string value= "<span>{0}</span>";
string tab ="\t";
StringBuilder sb = new StringBuilder();
foreach (PropertyInfo pi in properties)
{
var label = string.Format(lbl,pi.Name);
var val = string.Format(value, pi.GetValue(yourObject, null))
sb.Append(label+tab+val);
sb.Append("<br/>")
}
Response.Write(sb.ToString());
Now in your pager add that control and sets its object property in code behind like
myControl.MyObject = yourObject;
myControl.Show();
NickG's answer will work... however consider two scenarios.
If your business object is ever null, the page will crash with an "Object Reference" error. This can be avoided with a cumbersome looking
<% if(MyObject != null) { %><%= MyObject.Prop %><% } %>
... but doing that every time makes for messy code.
If your page uses PostBack processing via UpdatePanel, the business object will have to be reloaded to the property every time the Page lifecycle runs... even if that portion of the page isn't being redrawn. This is because IIS will resolve all the <%= MyObject.Prop %> references regardless, causing wasted CPU cycles and probably wasted database calls if your object is coming from a database.
For these reasons I always use a Repeater control, which is lightweight, supports ViewState, can easily be assigned a one item list, and avoids the aforementioned issues. Here's an example using the HttpContext.Current.Request object as a "business object".
<asp:Repeater ID="rptTest" runat="server">
<ItemTemplate>
Request.URL = <%# Eval("Url") %>
</ItemTemplate>
</asp:Repeater>
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
var objTest = Request; //Using the Request object as a test business object
rptTest.DataSource = new List<System.Web.HttpRequest>() { objTest };
rptTest.DataBind();
}
}
To make this work we can customize ASP.NET Panel by inheriting it and using Custom Server control for ASP.NET
Use Below Code to modify the ASP.NET Panel in an ASP.NET Custom Server Control Project:
[DefaultProperty("Text")]
[ToolboxData("<{0}:CustomPanel runat=server></{0}:CustomPanel>")]
public class CustomPanel : Panel
{
[Bindable(true)]
public object MyDataSource
{
get;
set;
}
[Bindable(true)]
[Category("Appearance")]
[DefaultValue("")]
[Localizable(true)]
public StringBuilder Text
{
get;
set;
}
public void MyDataBind()
{
Text = new StringBuilder();
foreach (PropertyInfo p in MyDataSource.GetType().GetProperties())
{
Text.Append(string.Format("<b>{0}</b>", p.Name));
Text.Append(":");
if (p.GetIndexParameters() == null || p.GetIndexParameters().Length == 0)
Text.Append(p.GetValue(MyDataSource, null));
Text.Append("<br />");
}
}
protected override void RenderContents(HtmlTextWriter output)
{
output.Write(Text);
}
}
Then add this control's reference and toolbox item to your ASP.NET page:
<cc2:CustomPanel ID="MyCustomPanel" runat="server">
</cc2:CustomPanel>
Use the control as shown below:
MyCustomPanel.MyDataSource = theCompany;
MyCustomPanel.MyDataBind();

To use hidden field value in another aspx file

In the below code i have a hidden value in sample.ascx and i want to use that value in sample.aspx in its codebehind.pls help me to do this.
Sample.ascx
txthidd.Value = "Hai";
<asp:HiddenField ID="txthidd" runat="server" />
You can create a Public property in your ascx like this
public string txt
{
get
{
return this.txthidd.Value;
}
}
and can access this in aspx like this
string textOnAspx = UC_UserControl.txt;
In the codebehind, you should create a property getting the field:
public string TxtHidText{
get
{
return txthidd.Value;
}
}
Then, you'll reference it per the id, let's say you'll have something like this in ASPX:
<u1:Sample id="SomeSampleContentOfThePage" />
and in codebehind, it will be accessible via
var text = SomeSampleContentOfThePage.TxtHidText;
Note that if you want to set it from the other aspx, you should create a set part as well.

how can i pass the querystring into aspx

i have url like this : DossierSoin_Fiche.aspx?SoinId=1
how can i pass this SoinId into dx:ASPxPopupControl
<dx:ASPxPopupControl ID="ASPxPopupControl_Surveill"
ContentUrl="~/PopUp/Surveillance.aspx?SoinId=<%=SoinId %>" ?
thanks you in advance
PS : i can not use code behinde, because it will reload the page, then i will lost the data that have not save in database. I use callback instead, so i need pass this querystring value on aspx not in aspx.cs
In your containers codebehind:
protected string SoinId
{
get
{
return Request["SoinId"];
}
}
And use the code you have.
make a property "SoinID" (if you dont already have one)
protected string SoinId {get;set;}
(type of modifier is up to the OP, could also be public).
then, assign a value to the property in your page_load:
SoinId = Request.QueryString["SoinID"];
your .aspx code can stay the same if you use it like this.
Just pass the value to the public property in the CodeBehind of the page.
ASPxPopupControl_Surveill.ContentUrl = ...
[edit made with thanks to rs.]
Option A:
1) Declare a protected variable named SoinId in the scope of your aspx page.
2) In the Page_Load event, add this:
if(!Request.QueryString["SoinId"]==null)
{
SoinId = Request.QueryString["SoinId"];
}
Opetion B:
Replace your aspx code with this:
<dx:ASPxPopupControl ID="ASPxPopupControl_Surveill"
ContentUrl="~/PopUp/Surveillance.aspx?SoinId=<%=Request.QueryString["SoinId"] %>">
Edit: Consider using a property as other colleagues proposed. It's more ellegant.
I would imagine you could just assign the value in the code behind.
e.g.;
ASPxPopupControl_Surveill.ContentUrl = "~/PopUp/Surveillance.aspx?SoinId=" + Request["SoinId"].ToString();

Saving a value to and reading from the viewstate

I'm not too familiar with .NET, but I want to save a simple value (a number between 1 and 1000, which is the height of a particular div) to the viewstate and retrieve it when the update panel reloads (either in the markup somewhere or with javascript). What is the simplest way to do this?
This page gives me the following code:
string strColor;
if (Page.IsPostBack)
{
// Retrieve and display the property value.
strColor = (string)ViewState["color"];
Response.Write(strColor);
}
else
// Save the property value.
ViewState["color"] = "yellow";
However, I'm not totally clear on where or how to access the example strColor.
Since this is in the code behind, where will Response.Write even spit that code out? I couldn't find it when I tried this code. And how do I use javascript to set that value, instead of setting it in the code behind?
You can simply set the div as a server control as so:
<div id="yourdiv" runat="server" ...
And when the page posts back; simply set it's height by setting its attributes; for example:
yourDiv.Attributes("style","height:"+height_read_from_ViewState+"px;");
Or, you can store the height on the client side, using a Hidden field and reading that hidden field's value on the server side to set the div's height.
<asp:hiddenfield id="hdnHeight" runat="server" />
You set the height in Javascript as so:
function setHeight(value)
{
document.getElementById('<%=hdnHeight.ClientID').value=value;
}
And on post back on server side:
yourDiv.Attributes("style","height:"+hdnHeight.Value+"px;");
I would change strColor to a property and use the viewstate as a backing store for the propery.
public string strColor
{
get
{
return ViewState["strColor"];
}
set
{
ViewState["strColor"] = value;
}
}
And then you would use it like any other property:
if (Page.IsPostBack)
{
// Retrieve and display the property value.
Response.Write(strColor);
}
else
// Save the property value.
strColor = "yellow";

aspx change focus from different TextBoxes on the fly

I am trying to change the focus from one textbox to another while the character count in
on textbox reaches 13 I am using the code below with nothing happening whatsoever:
if (!this.ClientScript.IsClientScriptBlockRegistered("qtyFocus"))
{
this.ClientScript.RegisterClientScriptBlock(this.GetType(), "qtyFocus",
#"<script type='text/javascript' language='javascript'>function qtyFocus(){
var trckNumberLength = document.getElementById('txtTrackingNumber').value.length;
if(trckNumberLength == 13){
document.getElementById('txtQuantity').focus();
}}</script>");
}
txtTrackingNumber.Attributes.Add("onchange", "javascript:return qtyFocus();");
can anyone help please ?
Probably because the line in the script that's doing
var trckNumberLength = document.getElementById('txtTrackingNumber').value.length;
Needs to be changed for:
var trckNumberLength = document.getElementById('"+txtTrackingNumber.ClientID+"').value.length;
The reason being that txtTrackingNumber will very likely have a different Id when it's rendered on the page so you need to use the ClientID property of the control instead of the id you defined on the markup.

Categories