Adding Querystring Parameter to GridView ItemTemplate - c#

I have a gridview with a hyperlink in first column. Upon clicking the hyperlink, the user is redirected to Vendor.aspx. Now, I need to pass the consumer id (of the clicked row) as a query string to the Vendor.aspx.
What is the best method to achieve it? Is there a way in which we can handle it using markup code only?
<asp:GridView ID="grdConsumers" runat="server" AutoGenerateColumns="False"
EnableViewState="True" >
<Columns>
<asp:TemplateField HeaderText="ConsumerID" SortExpression="ConsumerID" >
<ItemTemplate>
<asp:HyperLink ID="lnkConsumerID" href="Vendor.aspx" runat="server"><%# Eval("ConsumerID")%></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Status" DataField="Status" SortExpression="Status"></asp:BoundField>
</Columns>
</asp:GridView>
READINGS:
Set Gridview DataNavigateUrlFormatString Dynamically inside User Control(ASCX)
How do I add "&Source" to DataNavigateUrlFormatString?
Select row in GridView with JavaScript
How to bind the URL of a GridView HyperLinkField when the bound value contains a colon?
asp.net gridview DataNavigateUrlFormatString from DataSource

Try using the DataNavigateUrlFormatString
<ItemTemplate>
<asp:HyperLinkField DataNavigateUrlFields="ConsumerID" DataTextField="ConsumerID" DataNavigateUrlFormatString="Vendor.aspx?id={0}" />
</ItemTemplate>
... it will spare you Eval() and the problem with single/double quotes when putting it inside your href.
You can substitute the DataTextField if you like - I just put the ConsumerID there to be consistent with your example.

Rewrite your hyperlink in gridview in .aspx file like this:
<asp:HyperLink ID="lnkConsumerID" runat="server" Text='<%# Eval("ConsumerID")%>' />
Then in code-behind create a RowDataBound event handler:
protected void grdConsumers_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType != DataControlRowType.DataRow) return;
var hlnkhlnk = (HyperLink)e.Row.FindControl("lnkConsumerID");
if (hlnkhlnk != null)
{
hlnkhlnk.NavigateUrl = "Vendor.aspx" + "?Consumer ID=" + hlnkhlnk.Text;
}
}
Hope it helps.

You can do same using at Grid view Item Data Bound Event
protected void grdConsumers_ItemDataBound(object sender,DataGridItemEventArgs e)
{
if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
// Get your consumerId here
((HyperLink)e.Item.FindControl("Edit")).NavigateUrl = "Vendor.aspx?id=" + consumerId
}
}

Related

getting GridView data from buttonField press?

So I have a GridView for a C# web application, that has a Buttonfield, and when that button is clicked, I need to get the value of one of the fields for that row and store it in a variable for processing in some way.
However, neither the GridView nor the ButtonField seem to possess any means of doing this.
Can anyone recommend a way of getting data from a GridView, or if this is not possible, a different type of view that does offer this functionality, while still displaying a whole table (eg, not a DetailsView)
You can Check this link: https://msdn.microsoft.com/en-us/library/bb907626(v=vs.140).aspx.
Define the CommandName of the Button.
In the GridView Define the RowCommand Event and Check the CommandName.
Get the Index of the Row.
Get the Column with GridView.Rows[index](columnIndex)
If you are using asp:TemplateField like shown below then you can access the row content using RowCommand
Markup
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblCode" runat="server" Text='<%# Eval("CustomerID") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:ButtonField CommandName="AddCode" Text="Add New"/>
Code
protected void gvwSearch_RowCommand(object sender, GridViewCommandEventArgs e)
{
if(e.CommandName == "AddCode")
{
var clickedButton = e.CommandSource as Button;
var clickedRow = clickedButton.NamingContainer as GridViewRow;
var rows_lblCode = clickedRow.FindControl("lblCode") as Label;
// now you can acccess all the label properties. For example,
var temp = rows_lblCode.Text;
}
}

Telerik RadGrid row data to populate GridEditableItem column

