How to add conditional button in template field gridview? - c#

I have one gridview that contains some fields, I want to show button in TemplateField when Process field has value.
Here is my code:
<asp:GridView ID="grdList" PageSize="20" runat="server" DataSourceID="ODList" AllowPaging="True"
AllowSorting="True" PagerSettings-Position="Top" AutoGenerateColumns="False"
ShowFooter="True" ShowHeaderWhenEmpty="True" OnPageIndexChanged="grdList_PageIndexChanged">
<Columns>
<asp:BoundField DataField="MeasureCatalogId" SortExpression="MeasureCatalogId" />
<asp:BoundField DataField="MeasureName" SortExpression="MeasureName" />
<asp:TemplateField SortExpression="Process">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("Process") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("LevelId") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<%if(????????) -- want condition for process!= ""
{
%>
<img class="semPopup" sempopupurl='<%=Constant.AppPath %>/forms/baseform/MeasureProcessFromCatalogForm.aspx?t=2&lid=<%# Eval("LevelId") %>&mid=<%# Eval("MeasureCatalogId") %>'
sempopupwidth="<%=width %>" sempopupheight="<%=height %>"
src="../../App_Themes/images/select2.gif" />
<%} %>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<PagerSettings Position="Top"></PagerSettings>
<PagerStyle CssClass="grid_pager" />
</asp:GridView>

As an alternative to the other recommendations; you could try using a code expression on the field:
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<img class="semPopup" sempopupurl='<%=Constant.AppPath %>/forms/baseform/MeasureProcessFromCatalogForm.aspx?t=2&lid=<%# Eval("LevelId") %>&mid=<%# Eval("MeasureCatalogId") %>'
sempopupwidth="<%=width %>" sempopupheight="<%=height %>"
src="../../App_Themes/images/select2.gif" Visible='<%# ShowButton(Eval("Process")) %>'/>
</ItemTemplate>
</asp:TemplateField>
I have not tried this out, but it follows a similar pattern to what i have previously used. The code expression calls the codebehind function 'ShowButton' which should return a bool, here you can evaluate the value of process passed in, and if it is to your liking, pass back a true value; otherwise return false and the button will not show.
C#
protected bool ShowButton(object DataItem)
{
//Here you can place as many conditions as you like
//Provided you always return either true or false
if (DataItem != null)
return true;
else
return false;
}
A suggested edit was posed in a similar fashion, however instead of a bool visibility, the visibility setting is altered by string value. I am sure they will add their take too. After all, variety is the spice of life

Use codebehind, make the button visible when appropriate:
protected void gridview1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRow row = ((DataRowView)e.Row.DataItem).Row;
string process = row.Field<string>("Process"); // change type from string to whatever it is
Button btn = (Button) e.Row.FindControl("ButtonID");
btn.Visible = process == "YourProcessValue";
}
}

you can make use of RowDataBoundand than make decision of hiding your control
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
SomeObject mapItem = (SomeObject)e.Row.DataItem;
if(!mapItem.Process)
(e.Row.Cells[3].FindControl("Buttonid") as Button).visible= false;
}
}
or try
<ItemTemplate>
<asp:Button runat="server" Text="Reject"
Visible='<%# ((bool)Eval("Process")) %>' />
</ItemTemplate>

Related

Hide Column In Grid

