I'm using ASP C# VS 2015. I managed to generate a gridview with data from MySQL. The update and delete command appear as links and I managed to hooked them up to the events properly.
Now I would like to add a feature to add confirmation before delete plus a message (textbox) for reason of deletion?
How do I do that in .NET?
I'm well versed in PHP and jQuery but still in learning curve in .NET.
Thanks in advance.
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False" DataKeyNames="id"
OnRowDataBound="OnRowDataBound" OnRowEditing="OnRowEditing" OnRowCancelingEdit="OnRowCancelingEdit"
OnRowUpdating="OnRowUpdating" EmptyDataText="No records has been added." OnRowDeleting="OnRowDeleting" OnRowDeleted="OnRowDeleted">
<Columns>
<asp:TemplateField HeaderText="Id" ItemStyle-Width="20">
<ItemTemplate>
<asp:Label ID="lblId" runat="server" Text='<%# Eval("id") %>'></asp:Label>
</ItemTemplate>
<ItemStyle Width="20px"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="Email">
<ItemTemplate>
<asp:Label ID="lblEmail" runat="server" Text='<%# Eval("email") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" ShowDeleteButton="True" DeleteText="Reject" headertext="Controls"></asp:CommandField>
</Columns>
</asp:GridView>
Try this
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string item = e.Row.Cells[0].Text;
foreach (Button button in e.Row.Cells[2].Controls.OfType<Button>())
{
if (button.CommandName == "Delete")
{
button.Attributes["onclick"] = "if(!confirm('Do you want to delete " + item + "?')){ return false; };";
}
}
}
}
Related
I have a gridview with a label and a commandfield for edit.
I want to disable the commandfield if the label contains today's date.
All commandfields of empty labels should be enabled.
How can I achieve that?
Thanks
Aspx -
<asp:GridView ID="gv" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="Schedule Date">
<ItemTemplate>
<asp:Label ID="schedule" runat="server" Text='<%# Eval("Date","{0:dd-MMM-yy}") %>'></asp:Label>
</ItemTemplate>
<asp:CommandField ShowEditButton="true" EditText="Click here to Schedule/Re-Schedule" UpdateText="Submit" HeaderText="Schedule/Re-Schedule" />
</Columns>
</asp:GridView>
its better if you use command field as linkButton:
<asp:GridView ID="gv" runat="server" AutoGenerateColumns="False"
onrowdatabound="gv_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Schedule Date">
<ItemTemplate>
<asp:Label ID="schedule" runat="server" Text='10:25-02-2015'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False"
CommandName="Edit" Text="Edit"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
then you can use row data bound event:
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label schedule = (Label)e.Row.FindControl("schedule");
LinkButton LinkButton1 = (LinkButton)e.Row.FindControl("LinkButton1");
if (schedule.Text == string.Empty)
{
LinkButton1.Enabled = false;
}
else
{
LinkButton1.Enabled = true;
}
}
}
This will help you!
I am using ASP.NET GridView on ASPX page:
<asp:GridView ID="GrdLimitAndUtilization" runat="server" AutoGenerateColumns="False" GridLines="None"
Width="99%" meta:resourcekey="GrdAccountListResource1" OnRowDataBound="GrdLimitAndUtilization_RowDataBound"
ShowHeader="True" rowstyle-cssclass="rowHover" ClientIDMode="Static" CssClass="gridView">
<Columns>
<asp:TemplateField HeaderText="Excess" meta:resourcekey="Excess">
<HeaderStyle HorizontalAlign="Left" Width="120px" CssClass="gridheader" />
<HeaderTemplate> <asp:Label ID="col5a" Text="Excess" runat="server"></asp:Label></HeaderTemplate>
<ItemTemplate>
<asp:HyperLink ID="lnkExcess" runat="server" value='' Text='<%# Bind("Excess") %>'
meta:resourcekey="HyperLink1Resource1"></asp:HyperLink>
<asp:Label ID="Excess_Currency" runat="server" Text='<%# Bind("Currency") %>'></asp:Label>
</ItemTemplate>
<ItemStyle Width="120px" HorizontalAlign="Left" CssClass="customerProductItemTemp gridviewLeftMargin" />
</asp:TemplateField>
</Columns>
</asp:GridView>
I know I can access GridView column by following code:
GrdLimitAndUtilization.Rows[0].Cells[0].ForeColor = System.Drawing.Color.Green;
BUT, How can I access value/text of only HyperLink control with ID="lnkExcess"??
Thanks.
You can use RowDataBound event like this:-
protected void GrdLimitAndUtilization_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
HyperLink lnkExcess = (HyperLink)e.Row.FindControl("lnkExcess");
//Access hyperlink's properties here.
}
}
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.
I have the following database design:
Employee Table: Username, Name, JobTitle, BadgeNo, IsActive, DivisionCode
Divisions Table: SapCode, DivisionShortcut
And I have a GridView that I am using it to add, delete and update/edit the employees information. This information is employee Username, Name, BadgeNo, JobTitle, IsActive and the DivisionShortcut. IsActive is a flag that indicates if the employee is available or in an assignment. I made it as a checkbox and the column should show two values; Active and Inactive. In the Edit mode, the Checkbox will be displayed. If it is checked, then it means the employee is avaiable, otherwise it is inactive.
I wrote the code and everything works fine, but now I am facing two problems and I don't know how to make them work with my code.
The GridView shows True or False instead of Active and Inactive and
I don't know why.
In the Edit mode, the checkbox will be displayed and the values (Active or Inactive) will be displayed besides to it and it shouldn't be displayed. I just want the checkbox to be displayed.
So how to modify them?
ASP.NET code:
<%-- GridView for User Management Subsystem --%>
<asp:GridView ID="GridView1" runat="server" AllowSorting="True"
AutoGenerateColumns="False" DataKeyNames="Username"
DataSourceID="SqlDataSource1" BorderWidth="1px" BackColor="#DEBA84"
CellPadding="3" CellSpacing="2" BorderStyle="None"
BorderColor="#DEBA84">
<FooterStyle ForeColor="#8C4510"
BackColor="#F7DFB5"></FooterStyle>
<PagerStyle ForeColor="#8C4510"
HorizontalAlign="Center"></PagerStyle>
<HeaderStyle ForeColor="White" Font-Bold="True"
BackColor="#A55129"></HeaderStyle>
<Columns>
<asp:CommandField ButtonType="Image" ShowEditButton="true" ShowCancelButton="true"
EditImageUrl="Images/icons/edit24.png" UpdateImageUrl="Images/icons/update24.png"
CancelImageUrl="Images/icons/cancel324.png" />
<asp:TemplateField HeaderText="Division">
<ItemTemplate>
<%# Eval("DivisionShortcut")%>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="DivisionsList" runat="server" DataSourceID="DivisionsListDataSource"
DataTextField="DivisionShortcut" DataValueField="SapCode"
SelectedValue='<%# Bind("DivisionCode")%>'>
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Username" HeaderText="Network ID" ReadOnly="True"
SortExpression="Username" />
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<%# Eval("Name")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEmployeeName" runat="server" Text='<%# Bind("Name")%>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Job Title">
<ItemTemplate>
<%# Eval("JobTitle")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtJobTitle" runat="server" Text='<%# Bind("JobTitle")%>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Badge No.">
<ItemTemplate>
<%# Eval("BadgeNo")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtBadgeNo" runat="server" Text='<%# Bind("BadgeNo")%>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Is Active?">
<ItemTemplate>
<%# Eval("IsActive")%>
</ItemTemplate>
<EditItemTemplate>
<asp:CheckBox ID="isActive" runat="server"
AutoPostBack="true" OnCheckedChanged="isActive_OnCheckedChanged"
Checked='<%# Convert.ToBoolean(Eval("IsActive")) %>'
Text='<%# Eval("IsActive").ToString().Equals("True") ? " Active " : " Inactive " %>'/>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete?">
<ItemTemplate>
<span onclick="return confirm('Are you sure to Delete the record?')">
<asp:ImageButton ID="lnkB" runat="server" ImageUrl="Images/icons/delete24.png" CommandName="Delete" />
</span>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code-behind:
//for updating the (IsActive) column using checkbox inside the GridView
protected void isActive_OnCheckedChanged(object sender, EventArgs e)
{
CheckBox chkStatus = (CheckBox)sender;
GridViewRow gvrow = (GridViewRow)chkStatus.NamingContainer;
//Get the ID which is the NetworkID of the employee
string username = gvrow.Cells[2].Text;
bool status = chkStatus.Checked;
string connString = ConfigurationManager.ConnectionStrings["UsersInfoDBConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(connString);
string updateIsActive = "UPDATE Employee SET IsActive = #IsActive WHERE Username = #Username";
SqlCommand cmd = new SqlCommand(updateIsActive, conn);
cmd.Parameters.AddWithValue("#IsActive", status);
cmd.Parameters.AddWithValue("#Username", username);
try
{
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
catch (SqlException se)
{
throw se;
}
finally
{
cmd.Dispose();
conn.Close();
conn.Dispose();
}
}
UPDATE:
I update my code as following:
ASP.NET Code:
<asp:GridView ID="GridView1" runat="server" AllowSorting="True"
AutoGenerateColumns="False" DataKeyNames="Username"
DataSourceID="SqlDataSource1" OnRowDataBound="GridView1_RowDataBound" BorderWidth="1px" BackColor="#DEBA84"
CellPadding="3" CellSpacing="2" BorderStyle="None"
BorderColor="#DEBA84">
<FooterStyle ForeColor="#8C4510"
BackColor="#F7DFB5"></FooterStyle>
<PagerStyle ForeColor="#8C4510"
HorizontalAlign="Center"></PagerStyle>
<HeaderStyle ForeColor="White" Font-Bold="True"
BackColor="#A55129"></HeaderStyle>
<Columns>
<asp:CommandField ButtonType="Image" ShowEditButton="true" ShowCancelButton="true"
EditImageUrl="Images/icons/edit24.png" UpdateImageUrl="Images/icons/update24.png"
CancelImageUrl="Images/icons/cancel324.png" />
<asp:TemplateField HeaderText="Division">
<ItemTemplate>
<%# Eval("DivisionShortcut")%>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="DivisionsList" runat="server" DataSourceID="DivisionsListDataSource"
DataTextField="DivisionShortcut" DataValueField="SapCode"
SelectedValue='<%# Bind("DivisionCode")%>'>
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Username" HeaderText="Network ID" ReadOnly="True"
SortExpression="Username" />
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<%# Eval("Name")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEmployeeName" runat="server" Text='<%# Bind("Name")%>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Job Title">
<ItemTemplate>
<%# Eval("JobTitle")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtJobTitle" runat="server" Text='<%# Bind("JobTitle")%>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Badge No.">
<ItemTemplate>
<%# Eval("BadgeNo")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtBadgeNo" runat="server" Text='<%# Bind("BadgeNo")%>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Is Active?">
<ItemTemplate>
<asp:Label ID="lblIsActive" runat="server" Text='<%# Eval("IsActive")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:CheckBox ID="isActive" runat="server"
AutoPostBack="true" OnCheckedChanged="isActive_OnCheckedChanged"
Checked='<%# Convert.ToBoolean(Eval("IsActive")) %>'
Text='<%# Eval("IsActive")%>'/>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete?">
<ItemTemplate>
<span onclick="return confirm('Are you sure to Delete the record?')">
<asp:ImageButton ID="lnkB" runat="server" ImageUrl="Images/icons/delete24.png" CommandName="Delete" />
</span>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code-Behind:
//For showing Active or Inactive in the IsActive column instead of True or False
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Here we will select the IsActive column and modify its text
Label isActive = new Label();
isActive = (Label)e.Row.FindControl("lblIsActive");
//Now, after getting the reference, we can set its text
isActive.Text = "Active or Inactive";
// First check Checkedbox is check or not, if not make it grey
//if (e.Row.Cells[6].Text == "False")
// GridView1.BackColor = Color.Gray;
}
}
And I am getting the following error and I don't know why:
For question no: 1
You have to add an Row_DataBound Event of your grid view, in which you select the IsActive column and replaced its text by Active and InActive. But before going to code behind make a little change to you aspx code: In your item template instead of direct binding place a label control and bind it as I does in the below code:
<asp:TemplateField HeaderText="Is Active?">
<ItemTemplate>
<asp:Label ID="lblIsActive" runat="server" Text='<%# Eval("IsActive") %>' ></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:CheckBox ID="isActive" runat="server"
AutoPostBack="true" OnCheckedChanged="isActive_OnCheckedChanged"
Checked='<%# Convert.ToBoolean(Eval("IsActive")) %>'
Text='<%# Eval("IsActive").ToString().Equals("True") ? " Active " : " Inactive " %>'/>
</EditItemTemplate>
</asp:TemplateField>
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// here you will select the IsActive column and modify it's text
Label isActive=new Label();
isActive = (Label) e.row.FindControl("lblIsActive");
// after getting the reference set its text
isActive.Text="Active or InActive";
}
}
For question no 2:
Remove the condition form this
Eval("IsActive").ToString().Equals("True") ? " Active " : " Inactive " %>'
and replace it with
Eval("IsActive")
Now check boxes will be displayed.
Updated Answer:
You are receiving an object reference not found error, Please debug your site and check it why you are unable to get the exact reference. I saw you code and it looks that your code is fine.
To prove that my code is working,I created a gridview with a single column
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
// and bind this grid view in the Page_Load of my Page
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("name");
DataRow row = dt.NewRow();
row[0] = "Waqar Janjua";
dt.Rows.Add(row);
GridView1.DataSource = dt;
GridView1.DataBind();
}
// When I view this page in the browser it shows "Waqar Janjua"
// Now to update the columns text, I add the following code and it works.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowState != DataControlRowState.Edit)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label l = new Label();
l = (Label)e.Row.FindControl("Label1");
l.Text = "waqar";
}
}
}
// When I run this page now, it shows me "Waqar" not "Waqar Janjua" The code works for me.
It is returning "true" or "false" as it is expecting a boolean data type from IsActive. If you want to change that out put, I suspect you need to amend this conditionally on the ItemDataBound event of the grid.
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;
}
}