Can't access HyperLinkField text in a GridView - asp.net

I have a HyperLinkField defined as follows:
<asp:GridView ID="gvNotifications" runat="Server" AutoGenerateColumns="false" EnableViewState="true" CssClass="tableWhole" AlternatingRowStyle-CssClass="tableAlt">
<Columns>
<asp:HyperLinkField HeaderText="Item#" DataTextField="sku"
DataNavigateUrlFormatString="/store/item/{0}/"
DataNavigateUrlFields="sku" ItemStyle-CssClass="itemNo" />
In my code-behind, I'm attempting to access the Text property like this:
For Each gvRow In gvNotifications.Rows
processItem(gvRow.Cells(0).Text.ToString)
Next
This code worked when it was defined as a BoundField, like this:
<asp:BoundField HeaderText="Item #" DataField="sku" ItemStyle-CssClass="itemNo" />
How can I access the Text property on a HyperLinkField in a GridView.Row.Cells?

Nevermind, I figured it out based-on a related C# question.
For Each gvRow In gvNotifications.Rows
processItem(gvRow.Cells(0).Controls(0).Text.ToString)
Next

Related

populate label with control id

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="audition_ID" DataSourceID="ObjectDataSource10" AllowPaging="True" AllowSorting="True">
<Columns>
<asp:BoundField DataField="audition_ID" HeaderText="audition_ID" InsertVisible="False" ReadOnly="True" SortExpression="audition_ID" />
<asp:BoundField DataField="audition_date" HeaderText="audition_date" SortExpression="audition_date" />
<asp:BoundField DataField="ins_ID" HeaderText="ins_ID" SortExpression="ins_ID" />
<asp:BoundField DataField="insturment_name" HeaderText="insturment_name" SortExpression="insturment_name" />
<asp:BoundField DataField="audition_status" HeaderText="audition_status" SortExpression="audition_status" />
<asp:BoundField DataField="audition_location" HeaderText="audition_location" SortExpression="audition_location" />
<asp:BoundField DataField="audition_time" HeaderText="audition_time" SortExpression="audition_time" />
<asp:HyperLinkField DataNavigateUrlFields="audition_ID" DataNavigateUrlFormatString="judgescores.aspx?auditionID={0}" HeaderText="Details" Text="Details" />
</Columns>
</asp:GridView>
I am using a grid view to display information for a database based on the selection in a drop down list. I have that working and when selecting the DDL- the grid view updates and shows the associated records.
I then added a "Details" hyperlink column that directs to the details.aspx page and picks up the ID so it shows the correct details associated with that record.
DataNavigateURLFormat = details.aspx?ID={0}
I can see the ID in the URL od this details page. What I am trying to do now is take that ID and populate it in a label on the details page.
I am exploring the "Expression" property in the Data section of the label properties- but have not found any luck using "AccessControlID" or "ClientIDMode" giving it a "RouteValue".
I was also exploring going in the code of the details page (details.aspx.vb)
and doing something like
lbldetail.Text = #ID
But not sure if that would work.
Any help would be greatly appreciated.
Contents of judgescores.aspx.vb page...
Partial Class Judges_judgescores
Inherits System.Web.UI.Page
Sub Page_Load()
lblCurrentAudition.Text = Request.QueryString[audition_ID]
End Sub

OnCheckChanged not Firing when Unchecked