This is my html mark-up and adding the visibility to false in the div tag hides the actual data itself, but just leaves a blank column. I tried to access the div tag (yes I added the runat="server" tag to the html) and attempted to access it like so hideme.Visible = true; which threw a compile error of
Does not exist in the current context.
What should I alter/modify to ensure that this column is completely hidden from my grid?
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" ShowFooter="true"
onrowdatabound="GridView1_RowDataBound" onrowcreated="GridView1_RowCreated">
<Columns>
<asp:BoundField DataField="abcd" HeaderText="abcd" />
<asp:BoundField DataField="def" HeaderText="def" />
<asp:BoundField DataField="hij" HeaderText="hij" />
<asp:BoundField DataField="xyz" HeaderText="xyz" />
<asp:BoundField DataField="eee" HeaderText="eee" />
<asp:BoundField DataField="era" HeaderText="era" />
<asp:BoundField DataField="nai" HeaderText="nai" />
<asp:BoundField DataField="fac" HeaderText="fac" />
<asp:TemplateField>
<ItemTemplate>
<div runat="server" style="visibility:hidden" id="hideme">
<asp:Label ID="lbllunch" runat="server" Text='<%# Eval("hij") %>' />
<asp:Label ID="lbllunchoverage" runat="server" Text='<%# Eval("xyz") %>' />
<asp:Label ID="lbleee" runat="server" Text='<%# Eval("eee") %>' />
<asp:Label ID="lblera" runat="server" Text='<%# Eval("era") %>' />
<asp:Label ID="lblnai" runat="server" Text='<%# Eval("nai") %>' />
<asp:Label ID="lblfac" runat="server" Text='<%# Eval("fac") %>' />
</div>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
EDIT
I added the .Visible command to my page load event (where I always hide anything on my page) like so:
protected void Page_Load(object sender, EventArgs e)
{
hideme.Visible = false;
/More here
}
Since hideme is inside the GridView TemplateField, you can't access it in Page_Load method, however you can access it in GridView1_RowDataBound method as below
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// find the hideme div
HtmlGenericControl div = (HtmlGenericControl)e.Row.FindControl("hideme");
// set the visible property
div.Visible = false;
}
}
You can hide the column in DataBound event of gridview.
protected void GridView_DataBound(object sender, GridViewRowEventArgs e)
{
GridView.Columns[8].Visible = false;
}
If you want to hide template field column why you are adding it to markup. Yes if you keep style="visibility:hidden" it will show blank column only because item template still exists as column.
My suggestion for you is if dont need column dnt add markup.

Create hyperlink button cells in gridview using C# asp.net

I am having a GridView in my web page. Which is displaying the data with the columns as Status, Name , Id and Action. My status column always filled with the 3 values(Complete, Queued and Failed) randomly.
Now I want to display this status column values as a link ,If it is having the value either "Failed" or "Queued". But "Complete" status should not be display as a link.
How Can I achive this design during the runtime?
My Code for binding the data into the grid is,
protected void Page_Load(object sender, EventArgs e)
{
DataTable dtActionList = clsactionList.GetADActionList();
grdADActionList.DataSource = dtActionList;
grdADActionList.DataBind();
}
protected void grdADActionList_RowDataBound(object sender, GridViewRowEventArgs e)
{
foreach (GridViewRow gvr in grdADActionList.Rows)
{
if ((gvr.FindControl("Label1") as Label).Text == "Completed")
{
(gvr.FindControl("Label1") as Label).Visible = true;
(gvr.FindControl("HyperLink1") as HyperLink).Visible = false;
}
}
}
using this code I am just simply binding the values in the grid. I am not able to create the Status column as having link buttons based on the binded values for that status column.
My .aspx Code is:
<asp:GridView ID="grdADActionList" runat="server" Height="83px" Width="935px" AutoGenerateColumns="false" OnRowDataBound="grdADActionList_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Status" SortExpression="Status">
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='http://localhost:52807/Default.aspx?'><%# Eval("Status") %>
</asp:HyperLink>
<asp:Label ID="Label1" runat="server" Text="<%# Container.DataItem %>" Visible="False"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="GivenName" HeaderText="GivenName"/>
Please help me to do this further....
On GridViewDataBound event, just hide the link and display a simple label if the value is complete.
ASP.NET:
<asp:TemplateField HeaderText="Status" SortExpression="Status">
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='your_url'>
<%# Eval("Status") %>
</asp:HyperLink>
<asp:Label ID="Label1" runat="server" Text="<%# Eval("Status") %>" Visible="False"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
C#:
protected void onGridViewDataBound()
{
foreach(GridViewRow gvr in grd)
if((gvr.FindControl("Label1") as Label).Text.ToLower() == "complete") // Updated Line
{
(gvr.FindControl("Label1") as Label).Visible = true;
(gvr.FindControl("HyperLink1") as HyperLink).Visible = false;
}
}
you have to work in design file means .aspx file
you have to use and
<asp:GridView ID="GridView1" runat="server" EnableModelValidation="True">
<asp:TemplateField HeaderText="Hyperlink">
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server"
NavigateUrl='<%# Eval("CODE", #"http://localhost/Test.aspx?code={0}") %>'
Text='link to code'>
</asp:HyperLink>
</ItemTemplate>
You can place an handler on RowDataBound event
protected void gw_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRowView v_DataRowView = (DataRowView)e.Row.DataItem;
string NavigateUrl = <....place your link here with DataRowView info>
e.Row.Attributes.Add("onclick", NavigateUrl);
}
}
For now you have your columns auto generated, so first disable that feature. Then you need to define each column as a BoundField, and for the hypelink, taking into account your condition, the best way is to define template field:
<asp:GridView ID="grdADActionList" runat="server" BorderStyle="Double" BorderWidth="3px"
Height="83px" Width="935px"
AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name"/>
<asp:BoundField DataField="Action" HeaderText="Action"/>
<asp:BoundField DataField="Id" HeaderText="Id"/>
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:HyperLink runat="server" NavigateUrl="~/link/address" Text='<%# Eval("Status") %>'
Visible='<%# (int)Eval("Status") != 1 %>'/>
<asp:Label runat="server" Text='<%# Eval("Status") %>'
Visible='<%# (int)Eval("Status") == 1 %>'>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Note that this is just a variation - you have not specified what values does Status column contain, so I assumed this is int-based enumeration.

