Setting Navigation url to hyperlink dynamically - c#

Im trying to set navigation url to a hyperlink which is inside a gridview.
Im creating the table inside the gridview using a literal in backend c# code.
The code now look like inside GridviewRowDataBound(object sender, GridViewRowEventArgs e)
Literal.Text += "<asp:HyperLink ID='hlContact' runat='server' NavigateUrl='#'>Contact </asp:HyperLink>";
I want to set the navidation inside this code
If anyone have an idea it will be helpful
Thanks

You should just create a HyperLink control, instead of trying to add one to a literal:
HyperLink lnk = new HyperLink();
lnk.Text = "Hello World!";
lnk.NavigateUrl = "~/somefolder/somepage.aspx";
e.Row.Cells[0].Controls.Add(lnk);
If your approach can work, you could try something like this:
Literal.Text += String.Format("<asp:HyperLink ID=\"hlContact\" runat=\"server\" NavigateUrl=\"{0}\">Contact</asp:HyperLink>", navigationUrl);
If you want to use a Literal control though, I would do something like this instead:
Literal.Text += String.Format("Contact", navigationUrl);

If you are just trying to simply databind a HyperLink field in a GridView with a bound field, you can use a TemplateField. Here is an example to do it up front and not the hassle of adding it in the code behind.
<asp:TemplateField HeaderText="Contact" SortExpression="LastName, FirstName">
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%# String.Format("~/Page.aspx?ID={0}", Eval("CustID").ToString()) %>'>Contact</asp:HyperLink>)
</ItemTemplate>
</asp:TemplateField>

When we writing html content to the literal, it won't picking up the asp hyperlink correctly. But when I used the normal “a” tag, it taking the redirection path correctly.
literal.Text += "a ID='linkcontact' runat='server' href='" + "www.website./pagename.aspx?ID=" + id + "'>contact</a>";

for make a menu and submenu code c#. with variables and navigateurl is of form next
<asp:Menu ID="NavigationMenu" runat="server" CssClass="menu" EnableViewState="false" IncludeStyleBlock="false" Orientation="Horizontal">
<Items>
<asp:MenuItem>
<asp:MenuItem></asp:MenuItem>
<asp:MenuItem></asp:MenuItem>
</asp:MenuItem>
</Items>
</asp:Menu>
NavigationMenu.Items[0].Text = "xxxxxx"; name of menu
MenuItem menu = NavigationMenu.Items[0];
MenuItem submenu = new MenuItem("xxxxxx"); //name of submenu
submenu.NavigateUrl = "~/Main/xxxxx.aspx?id=" + id + "";
MenuItem submenu1 = new MenuItem("xxxxxxx");//name of sumbenu1
submenu1.NavigateUrl = "~/Main/xxxxxxx.aspx?id=" + id + "";
menu.ChildItems.Add(submenu);
menu.ChildItems.Add(submenu1);

Related

How to use new window instead of new tab display gridview data on click event in .net?

Here is my code:
Response.Write("window.open('loginfo.aspx?id=" + btn.CommandArgument
"','height=200,width=200,alwaysRaised=yes')");
But still it didn't work as new window instead of new tab.
Now I got like shows data in gridview in new tab, but I need to show like new window.
For that what should I do?
update:
<asp:TemplateField HeaderText="Log Info">
<ItemTemplate>
<asp:Button runat="server" ID="btnloginfo" Text="Log-Info" CommandArgument='<%# Eval("Book_id") %>' Onclick="loginfo_click"/>
</ItemTemplate>
<ControlStyle BackColor="#FF0066" ForeColor="White" />
</asp:TemplateField>
cs:
protected void loginfo_click(Object sender, EventArgs e)
{
Button btn = (Button)(sender);
ScriptManager.RegisterStartupScript(
this,
GetType(),
"OPEN_WINDOW",
"window.open('loginfo.aspx?id=" + btn.CommandArgument + "','height=200,width=200,alwaysRaised=yes')",true);
}
You need to add script> tags and _blank to open it in new window:
Response.Write("<script>window.open('WebForm2.aspx?id=" + btn.CommandArgument + "','_blank', 'height=200,width=200,alwaysRaised=yes')</script>");
I suggest you to use FancyBox : GitHub
this is example result on my project...
I need to help you but i not have mor time , sorry !

Href Link Code Behind

