hyperlink in gridview - asp.net

I have a hyperlink in a gridview which I want users to click on and it directs them to a particular page and also either passes in the first field of the gridview (the ID) or holds it in session, preferebly in session.
The link is just static text so no matter what record they click on i want to get them to the same page, but with that records ID available.
Just not sure how to add this to the NavigateUrl of the hyperlink.
ANy hints appreciated, thanks

You can easily generate the URL in the markup of your GridView without resorting to code. What you need to do is:
In the DataNavigateUrlFields
property of your HyperLinkField, put
the name of the column that contains
your id.
In the
DataNavigateUrlFormatString, put the
path to your page, plus the
querystring that the next page will
use to get the id, but where the
value should go, put {0} instead.
e.g.
<asp:Hyperlink DataNavigateUrlFields="ProductId" DataNavigateUrlFormatString="details.aspx?id={0} />
When the control is rendered at runtime, you will find that for each row, the {0} is replaced by the value of the ProductId column.
See String.Format and DataNavigateUrlFormatString for more details.

You can handle the Row_DataBound event to find the hyperlink control and update the NavigateUrl property.
You can add simple html control Text to link, it will produce same html.

Use HyperLink control and then write an event handler function for RowDataBound event, like this:
protected void OnRowDataBound(object source, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
HyperLink hyperLink = e.Row.FindControl("hyperLinkID") as HyperLink;
// example, adjust this to your needs.
hyperLink.NavigateUrl = "~/detail.aspx?id=" + DataBinder.Eval(e.Row.DataItem, "ID");
}
}

Not sure why you have taken server control instead of tag of HTML.
two ways you can do it.
1)if it is an static link just prefix the page name and append the id in mark up.
for ex
<a href='myPage.aspx<%#Eval("YourID")%>'><strong>Click me to navigate</strong></a>
2)give some id to the a tag and make it runat server handle the data bound event and bind the value to it.
protected void MyGridview_ItemDataBound(object sender, ListViewItemEventArgs e)
{
HtmlAnchor AncImage = e.Item.FindControl("AncImage") as HtmlAnchor;
AncImage.href="myPage.aspx"/id=" + DataBinder.Eval(e.Row.DataItem, "ID"); ;
//the id is the value that you want to append for redirection
}

Related

FormView insert hidden parameters based on dropdownlist selection

I have a FormView which I populate using SqlDataSource1. I do databinding like:
Text='<%# Bind("EffectiveDate") %>'
FormView also contain a dropdownlist with a custom SqldataSource2. Dropdown list contains list of cities. User is able to change a value in dropdown.
Once I submit a form I have to send to PowerShell script some parameters which I supposed to hide like street, ZipCode, etc... On first form load I can bind this parameters to hidden fields from SqlDataSource1. But if user change a value in dropdownlist I have to rebind parameters. Have no idea yet how.
Thanks!
You can configure the drop down list to do a post back.
AutoPostBack="true"
and then on Page Load or Selection changed event you can set up the hidden field.
Example:
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
hfSomething.Value = ddlSomething.SelectedValue;
}
else
{
//data binding code
}
}

Access dynamically generated control from code behind