GridView does not update values on postback?

I have a gridview with some custom templates:
<asp:GridView ID="gvGroups" runat="server" AutoGenerateColumns="False"
CssClass="table table-hover table-striped" GridLines="None" >
<Columns>
<asp:BoundField DataField="GroupDescription" HeaderText="Name" ReadOnly="True"
SortExpression="GroupDescription" />
<asp:TemplateField HeaderText="Administrator">
<ItemTemplate>
<asp:CheckBox ID="cbAdmin" runat="server"
Checked='<%# Boolean.Parse((Boolean)Eval("IsReadOnly") ? "True" : "False") ? false : true %>'/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Remove">
<ItemTemplate>
<asp:CheckBox ID="cbRemove" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ID" SortExpression="GroupID" Visible="False">
<ItemTemplate>
<asp:Label ID="lblID" runat="server" Text='<%# Bind("GroupID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I then have a button that I click and that is supposed to change group administration and remove groups that are checked.
Here is the button code:
protected void btnSave_Click(object sender, EventArgs e)
{
foreach (GridViewRow gvr in gvGroups.Rows)
{
CheckBox cbAdmin = (CheckBox)gvr.FindControl("cbAdmin");
CheckBox cbRemove = (CheckBox)gvr.FindControl("cbRemove");
Label lblID = (Label)gvr.FindControl("lblID");
int id;
bool idValid = int.TryParse(lblID.Text,out id);
bool isReadOnly = !cbAdmin.Checked;
if (idValid)
{
Group g = SecurityManager.GetGroup(id);
if (g.IsReadOnly != isReadOnly)
{
bool updateSuccess = SecurityManager.ChangeGroupPermissions(id, isReadOnly);
}
if (cbRemove.Checked)
{
bool removeEmpSuccess = SecurityManager.RemoveEmployeesFromGroup(id);
bool removeSuccess = SecurityManager.RemoveGroup(id);
}
}
}
}
I used the debugger and even when I uncheck admin on all groups, when I look at cbAdmin.Checked, it is still true, which is the same value it started with, thus nothing ever happens.
What could be the problem? Why am I not seeing the updated values on the button postback?
Thanks
You have to call GridView#DataBind() within if(!IsPostBack){ }
Also you need to set AutoPostBack property of the textboxes to "true"
I guess that you're databinding the GridView on postbacks. That will load the data from database again and prevent changes. So ue the PostBack property of the Page:
protected void Page_Load(Object sender, EventArgs e)
{
if(!IsPostBack)
{
DataBindGridView();
}
}

How to reference a linkbutton thats inside a asp:grid when its clicked