I've googled this topic as much as i could, ive found similar topics around and even on stackoverflow but none were able to resolve my issue. I have a nested gridview bound to a sqldatasource that populates a few fields as well as a checkbox field from a 'bits' field in the database. The checkboxes populate correctly from the database (checked vs. unchecked) but my 'OnCheckedChanged' event only fires when i check a checkbox but does NOT fire when it is unchecked, the page just goes through its post back. I have 'EnableViewState' set to true on the master page, local page, and on the control as well as auto post back. What i need to do is update the DB with the new value of the checkbox (checked vs unchecked) and reload. Please let me know if anyone has suggestions.
Protected Sub Gridview3_OnCheckedChanged(Sender As Object, e As EventArgs)
Dim checkbox As CheckBox = TryCast(Sender, CheckBox)
Dim gridview3 As GridView = checkbox.Parent.Parent.Parent.Parent
Dim row As GridViewRow = checkbox.Parent.Parent
sql_insert(String.Format("UPDATE [STOREIT2-PORTAL].dbo.AA5VOLUMES SET PROTECTED = '{0}' WHERE GUID = '{1}' AND AGENTID = '{2}'", checkbox.Checked, gridview3.DataKeys(row.RowIndex).Values("GUID").ToString, gridview3.DataKeys(row.RowIndex).Values("AgentID").ToString))
End Sub
<asp:GridView ID="Gridview3" EnableViewState="true" runat="server" AutoGenerateColumns="False" DataKeyNames="AgentID,GUID" OnRowDataBound="GridView3_OnRowDataBound" RowStyle-CssClass ="row" AlternatingRowStyle-CssClass="altrow" RowStyle-HorizontalAlign="Center" CssClass="gvmain"> <AlternatingRowStyle CssClass="altrow"></AlternatingRowStyle>
<columns>
<asp:BoundField DataField="AgentID" HeaderText="AgentID" SortExpression="AgentID" visible="false"/>
<asp:BoundField DataField="GUID" HeaderText="GUID" SortExpression="GUID" visible="false"/>
<asp:BoundField DataField="VolumeName" HeaderText="VolumeName" SortExpression="VolumeName" readonly="true"/>
<asp:BoundField DataField="Label" HeaderText="Label" SortExpression="Label" nulldisplaytext="<i>{No Label}</i>" readonly="true"/>
<asp:BoundField DataField="BaseCount" HeaderText="BaseCount" SortExpression="BaseCount" nulldisplaytext="<i>{No Base Images}</i>" readonly="true"/>
<asp:BoundField DataField="TimeStamp" HeaderText="TimeStamp" SortExpression="TimeStamp" nulldisplaytext="<i>{Volume has no recent snapshots}</i>" readonly="true"/>
<asp:TemplateField headertext="Protected">
<ItemTemplate>
<asp:CheckBox ID="Protected" EnableViewState="true" runat="server" autopostback="true" checked='<%# Eval("Protected")%>' OnCheckedChanged="Gridview3_OnCheckedChanged"/>
</ItemTemplate>
</asp:TemplateField>
</columns>
</asp:GridView>
I'm noticing your code does not have the 'Handles Clause' Maybe this is causing the problem you mention. . .
Handles CheckBox1.CheckedChanged

Adding link dynamically to Template Field

I need to replace the link for each data bound item. I already checked out the databound event of the datarow. The problem with that is I can't control where the link shows up. I'm trying to stay away from javascript and keep it mostly in the code behind. Below is my asp code and the code behind I have. I also want to try to keep as much the same as possible, not changing to the html template items. The process Im using is as follows.
I have a custom object which contains all the fields and data of a blog entry. Those items are put into a list and then supplied to the datagrid.
<asp:GridView ID="grdRecentNews" runat="server" AutoGenerateColumns="False" DataKeyNames="Key"
GridLines="None" PageSize="4" ShowHeader="False"
AllowPaging="True">
<PagerSettings Visible="False" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<blockquote>
<%-- <strong><a href=**"News.aspx"**>--%>
<strong><a href="News.aspx">
<%#Eval("NewsDesc")%></a></strong>
<br />
<span class="italic">
<%#Eval("NewsDate")%></span>
</blockquote>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
This is the code I had in the Databound event, problem being I only want to provide a link for one of the fields of the Rss object. as above below. I want to replace News.aspx" for each item added to the datagrid with the rssobject's link property.
Protected Sub grdRecentNews_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles grdRecentNews.RowDataBound
If e.Row.DataItem IsNot Nothing AndAlso e.Row.DataItem.ToString = "RssEntry" Then
Dim curItem As RssEntry = CType(e.Row.DataItem, RssEntry)
e.Row.Attributes.Add("href", curItem.Link) 'data-url
End If
End Sub
I found a way to insert an <%#Eval %> statement into the attribute I wanted to change. I point it towards the correct property of the rssobject, and its working.
<Columns>
<asp:TemplateField>
<ItemTemplate>
<blockquote>
<strong><a href='<%#Eval("Link")%>'>
<%#Eval("NewsDesc")%></a></strong>
<br />
<span class="italic">
<%#Eval("NewsDate")%></span>
</blockquote>
</ItemTemplate>
</asp:TemplateField>
</Columns>