I load a piece of html which contains something like:
<em> < input type="text" value="Untitled" name="ViewTitle" id="ViewTitle" runat="server"> </em>
into my control. The html is user defined, do please do not ask me to add them statically on the aspx page.
On my page, I have a placeholder and I can use
LiteralControl target = new LiteralControl ();
// html string contains user-defined controls
target.text = htmlstring
to render it property. My problem is, since its a html piece, even if i know the input box's id, i cannot access it using FindControl("ViewTitle") (it will just return null) because its rendered as a text into a Literal control and all the input controls were not added to the container's control collections. I definitely can use Request.Form["ViewTitle"] to access its value, but how can I set its value?
Jupaol's method is the prefer way of adding dynamic control to a page.
If you want to insert string, you can use ParseControl.
However, it doesn't cause compilation for some controls such as PlaceHolder.
Your process is wrong, you are rendering a control to the client with the attribute: runat="server"
This attribute only works if the control was processed by the server, you are just rendering as is
Since your goal is to add a TextBox (correct me if I'm wrong), then why don't you just add a new TextBox to the form's controls collection???
Something like this:
protected void Page_Init(object sender, EventArgs e)
{
var textbox = new TextBox { ID="myTextBoxID", Text="Some initial value" };
this.myPlaceHolder.Controls.Add(textbox);
}
And to retrieve it:
var myDynamicTextBox = this.FindControl("myTextBoxID") as TextBox;
I have created several working examples and they are online on my GitHub site, feel free to browse the code

How to find the HtmlInputCheckBox of a repeater control in code behind file without using runat ="server" tag

Inside repeater i have a html checkbox , now i want to access this checkbox in code behind file to check whether the checkbox is checked or not. but i dont want to user runat="server" tag , how can i do this my code as above
<input id="cbfdgroup" class="checkitem" type="checkbox" name="fd_cb_group[]" value='<%#Eval("FoodItemsUid") %>'>
in code behind file i am trying to access like this
foreach (RepeaterItem ri in rptMenu.Items)
{
if (ri.ItemType == ListItemType.Item || ri.ItemType == ListItemType.AlternatingItem)
{
HtmlInputCheckBox chk = (HtmlInputCheckBox)ri.FindControl("cbfdgroup");
if (chk.Checked)
{
}
}
}
but this is giving error as object referrence is not set to instance of an object.. how should i get this control in code behind file without using runat = "server" tag
It is not possible. To clarify, the runat="server" portion is doing just what it says. It is saying that this control should be made available and accessible to the server.
Code which is in the code-behind is code which is running on/executed by the server. So logistically, if the control is not made available to the server, the it cannot be manipulated by code (hence when it will not show up in intellisense either.)
I don't believe what you are asking is possible. runat=server is what makes controls available to the code behind. If you remove that attribute, your code behind is simply not aware of the control in any way.
A little bit more explanation:
The codebehind executes on the server. Therefore, any control you want to access in your codebehind must have runat=server in order to be available. The two are inseparable.
you don't need to read the items from repeater
assuming that you are sending a postback to the server (http post)
you can read the selected checkbox by simply:
string x = Request["fd_cb_group[]"];
it is more than 1 it will separate by comma, just use split the get a list of string of selected values.
the whole thing would be something like that:
protected void Button1_Click(object sender, EventArgs e)
{
string x = Request["fd_cb_group[]"];
string[] allSelectedOnes = x.Split(',');
foreach(string item in allSelectedOnes)
{
//your custom code for the selected checkboxes
}
}

Postback From Controls inside Composite Web Control

Let's say we have a composite web control with a combobox and a textbox. Is it possible to build into the control functionality such that when the text in the textbox changes, it posts back and adds the value as an option in the combobox?
I know that I could add an "onchange" handler to the textbox and make something work with Javascript, but that's not really what I'm looking to do. Is there a way to just put like:
Protected Sub txt1_TextChanged(sender As Object, e As System.EventArgs) Handles txt1.TextChanged
combo1.items.add(txt1.Text)
End Sub
in the web control code and it connect to the TextChanged event of the textbox?
In short yes, you should be able to do this.
I don't know what syntax you need for VB, but I have done similar things multiple times in C#. For C# you would add the name of the even handler to the markup of your text box, and set auto postback on the text box to true. Then the code behind event handler does what ever work you need it to.
As a rule I also define a custom event on the web control, and have the event handler for the textbox raise this custome event as well. This gives the option of letting the page that is using the control act on the event as well.
EDIT:
Here is an example with a DropDownList, it was part of a control to look up users within a set of Active Directory domains. If the user changed what domain they had selected we wanted it to search for the previously entered values on the new domain.
Mark-up:
<asp:DropDownList ID="ddl_Domain" runat="server" onselectedindexchanged="ddl_Domain_SelectedIndexChanged" AutoPostBack="True"></asp:DropDownList>
Code behind:
protected void ddl_Domain_SelectedIndexChanged(object sender, EventArgs e)
{
if (UserID != "" || LastName != "" || FirstName != "" || EmailAddress != "")
{
lnk_Find_Click(sender, e);
}
}
Or in the case where I have added a child control dynamically through code I have used this syntax:
DropDownList ddl = new DropDownList();
ddl.ID = "ddl";
ddl.DataTextField = "Text";
ddl.DataValueField = "Value";
ddl.SelectedIndexChanged += This_SelectedValue_Changed;
ddl.AutoPostBack = true;
As I said, I am not sure how to make this work with the Handles syntax of VB but it should be possible.

Forward a form submission in asp.net

I have a HTML webform (NOT asp.net webform) that submits its form to an aspx script.
On the aspx script, I'd like to simply forward the form submission to a different form processing script. (after checking just one or two things using Request.Form["variable"])
What is the simplest way to forward the original html page's form submission?
Currently:
html1 -> aspx1 -> html2
Desired:
html1 -> aspx1 -> aspx2 -> html2
I would attempt to solve this problem in the following fashion
Create a Repeater
Set the Request.Form as the datasource of the repeater. If this does not work, i would convert Request.Form into a suitable datastructure, such as a Dictionary or Datatable for binding to the Repeater
Each repeater item would have an input tag, and would receive the appropriate name/id and value. I would not use a server-control input tag. I would emit the string in a more organic fashion.
I would then post to the second aspx page.
The purpose of the repeater is to build an equivalent Form NameValueCollection for processing on the second aspx page.
References
Cross Page Postback
Posting to another page
Binding a Dictionary to a Repeater
Binding Dictionary to DropDownList - (Note, "Key", "Value")
If it is only about simplest way then it is using session variable.
Just save your form values to the session and then you can access it anywhere in your application during the particular session.
So I would have my aspx1 page something like this
// ASPX1 page's Page_Load
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Form["variable"] == "SomeValue")//some condition
{
// save these values to session so that they will
// be available when I will be in aspx2 page
Session["FormValues"] = Request.Form;
Response.Redirect("ASPX2.aspx"); // your aspx2 page's link
}
}
And aspx2 page something like this
// ASPX2 page's Page_Load
protected void Page_Load(object sender, EventArgs e)
{
// form values from aspx1 page
NameValueCollection formValuesCollection =
(NameValueCollection)Session["FormValues"];
string variableValue = formValuesCollection["variable"];
// some processing using form values from aspx1 page
Response.Redirect("HTML2.html");
}

Resources