I have a ASP:grid which has a link button, i need to some how reference that on the code behind when its clicked but im struggling on the syntax
Heres my ASP:Grid i need to execute code in the code behind when that link button 'Re-Take' is pressed and also be able to know what row it was clicked on as i will need to reference the users emails and name and then send an email with the relevant information....
<asp:GridView ID="GrdViewUsers" runat="server" AutoGenerateColumns="false" GridLines="None"
EnableViewState="false" class="tablesorter">
<AlternatingRowStyle></AlternatingRowStyle>
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton Text="Re-Take" runat="server" ID="Edit" CommandName="Edit"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Full Name">
<ItemTemplate>
<asp:HyperLink ID="HyperFullName" CssClass="gvItem" runat="server" NavigateUrl='<%#Eval("UserID","/ExamPaper.aspx?uid={0}") %>'
Text='<%# DataBinder.Eval(Container,"DataItem.FullName") %>'></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Email">
<ItemTemplate>
<asp:Label ID="lblSurname" CssClass="gvItem" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.Email") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Exam Taken">
<ItemTemplate>
<asp:Label ID="lblUsername" CssClass="gvItem" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.ExamTaken") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Date Taken">
<ItemTemplate>
<asp:Label ID="lblUsername" CssClass="gvItem" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.DateTaken") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Exam Total">
<ItemTemplate>
<asp:Label ID="lblUsername" CssClass="gvItem" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.ExamTotal") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
If someone can help me with a snippet i would highly appreciate it
You could approach this slightly different. You see, when a control is placed inside a gridview, any event raised from that control raises also the RowCommand on the GridView.
To get what you want you could then add both CommandName and CommandArgument to your LinkButton and then catch it in the GridView's RowCommand.
<asp:LinkButton id="LinkButton1" runat="server" commandName="LinkButtonClicked" commandArgument='Eval("myObjectID")' />
where myObjectID is the name of the ID column of your object you bind the grid to.
Then
void GridView1_RowCommand( object sender, GridViewCommandEventArgs e )
{
if ( e.CommandName == "LinkButtonClicked" )
{
string id = e.CommandArgument; // this is the ID of the clicked item
}
}
see: ASP.net GridView: get LinkItem's row
FindControl should work in this case.
protected void GrdViewUsers_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
HyperLink myHyperLink = e.Row.FindControl("Edit") as HyperLink;
}
}
First: You have repeating ID's in your TemplateFields like lblUsername what is not allowed since it's the same NamingContainer.
You can pass the RowIndex as CommandArgument to RowCommand:
on aspx:
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton
Text="Re-Take"
runat="server"
ID="Edit"
CommandName="Edit"
CommandArgument="<%# ((GridViewRow) Container).RowIndex %>">
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
Handle the GridView's RowCommand:
void GrdViewUsers_RowCommand(Object sender, GridViewCommandEventArgs e)
{
if(e.CommandName=="Edit")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = GrdViewUsers.Rows[index];
// now you can get all of your controls like:
Label lblSurname = (Label)row.FindControl("lblSurname");
String email = lblSurname.Text // you noticed that DataItem.Email is bound to lblSurname?
}
}
Suppose the grid has linkbutton on which we want to get row index
<asp:LinkButton ID="lnkbtnAdd " runat="server" CommandName="cmdAdd" ImageUrl="~/Images/add.gif" ></asp:LinkButton>
In code behind, In OnRowCreated event we attach row number of grid to each button of row to get it back when it is clicked in RowCommand event
protected void gvListing_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
System.Web.UI.WebControls.LinkButton lnkbtnAdd = new System.Web.UI.WebControls.LinkButton();
lnkbtnAdd = (System.Web.UI.WebControls.LinkButton)e.Row.FindControl("lnkbtnAdd");
if (lnkbtnAdd != null)
lnkbtnAdd .CommandArgument = e.Row.RowIndex.ToString();
}
}
In RowCommand event we will get back the current row index and set the selected index of the grid
protected void gvListing_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.ToString() == "cmdAdd")
{
int RowIndex = int.Parse(e.CommandArgument.ToString());// Current row
}
}

GridView RowDataBound Handler - Can't get data from row