I have a telerik radgrid with a hyperlink in one of the columns in edit mode. I want to have the text of the hyperlink set to the page title of the page it links to without creating a hidden field for this. I get this title from a database call which I pass the ID of the current row in the grid that is being edited. Since the ItemDataBound method always does the binding of the GridEditableItem before the actual row itself, the MasterTableView does not contain the ID I need until the next iteration.
The ugly solution I came up with was to keep a reference to the hyperlink and populate it on the very next iteration when the ID is now availible on the grid.
I seem to think there is a better solution!
protected void grid_ItemDataBound(object sender, GridItemEventArgs e)
{
if (e.Item is GridEditableItem && e.Item.IsInEditMode)
{
link = ((e.Item as GridEditableItem)["myHyperlink"].Controls[1] as HyperLink);
go1 = true;
}
if(go2)
{
string myID = grid.MasterTableView.Items[grid.Items.Count - 1].GetDataKeyValue("myID").ToString();
string pageId= PoolAgent.getPageId(Int32.Parse(myID));
link.Text = pageId;
go2 = false;
go1 = false;
}
if (go1)
go2 = true;
aspx:
<telerik:GridBoundColumn DataField="myID" UniqueName="myID" HeaderText="ID" ReadOnly="true">
</telerik:GridBoundColumn>
<telerik:GridTemplateColumn EditFormColumnIndex="2" UniqueName="myHyperlink" HeaderText="Link:" ItemStyle-HorizontalAlign="Center" Display="False" >
<ItemTemplate>
</ItemTemplate>
<EditItemTemplate>
<asp:Hyperlink ID="KeyManagerLink" Runat="server" NavigateUrl='' onclick="popupwindow(this.href, 'popupwindow', 1150, 500); return false;"></asp:Hyperlink>
</EditItemTemplate>
</telerik:GridTemplateColumn>

Nesting a ListView inside a GridView

I have an ASP.NET GridView which amongst other values binds an ID to one of the columns.
Another one of the columns of this table should contain a list of items, which should be resolved by passing in the ID from the GridView.
To achieve this, I tried nesting the ListView inside the GridView, and passing the ID into the Default Parameter of an ObjectDataSource used by the ListView, but this syntax is not allowed:
<asp:TemplateField HeaderText="columnItems">
<ItemTemplate>
<asp:ListView ID="listOfItems" runat="server" DataSourceID="MyObjectDataSource >
<ItemTemplate>
<asp:LinkButton ID="MyLinkButton" Runat="Server" Text='item'></asp:LinkButton>
</ItemTemplate>
</asp:ListView>
<asp:ObjectDataSource ID="MyObjectDataSource" runat="server"
TypeName="MyTypeName.Whatever" SelectMethod="GetItems">
<SelectParameters>
<asp:Parameter Name="requestId" Type="String" DefaultValue='<%# Eval("ID")'/>
</SelectParameters>
</asp:ObjectDataSource>
</ItemTemplate>
</asp:TemplateField>
</Columns>
So how do I go about passing in the ID so I can get the list of items?
You probably need to do that in the RowDataBound event, get the ID there and then do you DB
then do something like
if(e.Row.RowType != DataControlRowType.DataRow)
{
return;
}
ListView a = (ListView)e.Row.FindControl("listOfItems");
a.datasource = // the result of your db call
a.databind();
Attach a 'OnRowDataBound' event to the GridView control to retrieve the items for the ListView for each row on the GridView (after the GridView has been bound):
e.g. On the ASPX page:
<asp:GridView id="MyGridView" OnRowDataBound="GetItems" ... > ... </asp:GridView>
In the code-behind:
protected void GetItems(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType != DataControlRowType.DataRow)
{
return;
}
// Get the ID from the GridView
var dataRowView = (DataRowView) e.Row.DataItem;
var id = dataRowView["ID"].ToString();
// Bind the supporting documents to the ListView control
var listView = (ListView) e.Row.FindControl("listOfItems");
listView.DataSource = /* Call to database to return a DataSet of items */;
listView.DataBind();
}
(As would be appropriate, I tried editing Tunisiano's post to elaborate on his answer on attaching the event to the GridView and getting the request ID, but SO editors are rejecting it for no good reason. The above code is tested and answers the question exactly).

Repeater and Collapsible Panel Extender

I am trying to bind a grid view into a repeater for collapsible panel extender body. Here is the code:
<!-- Collapsible panel extender body -->
<asp:Panel ID="pBody1" runat="server" CssClass="cpBody">
<asp:Label ID="lblBodyText1" runat="server" />
<asp:Repeater ID="Repeater2" runat="server" OnItemDataBound="Repeater2_ItemDataBound">
<ItemTemplate>
<asp:GridView ID="gvProduct" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="id" HeaderText="ID" />
<asp:BoundField DataField="name" HeaderText="Name" />
<asp:BoundField DataField="categoryName" HeaderText="Category" />
<asp:BoundField DataField="inventoryQuantity" HeaderText="Quantity" />
</Columns>
</asp:GridView>
</ItemTemplate>
</asp:Repeater>
</asp:Panel>
And from the code behind, I am trying to loop thru the list to get category name. Then, I get all the products based on category name and display them in gridview.
protected void Repeater2_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
// This event is raised for the header, the footer, separators, and items.
//Execute the following logic for Items and Alternating Items.
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
for (int count = 0; count < categoryList.Count; count++)
{
string category = categoryList[count].categoryName;
List<ProductPacking> prodList = new List<ProductPacking>();
prodList = packBLL.getAllProductByCategory(category);
gvProduct.DataSource = prodList;
gvProduct.DataBind();
}
}
}
However, it told me that gvProduct does not exist in current context. I wonder how can I get the components inside a repeater? Or am I doing in the wrong way?
Updated Portion.
This is how I bind the header for category name. And I am using another repeater:
<asp:Label ID="lblCategory" Text='<%# DataBinder.Eval(Container.DataItem, "categoryName") %>' runat="server" />
And from the code behind, at the page load, I get all the category:
if (!IsPostBack)
{
//Get all category and bind to repeater to loop
categoryList = packBLL.getAllCategory();
Repeater1.DataSource = categoryList;
Repeater1.DataBind();
}
And for repeater2 which shows the product in each category, I edited it to become like this:
protected void Repeater2_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
// This event is raised for the header, the footer, separators, and items.
string category = e.Item.FindControl("categoryName").ToString();
//Execute the following logic for Items and Alternating Items.
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
GridView gv = (GridView)e.Item.FindControl("gvProduct");
if (gv != null)
{
List<ProductPacking> prodList = new List<ProductPacking>();
prodList = packBLL.getAllProductByCategory(category);
DataRowView drv = (DataRowView)e.Item.DataItem;
gv.DataSource = prodList;
gv.DataBind();
}
}
}
However, when I expand the extender, nothing shows up.
If I remember right, you need to use FindControl to access controls that are part of templates, like
GridView oGV = e.Item.FindControl ( "gvProducts" ) as GridView;
You cannot refer to the GridView as gvProducts because there's no single GridView control with that name - a different instance (with a different name) is created for each data item from the template. You need the instance for the current row.
Here's an MSDN example that shows how to access a control during data binding (the example uses a Label).

How to transform a column from a gridview in a dropdownlist with 2 values to choose

I have a gridview with the following columns:
NAME|AGE|Birthday|Code
Joh 21 12.12.2 Yes/No
Currently the column code is a textbox. How can I transform it into a dropdownlist with 2 values: Yes/No so if I press edit I can choose in that cell the Value Yes or No.
Also How can I check on edit event too see if value is yes?
You can create a template field like this:
<columns>
<asp:TemplateField HeaderText="code">
<ItemTemplate>
<asp:DropDownList ID ="ddlCode" runat="server" AppendDataBoundItems="true" CssClass="DropDn1" />
</ItemTemplate>
</asp:TemplateField>
</columns>
In your rowdatabound event of the grid you will bind it if you want to bind from the database.
protected void RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList code= (DropDownList)e.Row.FindControl("ddlCode") as DropDownList;
if (code!= null)
{
//Bind the dropdownlist
}
}
To retrieve the value from the dropdown in your edit event you will do this:
string code = (row.FindControl("ddlCode") as DropDownList).Text);

Categories

Resources