How can I select all data from GridView's current row - c#

How can I select all data from GridViews current row..
I have a column for edit link in GridView. When "Edit" link button is clicked, I want to use that selected row's data. I am trying the following code, but it's returning me with an empty value
protected void gv_RowEditing(object sender, GridViewEditEventArgs e)
{
gv.EditIndex = -1;
GridViewRow gvRow = gv.Rows[ e.NewEditIndex];
string selectedID = gvRow.Cells[3].Text;
}
<asp:GridView runat = "server" ID="gvRange0" SkinID="gridView" AutoGenerateColumns="False"
AllowSorting="True" OnRowCancelingEdit="gvRange_RowCancelingEdit" OnRowDeleting="gvRange_RowDeleting"
OnRowEditing="gvRange_RowEditing" OnRowUpdating="gvRange_RowUpdating"
Width="684px" OnRowDataBound="gvRange_RowDataBound"
DataMember="DefaultView" OnPageIndexChanged="gvRange_PageIndexChanged"
OnPageIndexChanging="gvRange_PageIndexChanging" OnSorting="gvRange_Sorting" DataKeyNames = "RANGE_ID"
OnSelectedIndexChanged="gvRange_SelectedIndexChanged" Height="65px" >
<Columns>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<ControlStyle Width="2px" />
<asp:LinkButton ID="lnkDelete0" runat="server" CssClass="lnk"
CausesValidation="False" CommandName="Delete"
Text="Delete" Visible="false"></asp:LinkButton>
<asp:CheckBox runat="server" ID="chkSelect" CssClass="lbl" Text="" AutoPostBack="False" OnCheckedChanged="chkSelect_CheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<controlStyle width="2px" />
<asp:LinkButton ID="lnkEdit" runat="server" CssClass="lnk" CausesValidation="False" CommandName="Edit"
Text="Edit" ></asp:LinkButton>
</ItemTemplate>
<ItemStyle Width="5px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Ranges" SortExpression="Sort_Ranges">
<ControlStyle Width="5px" />
<ItemTemplate>
<%#DataBinder.Eval(Container.DataItem,"Min_Age") %>
<%# CheckNull(DataBinder.Eval(Container.DataItem,"Max_Age")) %>
</ItemTemplate>
<%-- <ItemTemplate>--%>
<%--<asp:Label ID="lblStageName" CssClass="lbl" runat="server" Text='<%# Bind("Age_Range") %>' Width="1px"></asp:Label>--%>
<%-- </ItemTemplate>--%>
</asp:TemplateField>
<asp:TemplateField HeaderText="Range ID">
<ItemTemplate><%#DataBinder.Eval(Container.DataItem,"RANGE_ID") %></ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
There are 4 columns in the GridView. One contains check box, second is link button for edit, third databound with some value, fourth is the column which I want to use to get some values from database(that is primary key there) and this column is hidden.

sometime in gridview cell create child controls.
you can try this code. may be solve it.
protected void gv_RowEditing(object sender, GridViewEditEventArgs e)
{
gv.EditIndex = -1;
GridViewRow gvRow= (GridViewRow)(((Button)e.CommandSource).NamingContainer);
foreach (TableCell Tc in gvRow.Cells)
{
//if you are not getting value than find childcontrol of TabelCell.
string sss = c.Text;
foreach (Control ctl in Tc.Controls)
{
//Child controls
Label lb = ctl as Label;
string s = lb.Text;
sb.Append(s + ',');
}
}
}

I've noticed that you say you need to access the 4th column but you're using gvRow.Cells[3].Text;
The indexing in the Cell object is done from 1, so if you need to access the 4th row in the grid view try this:
string selectedID = gvRow.Cells[4].Text;
EDIT:
Could you please confirm two things for me
1)When you click on lnkEdit is the GridView1_RowEditing event being raised?
2)If yes, is the e.NewEditIndex value always showing up as '0'?
Attempt clicking the edit link on different rows, is the result always '0'?

Related

How to get cell value in a GridView on LinkButton Click Event? Or RowCommand?