I have a GridView with an anonymous type. I need to check the value in a cell and highlight that cell if a condition is met. The problem is, I always get an empty string when I try to pull data out of the row's cells. I have successfully highlighted all the cells and I have checked in the Visual Studio 2010 debugger and confirmed that the Row has data (the row's DataItem has the values I need). This is happening on a PostBack, I'm not sure if that's a problem or not.
Here is the code and solutions I've tried:
protected void grvValidCourses_RowDataBound(Object sender, GridViewRowEventArgs e) {
if (e.Row.RowType == DataControlRowType.DataRow) {
String str = e.Row.Cells[6].Text.ToString(); // empty string
Label lbl = (Label) grvValidCourses.FindControl("lblEndDate"); // null
DataRowView rowView = (DataRowView)e.Row.DataItem; // exception about casting anonymous type
What's going on here? Why can't I get data from the cells?
Markup for GridView:
<asp:GridView ID="grvValidCourses" runat="server" Width="790px" OnRowCancelingEdit="grvValidCourses_RowCancelingEdit"
OnRowEditing="grvValidCourses_RowEditing" OnRowUpdating="grvValidCourses_RowUpdating" OnRowDeleting="grvValidCourses_RowDeleting"
AutoGenerateColumns="False" OnSelectedIndexChanged="grvValidCourses_SelectedIndexChanged"
OnRowDataBound="grvValidCourses_RowDataBound" >
<Columns>
<asp:CommandField ShowEditButton="True" EditText="Edit" UpdateText="Update |" />
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="lbnDelete" runat="server" CausesValidation="False" CommandName="Delete"
Text='<%# (Eval("active") == null ? "Delete" : ((Eval("active").ToString() == "0" ? "Restore" : "Delete"))) %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowSelectButton="True" SelectText="Details" />
<asp:TemplateField HeaderText="Training Name" SortExpression="coursename">
<EditItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("coursename") %>'></asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("coursename") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ttNo" HeaderText="#" SortExpression="ttNo" ReadOnly="True" />
<asp:TemplateField HeaderText="Course Date" SortExpression="startDate">
<EditItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("startdate", "{0:M/d/yyyy}") %>'></asp:TextBox>
<asp:CalendarExtender ID="TextBox3_CalendarExtender" runat="server" Enabled="True"
TargetControlID="TextBox3" Format="M/d/yyyy">
</asp:CalendarExtender>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("startdate", "{0:M/d/yyyy}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Expiry Date" SortExpression="endDate">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("enddate", "{0:M/d/yyy}") %>'></asp:TextBox>
<asp:CalendarExtender ID="TextBox1_CalendarExtender" runat="server" Enabled="True"
TargetControlID="TextBox1" Format="M/d/yyyy">
</asp:CalendarExtender>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblEndDate" runat="server" Text='<%# Bind("enddate", "{0:M/d/yyyy}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>No valid courses found.</EmptyDataTemplate>
</asp:GridView>
UPDATE: I've been trying all your suggestions, but I get exceptions or nulls or empty strings. I've even re-created the problem in a simpler example and still can't figure it out! I'll keep trying though, and I appreciate any new suggestions.
Part 1 - Missing Text
You are probably getting blank values in the first part due to a need to access a child control:
String str = ((DataBoundLiteralControl)e.Row.Cells[6].Controls[0]).Text;
To see if your cells have any values in debug mode (check text in debug output window):
void grvValidCourses_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
System.Diagnostics.Trace.WriteLine(e.Row.Cells.Count);
foreach (TableCell c in e.Row.Cells)
{
System.Diagnostics.Trace.WriteLine(c.Text);
}
}
}
Part 2 - Missing Control
This is wrong:
Label lbl = (Label) grvValidCourses.FindControl("lblEndDate"); // null
You can't search the gridview for a row's control. You need to search the row.
Label lblProductOptionGrpName = (Label)e.Row.FindControl("lblProductOptionGrpName");
Part 3 - Accessing DataItem
DataBinder.Eval(e.Row.DataItem, "ColumnName")
Finally, I'm not sure what you're doing with your anonymous types, but you may need to check the contents before accessing properties:
if(MyControl.GetType() == typeof(HyperLink))
{
HyperLink TestLink = (HyperLink)MyControl;
TestLink .Visible = false;
}
Okay I finally figured out what is going on! I can only access the bound field through the row (e.g. e.Row.Cells[index].Text). So I used the bound field to get the ID of my item, then found the item in the database, got the date, compared it, and highlighted the row's cells. Not the most efficient way, but it works.
Code from simple sample:
Grid View Front End
<asp:GridView ID="gdv" runat="server" AutoGenerateColumns="True" OnSelectedIndexChanged="gdv_SelectedIndexChanged">
<Columns>
<asp:CommandField ShowSelectButton="True" SelectText="Select" />
<asp:BoundField DataField="id" HeaderText="#" ReadOnly="True" />
<asp:TemplateField HeaderText="CategoryName" >
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Description" >
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("desc") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Label ID="lblSelected" runat="server" Text="No row selected"></asp:Label>
Code Behind Page
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) {
var qry = ctx.Categories
.Select(c => new {
id = c.CategoryID,
name = c.CategoryName,
desc = c.Description,
});
gdv.DataSource = qry;
gdv.DataBind();
}
}
protected void gdv_SelectedIndexChanged(object sender, EventArgs e) {
selectRow();
}
private void selectRow() {
GridViewRow row = gdv.SelectedRow;
String strId = row.Cells[1].Text; // Bound Field column
lblSelected.Text = strId;
// use ID to get object from database...
}
If you can post markup, then it will be possible to figure out your issue.
You are doing this in wrong way,
this DataRowView rowView = (DataRowView)e.Row.DataItem;
should be DataRow rowView = ((DataRowView)e.Row.DataItem).Row;
protected void gridPanne_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType==DataControlRowType.DataRow)
{
Label label = (Label)e.Row.FindControl("Label4");
lbl.Text += " ** / ** "+label.Text;
}
}

Categories

Resources