How to get the non visible gridview cell value in ASP.net?

I have a grid like below.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" s
onrowcommand="GridView1_RowCommand">
<Columns>
<asp:ButtonField DataTextField="Name" HeaderText="Name" />
<asp:BoundField DataField="ArrDate" DataFormatString="{0:MM/dd/yyyy}"
HeaderText="Arr Date" />
<asp:BoundField HeaderText="Dep Date" DataField="DepDate"
DataFormatString="{0:MM/dd/yyyy}" />
<asp:BoundField HeaderText="Mail" DataField="Mail" />
<asp:BoundField HeaderText="Status" DataField="Status" />
<asp:BoundField DataField="ResId" HeaderText="ResId" Visible="False" />
</Columns>
</asp:GridView>
In Code Behind:-
try
{
string text = GridView1.Rows[2].Cells[5].Text;
ScriptManager.RegisterStartupScript(this, GetType(), "Message", "alert('ResId = " + text + ".');", true);
}
catch { }
Now the message shows - RegId =.
I can't get the value. So I change the RedId BoundField as vissible. Now I got the Value.
that is RegId =6.
I have two issue now -
1) How to get the RegId value in Non Visible Column.
2) How I find the Row value which i click... bzs the only i can change the ROWVALUE in code..
string text = GridView1.Rows[ROWVALUE].Cells[5].Text;
That is certainly not the right way to do it. You might want to look at using DataKeys to achieve this. With current approach, when you add a new column to your grid your code will fail.
Add your RegId column inside DataKeys property on your gridview
Reference your gridview datakey for the current row in codebehind like this
int regId= Convert.ToInt32(YourGridview.DataKeys[rowIndex]["RegId"].ToString());

Optionally display a text in place of GridView when the GridView has no rows

I have a basic GridView that displays a list of tasks to do (just an example)
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" AllowSorting="True" >
<Columns>
<asp:BoundField DataField="todo" HeaderText="To Do" ReadOnly="True" SortExpression="todo" />
<asp:BoundField DataField="byDate" HeaderText="By When" ReadOnly="True"
SortExpression="byDate" />
the data source is specified within the aspx page and it is a result set from a stored procedure
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="..."
SelectCommand="pToDoList" SelectCommandType="StoredProcedure">
</asp:SqlDataSource>
So the rendered page presents tasks as rows of data (a row per task)
My question is
When there is not data returned by stored procedure the page remains blank. I would like to have a text instead saying for example: "nothing to do today"
How to do that? Thank you
Use the EmptyDataTemplate:
<asp:gridview id="CustomersGridView"
datasourceid="CustomersSqlDataSource"
autogeneratecolumns="true"
runat="server">
<emptydatarowstyle backcolor="LightBlue"
forecolor="Red"/>
<emptydatatemplate>
<asp:image id="NoDataImage"
imageurl="~/images/Image.jpg"
alternatetext="No Image"
runat="server"/>
No Data Found.
</emptydatatemplate>
</asp:gridview>
Example from http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.emptydatatemplate.aspx
there is a property "EmptyDataText" that allows you to specify text if the gridview is empty
Add a Label to the page, call it ErrorLabel, then do something like this in the DataBound event of the GridView:
protected void GridView1_DataBound(object sender, EventArgs e)
{
if(GridView1.Rows.Count <= 0) ErrorLabel.Text = "Nothing to do today";
else ErrorLabel.Visible = false;
}
Although a Google search would have probably gotten that for you.
One option is to use the Footer to display this message. During the ItemDataBound, if the ItemType is the footer, check if the DataSource is empty and if it is, display the message.
Or if you want to work declaritvely in the ASPX you can use the EmptyDataTemplate and add your message there.
I would simply would add a label control noDataLabel containing the text "Nothing to do today", and add some code in the Page_Load event:
if (GridView1.Rows == 0)
{
GridView1.Visible = false;
}
else
{
noDataLabel.Visible = false;
}
It is a bit crude, but it beats have embedded C# inside your webform HTML. If there is no data, and the form is rendered, the GridView is simply ignored.

Resources