I Have a GridView which conntains multiple records and couple of Link Buttons Named Edit and Detail. Now i want to Get the Name of the User (NOT Index), when a user click on Detail Link Button. Like "Name", "FatherName" etc
Here is the .aspx code
<asp:GridView ID="dgvEmployeesInformation" runat="server" CssClass=" table table-bordered table-hover table-responsive" DataKeyNames="Id" AutoGenerateColumns="False" OnRowCommand="dgvEmployeesInformation_RowCommand" OnRowDataBound="dgvEmployeesInformation_RowDataBound" AllowPaging="True" AllowSorting="True" OnPageIndexChanging="dgvEmployeesInformation_PageIndexChanging">
<%--1st Column--%>
<Columns>
<asp:BoundField HeaderText="ID" DataField="Id" ControlStyle-BackColor="#0066ff" Visible="False">
<ControlStyle BackColor="#0066FF"></ControlStyle>
</asp:BoundField>
<asp:BoundField HeaderText="Name" DataField="Name" />
<asp:BoundField HeaderText="Employee No" DataField="EmployeeNo" />
<asp:BoundField HeaderText="Father Name" DataField="FatherName" />
<asp:HyperLinkField DataNavigateUrlFields="Id" DataNavigateUrlFormatString="AddEmployeeBasic1.aspx?thid={0}" HeaderText="Update" NavigateUrl="~/AddEmployeeBasic1.aspx" Text="Edit" />
<asp:TemplateField HeaderText="Action" ShowHeader="True">
<ItemTemplate>
<asp:LinkButton ID="lbDelete" runat="server" CausesValidation="False" CommandName="Delete" Text="Delete"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server" ID="lbDetail" OnClick="lbDetail_Click" DataNavigateUrlFields="Id" DataNavigateUrlFormatString="EmployeesDetails.aspx?EmpID={0}" NavigateUrl="~/EmployeesDetails.aspx" HeaderText="Show Detail" Text="Detail"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Here is the lbDetail_Click Code
protected void lbDetail_Click(object sender, EventArgs e)
{
GridViewRow clickedRow = ((LinkButton)sender).NamingContainer as GridViewRow;
Label lblUserName = (Label)clickedRow.FindControl("Name");
EmployeeID.EmpName = lblUserName.ToString();
}
When i put my program on Debugging mode, the lblUserName return NULL
Here is the picture.
What i want is that, when a user click on Detail LinkButton, then on lbDetail Click event, it gets the Name of the Employee and store it in a static variable. Following is the picture
I don't understand how to solve this problem. Please help me through this. Your help will be really appreciated.
I would just add data attributes to the details button then get it's values at code behind.
For example:
1.) Add new data-myData='<%# Eval("Name") %>' attribute and its value to button
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server" ID="lbDetail" OnClick="lbDetail_Click" Text="Detail" data-ID='<%# Eval("ID") %>' data-myData='<%# Eval("Name") %>' ></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
2.) Get those data from event handler
protected void lbDetail_Click(object sender, EventArgs e)
{
LinkButton button = (LinkButton)sender;
var name = (string)button.Attributes["data-myData"];
var selectedID = (string)button.Attributes["data-ID"];
Session["selectedID"] = selectedID ;
}
lblUserName is null because it's not a Label, but a BoundField.
What you could do it get the Cell value.
protected void lbDetail_Click(object sender, EventArgs e)
{
GridViewRow clickedRow = ((LinkButton)sender).NamingContainer as GridViewRow;
Label1.Text = clickedRow.Cells[1].Text;
}
Or use a TemplateField that does contain a Label Name
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="Name" runat="server" Text='<%# Eval("Name")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
Here is how your code should look:
protected void lbDetail_Click(object sender, EventArgs e)
{
GridViewRow clickedRow = ((LinkButton)sender).NamingContainer as GridViewRow;
var username = clickedRow.Cells[1].Text;
if(string.IsNullOrEmpty(username))
{
return;
}
EmployeeID.EmpName = username;
}

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.

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
}
}

Hidden fields in a grid won't import to a edit form

I've got a grid that only displays one piece of information such as a title. Other fields are hidden. When you click edit a modal popup displays a form and imports the information from the grid for editing. The information in hidden field are not imported though. I don't want to display all the information in the grid because I have only room for the title.
How can I make this work? Thanks. Risho
<asp:GridView ID="gvForum" runat="server" DataSourceID="odsForumApproval" DataKeyNames="id" Width="200px"
RepeatColumns="1" DataKeyField="id" CssClass="gridview"
AutoGenerateColumns="False" GridLines="None" OnSelectedIndexChanged="_OnCommand">
<AlternatingRowStyle CssClass="altbgcolor" />
<Columns>
<asp:BoundField DataField="title" />
<asp:TemplateField >
<ItemTemplate>
<asp:HiddenField runat="server" ID="hfId" Value='<%# Eval("id") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField >
<ItemTemplate>
<asp:HiddenField runat="server" ID="hfDesc" Value='<%# Eval("description") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField >
<ItemTemplate>
<asp:LinkButton ID="lnkbtn" Text="Approve" runat="server" onclick="lnkbtn_Click"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
protected void lnkbtn_Click(object sender, EventArgs e)
{
LinkButton btndetails = sender as LinkButton;
GridViewRow gvrow = (GridViewRow)btndetails.NamingContainer;
lblID.Value = gvrow.Cells[1].Text;
txtTitle.Text = gvrow.Cells[0].Text;
lblMessage.Text = gvrow.Cells[3].Text;
this.ModalPopupExtender1.Show();
}
The Cell-Text is empty if you are using TemplateFields with nested controls . You need to get the reference to the controls and use their appropriate properties(like TextBox.Text or HiddenField.Value). Therefor you can use FindControl on the GridViewRow:
var hfId = (HiddenField)gvrow.FindControl("hfId");
var hfDesc = (HiddenField)gvrow.FindControl("hfDesc");
txtTitle.Text = gvrow.Cells[0].Text;
lblID.Value = hfId.Value;
txtTitle.Text = hfdesc.Value;

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