I am trying to add a a link as part of the Product.Text but I've horribly got it wrong here, doing this on the C-Sharp code behind.
tcProduct.Text = "<div class=\"productname\">" + "<a class=\"productnameLink\" href=\"item.Product.Url\">" + item.Product.Name + "</a>" + "</div>";
The backward slashes are beginning to confuse me. Instead of a normal hyperlink i guess i should be using the .NET hyperlink instead??
I've tried this but doesn't add the hyperlink;
HyperLink productNameLink = new HyperLink();
productNameLink.Text = "<div class=\"productname\">" + item.Product.Name + "</div>";
productNameLink.NavigateUrl = item.Product.Url.ToString();
productNameLink.CssClass = "prodNameLink";
tcProduct.Controls.Add(productNameLink);
Plain string formatting should do the trick:
tcProduct.Text = string.Format("<div class=\"productname\"><a class=\"productnameLink\" href=\"{0}\">{1}</a></div>",
item.Product.Url, item.Product.Name);
However, you really better use a Repeater which is meant exactly for such things. Markup:
<asp:Repeater ID="rptProducts" runat="server">
<HeaderTemplate><h1>Products</h1></HeaderTemplate>
<ItemTemplate>
<div class="productname"><a class="productnameLink" href="<%# Eval("Url") %>"><%# Eval("Name") %></a></div>
</ItemTemplate>
</asp:Repeater>
And in the code behind:
rptProducts.DataSource = arrProducts;
rptProducts.DataBind();
Where arrProducts is the collection of your products.
What i used to do that is ASP Literal.
<asp:Literal ID="Literal2" runat="server"></asp:Literal>
Then in the code set to it with
Literal2.Text = "<a class='productnameLink' href=" + item.Product.Url + ">" + item.Product.Name + "</a>"
You can use Panel control which renders as div.
var link = new HyperLink
{
Text = item.Product.Name,
NavigateUrl = item.Product.Url.ToString(),
CssClass = "prodNameLink"
};
var panel = new Panel
{
CssClass = "productname"
};
panel.Controls.Add(link);
tcProduct.Controls.Add(panel);
Output:
<div class="productname">
<a class="prodNameLink" href="http://www.google.com">Google</a>
</div>
The Text property is supposed to be text only.
Many ways to do what you need to, but if you want to stick to using html string you could use:
tcProduct.Controls.Add(new HtmlGenericControl
{
InnerHtml = string.Format(#"<div class=""productname""><a class=""productnameLink"" href=""{0}"">{1}</a></div>", item.Product.Url, item.Product.Name )
});
Bonus, you can get rid of the '\' escape char with averbatim string literal: #"" (you need to double the quotes).

cross page posting asp.net not returning values

I have a web form as
<asp:TextBox ID="txtname" runat="server" Text="Post on Next Page"/>
<asp:Button ID="btn1" runat="server" PostBackUrl="~/Page2.aspx" Text="Post on next page" />
Now on Page2.aspx the code-behind is as follows:
protected void Page_Load(object sender, EventArgs e)
{
if(PreviousPage!=null && PreviousPage.IsCrossPagePostBack)
{
TextBox txt1 = (TextBox)PreviousPage.FindControl("txtname");
label1.Text = "Value: " + txt1.Text;
}
}
I end up getting the error object reference not set to instance of an object for txt1
Where label1 is a label used to display the output. However, the value is not displayed.
What step am i missing?
Try this
if (PreviousPage != null && PreviousPage.IsCrossPagePostBack)
{
//get the content place holder from master page of your previous page where your controls are placed
//In this code the txtname textbox is placed inside ContentPlaceHolderID="MainContent"
var cp =PreviousPage.Master.FindControl("MainContent") as ContentPlaceHolder;
//find the textbox inside content place holder from previous page
TextBox txt1 = cp.FindControl("txtname") as TextBox;
label1.Text = "Value: " + txt1.Text;
}
Are you sure that PostBackURL is valid on a Textbox? Normally this attribute is attached to something that submits, such as a Button or LinkButton, eg:
<form runat="server">
Name:<asp:textbox id="TextBox1" runat=Server />
<asp:button id="Button1" Text="Submit"
PostBackUrl="demo_postbackurl.aspx" runat="Server" />
</form>
Edit: Aha! - you do use a button.
Your code looks OK to me.
If the TextBox is within another control FindControl might not find it - if (for example) it's within a Panel you would need to do something like
TextBox txt1 = (TextBox)PreviousPage.MyPanel.FindControl("txtname");
If it's not within another control then I'm afraid I don't know.

write the same code from aspx page to behind code in the cs page

is there a way to write this code from an aspx page
to a behind code of the aspx page (cs), in asp.net.
<a rel="lightbox" id="userImageLightBox" runat="server" title="profile image">
<img id="userImage" runat="server" width="150" height="146" alt="" src=""/>
</a>
for example if i have the code in apsx:
<asp:Label ID="pageProfileHeadName" runat="server" Visible="true"/>
in the behind code i can do:
Label label = new Label();
label.ID = "pageProfileHeadName";
label.Visible = true;
thanks
Short answer - yes - a hyperlink control renders as <a> so you could do this:
Hyperlink a = new Hyperlink();
a.ID = "userImageLightBox";
See the MSDN regarding this server control:
http://msdn.microsoft.com/en-us/library/k0b15efk(v=vs.71).aspx
Anytime a control is runat=server this means you will be able to access it from the aspx code behind page (.cs, .vb, etc). So if you ever want to change a specific property, such as the NavigateURL property you could do so.
a.NavigateURL = "someURL";
Since you have already set the runat="server" attribute, you can access the HTML controls in your code-behind through its id:
// *.aspx:
<a id="userImageLightBox" runat="server" ...>
<img id="userImage" runat="server" ... />
</a>
// code-behind:
userImageLightBox.Title = "New Title";
userImage.Src = "~/images/profile.png";
// To get or set an attribute like `rel`:
userImageLightBox.Attributes["rel"] = "test";
Update: If you want to create the HTML from the code-behind, you can do as JonH wrote:
HyperLink a = new HyperLink();
a.ID = "userImageLightBox";
a.Attributes["rel"] = "lightbox";
Image img = new Image();
img.ID = "userImage";
img.ImageUrl = "img.png";
img.Width = 150;
img.Height = 146;
a.Controls.Add(img);
Oh, and please increase your accept rate.

Retrieve a TextBox using JavaScript

I have a GirdView in Edit Mode with inside a TextBox.
I need to Retrieve this TextBox with ID (from the source code in the browser) in JavaScript.
ctl00$MainContent$uxListOptions$ctl02$uxValueInput
But I receive an error because my JavaScript is not able to find the TextBox.
Here is the code:
<span onclick="encodeMyHtml('<%# UniqueID.Replace("$", "_") %>_FormViewContentManager_ContentTextBox')">
<asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True" CommandName="Update" Text="[Publish]" />
</span>
In my control’s OnPageLoad I call this:
private void addEditorJavaScript()
{
// create our HTML encoder javascript function
// this way it shows up once per page that the control is on
string scr = #"<script type='text/javascript'>function encodeMyHtml(name){
var content = document.getElementById(name).value
content = content.replace(/</g,'<');
content = content.replace(/>/g,'>');
document.getElementById(name).value = content;
}</script>";
// add the javascript into the Page
ClientScriptManager cm = Page.ClientScript;
cm.RegisterClientScriptBlock(this.GetType(), "GlobalJavascript", scr);
}
I am trying to use this code http://dustyreagan.com/how-to-submit-html-without-disabling/
Any Idea what am I doing wrong? Thanks guys!
If you are using ASP.Net 4.0, you could use ClientIdMode=Static or Predictable for this control.
encodeMyHtml('<%# UniqueID.Replace("$", "_") %>_FormViewContentManager_ContentTextBox')
This will result in
encodeMyHtml('ctl00_MainContent_uxListOptions_ctl02_uxValueInput_FormViewContentManager_ContentTextBox')
Does a control of that ID exist in your DOM?
It seems that you're making a lot of assumptions as to how the ID's will be created. It would be better to immediately reference the ContentTextBox.ClientID.
Something like the following, provided that ContentTextBox is a valid reference to the text box:
encodeMyHtml('<%# ContentTextBox.ClientID %>')
You can define your grid like this :
<div>
<asp:GridView ID="GridView1" runat="server" Width = "550px"
AutoGenerateColumns = "false" Font-Names = "Calibri"
Font-Size = "12pt" HeaderStyle-BackColor = "LightYellow" AllowPaging ="true" ShowFooter = "true" OnPageIndexChanging = "OnPaging" PageSize = "10" >
<Columns>
<asp:TemplateField ItemStyle-Width = "100px" HeaderText = "Name">
<ItemTemplate>
<asp:TextBox ID="txtPeriod" runat="server" CssClass="css1 mycss" Text='<%# Eval("Period")%>'
onblur="SetPostingPeriod(this)"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<AlternatingRowStyle BackColor="#C2D69B" />
</asp:GridView>
</div>
And your Javascript Function Would be :
<script language="javascript" type="text/javascript">
/* Populating same data to all the textboxes inside grid,
once change of text for one textbox - by using jquery
*/
function SetPostingPeriod(obj) {
var cntNbr = $("#" + obj.id).val();
// var cntNbr = document.getElementById(obj.id).value;
// alert(cntNbr);
//Access Grid element by using name selector
$("#<%=GridView1.ClientID %> input[name*='txtPeriod']").each(function (index) {
if ($.trim($(this).val()) != "")
if (!isNaN($(this).val())) {
$(this).val(cntNbr);
}
});
}
</script>
This Javascript function is called onblur event of the textbox.
When this function is called at the same time it passes a parameter
which is nothing but the textbox id.
Inside javascript function by using the parameter which is the
id of the textbox we are getting the vaue.
Here is the code :
var cntNbr = $("#" + obj.id).val();
Then For each of the "txtPeriod" controls available inside the grid, we need to assign
the value of current "txtPeriod" textbox value to them.
Looping Grid to identify each "txtPeriod" available :
Here is the code :
$("#<%=GridView1.ClientID %> input[name*='txtPeriod']").each(function (index) {
});
Inside this loop we need to assign the "txtPeriod"(current/Modified) value to other
"txtPeriod" textboxes.Before assign its good practice to check is it null or NAN.
Here is the code :
if ($.trim($(this).val()) != "")
if (!isNaN($(this).val())) {
$(this).val(cntNbr);
}

Categories