I have a Gridview in which I want to add a row when the grid is empty using EmptyDataTemplate. The problem is when the grid is empty and I try to add a row, no error occurs but the data row is not added. The Header row is added but not the data. When I put a breakpoint at the start of the RowCommand method, it is not triggered. I can't understand why the event will not trigger. When there is a row present the RowCommand event is triggered and I can add a second row but not an initial row.
This is my markup:
<asp:GridView ID="UserGroupGridView" runat="server" AutoGenerateColumns="False"
Caption="Group Information" CaptionAlign="Top" CssClass="grid"
AllowPaging="true" PageSize="10"
HorizontalAlign="Left" ShowHeaderWhenEmpty="True" ShowFooter="true" DataKeyNames="GroupID"
onrowcommand="UserGroupGridView_RowCommand">
<Columns>
<asp:TemplateField HeaderText="GroupID">
<ItemTemplate>
<asp:Label ID="uggvLblGroupID" runat="server" Text='<%# Bind("GroupID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Group Name">
<HeaderTemplate> Group Name
<asp:ImageButton ID="uggvGroupFilter" runat="server" ImageUrl="Images/filter.png" OnClientClick="return ShowHideFilterTxtBox('uggvTxtNameFilter')" />
<asp:TextBox ID="uggvTxtNameFilter" runat="server" AutoPostBack="true" style="display:none;" ClientIDMode="Static" OnTextChanged="uggvGridFilter_TextChanged">
</asp:TextBox>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="uggvLblGroupName" runat="server" Text='<%# Bind("GroupName") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="uggvTxtBoxEditGroupName" runat="server" Text='<%# Bind("GroupName") %>'></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldEditGroupName" ControlToValidate="uggvTxtBoxEditGroupName" runat="server"
ErrorMessage="Required field." ValidationGroup="EditGroupNameValidation" Display="Dynamic" CssClass="message-error">
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="MaxValEditGroupName" ControlToValidate="uggvTxtBoxEditGroupName" runat="server"
ErrorMessage="Maximumn length is 80." ValidationGroup="EditGroupNameValidation" Display="Dynamic" CssClass="message-error"
ValidationExpression="^.{1,80}$" >
</asp:RegularExpressionValidator>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="uggvTxtBoxInsertGroupName" runat="server" Text='<%# Bind("GroupName") %>' ClientIDMode="Predictable"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldInsertGroupName" ControlToValidate="uggvTxtBoxInsertGroupName" runat="server"
ErrorMessage="Required field." ValidationGroup="InsertGroupNameValidation" Display="Dynamic" CssClass="message-error">
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="MaxValInsertGroupName" ControlToValidate="uggvTxtBoxInsertGroupName" runat="server"
ErrorMessage="Maximumn length is 80." ValidationGroup="InsertGroupNameValidation" Display="Dynamic" CssClass="message-error"
ValidationExpression="^.{1,80}$" >
</asp:RegularExpressionValidator>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Action" ItemStyle-Wrap="false" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Button ID="uggvEditButton" runat="server" CausesValidation="False" CommandName="Edit"
Text="Edit" CssClass="gridActionbutton">
</asp:Button>
<asp:Button ID="uggvDeleteButton" runat="server" CausesValidation="False" CommandName="Delete"
Text="Delete" CssClass="gridActionbutton" OnClientClick="return confirm('Are you sure you want to delete this Group Information?')" >
</asp:Button>
</ItemTemplate>
<EditItemTemplate>
<asp:Button ID="uggvUpdateButton" runat="server" CausesValidation="True" ValidationGroup="EditGroupNameValidation" CommandName="Update"
Text="Update" CssClass="gridActionbutton"></asp:Button>
<asp:Button ID="uggvCancelButton" runat="server" CausesValidation="False" CommandName="Cancel"
Text="Cancel" CssClass="gridActionbutton"></asp:Button>
</EditItemTemplate>
<FooterTemplate>
<asp:Button ID="uggvAddButton" runat="server" CommandName="Add" Text="Add Group" Width="90%" CausesValidation="true"
CssClass="gridActionbutton" ValidationGroup="InsertGroupNameValidation">
</asp:Button>
</FooterTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
<tr>
<th>GroupID</th>
<th>Group Name</th>
<th>Action</th>
</tr>
<tr>
<td colspan="3" style="text-align:center;">
No user-defined groups were found for you. Insert a group name and click the 'Add Group' Button.
</td>
</tr>
<tr>
<td></td>
<td>
<asp:TextBox ID="uggvTxtBoxInsertGroupName" runat="server" Width="90%"></asp:TextBox>
</td>
<td>
<asp:Button ID="uggvAddButtonEmpty" runat="server" CommandName="Add" Text="Add Group" Width="90%" CausesValidation="false"
CssClass="gridActionbutton">
</asp:Button>
</td>
</tr>
</EmptyDataTemplate>
</asp:GridView>
This is my RowCommand event:
protected void UserGroupGridView_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
if (e.CommandName.Equals("Add"))
{
//Get the Footer controls that have the new entry data
Control tFooterControls = CommonMethods.getFooterControls(UserGroupGridView);
string tstrGroupName = (tFooterControls.FindControl("uggvTxtBoxInsertGroupName") as TextBox).Text;
string tstrLoginUserID = CommonMethods.ParseUserID(User.Identity.Name);
//Insert into the database
m_pagingClient.InsertGroup(m_strUserID, tstrGroupName, tstrLoginUserID);
//Rebind the grid with the new data
populateGroupGrid();
}
}
catch (Exception ex)
{
logger.ErrorException(ex.Message, ex);
Response.Redirect("~/Error.aspx?use=" + m_strUserType, false);
}
}
This grid is the parent grid of a nested grid. But I don't think that should matter.
Can anyone see what I am doing wrong?
Thanks.
UPDATE
Below is the validation that I had in the emptytemplatedata control
<EmptyDataTemplate>
<tr>
<th></th>
<th>GroupID</th>
<th>Group Name</th>
<th>Action</th>
</tr>
<tr>
<td colspan="4" style="text-align:center;">
No user-defined groups were found for you. Insert a group name and click the 'Add Group' Button.
</td>
</tr>
<tr>
<td></td>
<td></td>
<td>
<asp:TextBox ID="uggvTxtBoxInsertGroupName" runat="server" Width="90%"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldInsertGroupNameEmpty" ControlToValidate="uggvTxtBoxInsertGroupName" runat="server"
ErrorMessage="Required field." ValidationGroup="InsertGroupNameValidationEmpty" Display="Dynamic" CssClass="message-error">
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="MaxValInsertGroupNameEmpty" ControlToValidate="uggvTxtBoxInsertGroupName" runat="server"
ErrorMessage="Maximumn length is 80." ValidationGroup="InsertGroupNameValidationEmpty" Display="Dynamic" CssClass="message-error"
ValidationExpression="^.{1,80}$" >
</asp:RegularExpressionValidator>
</td>
<td>
<asp:Button ID="uggvAddButtonEmpty" runat="server" CommandName="Add" Text="Add Group" Width="90%" CausesValidation="true"
CssClass="gridActionbutton" ValidationGroup="InsertGroupNameValidationEmpty">
</asp:Button>
</td>
</tr>
</EmptyDataTemplate>
Why would the required validation trigger after I added a value in the text box?
UPDATE
This is my Page_Load code:
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (!IsPostBack)
{
populateGroupGrid();
if (m_strUserID.Equals("Global"))
{
UserGroupGridView.Caption = "Global Group Information";
}
else
{
UserGroupGridView.Caption = "User Group Information";
}
}
}
catch (Exception ex)
{
logger.ErrorException(ex.Message, ex);
Response.Redirect("~/Error.aspx?use=" + m_strUserType, false);
}
}
This is my grid populate method.
private void populateGroupGrid()
{
try
{
HiddenField hdnFldFilter = (HiddenField)UserGroupGridWrapper.FindControl("uggvHidGridFilter");
m_strXmlTableData = m_pagingClient.GetGroups(m_strUserID);
m_dtGroupInfo = CommonMethods.ParseXML(m_strXmlTableData);
ViewState["GroupInfo"] = m_dtGroupInfo;
if (!String.IsNullOrEmpty(hdnFldFilter.Value))
{
m_dtGroupInfo.DefaultView.RowFilter = hdnFldFilter.Value;
}
UserGroupGridView.DataSource = m_dtGroupInfo;
UserGroupGridView.DataBind();
}
catch (Exception ex)
{
logger.ErrorException(ex.Message, ex);
Response.Redirect("~/Error.aspx?use=" + m_strUserType, false);
}
}
I fixed the problem by starting with the basic grid and adding everything back. It is working now but I don't know what in the gridview that was causing the problem. But it all works now.
Related
I have a Gridview that has 3 columns, ID, Text, Action. I am using VS2010. When the grid is empty and the user enters text in the text field, I would like the field to be validated as a required field and a max. length. These validations work fine if there is data in the grid but when the grid is empty, the required validation is triggered after the user enters data. If the user enters a second time, the data is successfully added to the database and refreshed in the grid.
Secondly, the column headers will not show when the grid is empty even though I had the attribute: ShowHeaderWhenEmpty="true"
This is my markup:
<asp:GridView ID="SubjectInfoGridView" runat="server"
AutoGenerateColumns="false" Caption="Personal Subject List"
CaptionAlign="Top" CssClass="grid"
RowStyle-Wrap="true" HorizontalAlign="Left" ShowFooter="true"
AllowPaging="false" PageSize="5" ShowHeaderWhenEmpty="true"
onrowcancelingedit="SubjectInfoGridView_RowCancelingEdit"
onrowediting="SubjectInfoGridView_RowEditing"
onrowdeleting="SubjectInfoGridView_RowDeleting"
onrowcommand="SubjectInfoGridView_RowCommand"
onrowupdating="SubjectInfoGridView_RowUpdating">
<Columns>
<asp:TemplateField HeaderText="Subject ID">
<ItemTemplate>
<asp:Label ID="sigvLblSubjectID" runat="server" Text='<%# Bind("SubjectID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Subject" ItemStyle-Wrap="false">
<ItemTemplate>
<asp:Label ID="sigvLblSubject" runat="server" Text='<%# Bind("Subject") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="sigvTxtBoxEditSubject" runat="server" Text='<%# Bind("Subject") %>'></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldEditSubject" ControlToValidate="sigvTxtBoxEditSubject" runat="server"
ErrorMessage="Required field." ValidationGroup="EditSubjectValidation" Display="Dynamic" CssClass="message-error">
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="MaxValEditSubject" ControlToValidate="sigvTxtBoxEditSubject" runat="server"
ErrorMessage="Maximumn length is 80." ValidationGroup="EditSubjectValidation" Display="Dynamic" CssClass="message-error"
ValidationExpression="^.{1,80}$" >
</asp:RegularExpressionValidator>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="sigvTxtBoxInsertSubject" runat="server" Text='<%# Bind("Subject") %>'></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldInsertSubject" ControlToValidate="sigvTxtBoxInsertSubject" runat="server"
ErrorMessage="Required field." ValidationGroup="InsertSubjectValidation" Display="Dynamic" CssClass="message-error">
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="MaxValInsertSubject" ControlToValidate="sigvTxtBoxInsertSubject" runat="server"
ErrorMessage="Maximumn length is 80." ValidationGroup="InsertSubjectValidation" Display="Dynamic" CssClass="message-error"
ValidationExpression="^.{1,80}$" >
</asp:RegularExpressionValidator>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Action" ItemStyle-Wrap="false" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Button ID="sigvEditButton" runat="server" CausesValidation="False" CommandName="Edit"
Text="Edit" CssClass="gridActionbutton">
</asp:Button>
<asp:Button ID="sigvDeleteButton" runat="server" CausesValidation="False" CommandName="Delete"
Text="Delete" CssClass="gridActionbutton" OnClientClick="return confirm('Are you sure you want to delete this Device Information?')" >
</asp:Button>
</ItemTemplate>
<EditItemTemplate>
<asp:Button ID="sigvUpdateButton" runat="server" CausesValidation="True" ValidationGroup="EditSubjectValidation" CommandName="Update"
Text="Update" CssClass="gridActionbutton"></asp:Button>
<asp:Button ID="sigvCancelButton" runat="server" CausesValidation="False" CommandName="Cancel"
Text="Cancel" CssClass="gridActionbutton"></asp:Button>
</EditItemTemplate>
<FooterTemplate>
<asp:Button ID="sigvAddButton" runat="server" CommandName="Add" Text="Add Subject" Width="90%" CausesValidation="true"
CssClass="gridActionbutton" ValidationGroup="InsertSubjectValidation">
</asp:Button>
</FooterTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
<tr>
<td colspan="3" style="text-align:center;">
No User-defined Subjects were found for you. Subjects can be added by clicking the 'Add Subject' Button.
</td>
</tr>
<tr>
<td></td>
<td>
<asp:TextBox ID="sigvTxtBoxInsertSubject" runat="server" Text='<%# Bind("Subject") %>' Width="90%"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldInsertSubjectEmpty" ControlToValidate="sigvTxtBoxInsertSubject" runat="server"
ErrorMessage="Required field." ValidationGroup="InsertSubjectValidation" Display="Dynamic" CssClass="message-error">
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="MaxValInsertSubjectEmpty" ControlToValidate="sigvTxtBoxInsertSubject" runat="server"
ErrorMessage="Maximumn length is 80." ValidationGroup="InsertSubjectValidation" Display="Dynamic" CssClass="message-error"
ValidationExpression="^.{1,80}$" >
</asp:RegularExpressionValidator>
</td>
<td>
<asp:Button ID="sigvAddButtonEmpty" runat="server" CommandName="Add" Text="Add Subject" Width="90%" CausesValidation="true"
CssClass="gridActionbutton" ValidationGroup="InsertSubjectValidation">
</asp:Button>
</td>
</tr>
</EmptyDataTemplate>
</asp:GridView>
So, why won't the headers show when the grid is empty and what am I doing wrong with the validation that triggers the RequiredValidation after data is entered in the field?
Thanks!
UPDATE
I solved the 'Header problem' but just adding them to the EmptyDataTemplate. But the validation is still a problem.
I did this using VS2012 at another company and it was not a problem. I tried making the TextBox id different than the Insert ID and it still gives the same error.
I figured it out...
In case anybody else has this problem.
To correct the validation, I removed the text binding (Text='<%# Bind("Subject") %>'). Then I changed the ID for the Subject field to the same as in the Footer when I add a row when there is data. This allows me to only check one control within the RowBound event.
This is the data row in the EmptyDataTemplate:
<tr>
<td></td>
<td>
<asp:TextBox ID="sigvTxtBoxInsertSubject" runat="server" Width="90%"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldInsertSubjectEmpty" ControlToValidate="sigvTxtBoxInsertSubject" runat="server"
ErrorMessage="Required field." ValidationGroup="InsertSubjectValidationEmpty" Display="Dynamic" CssClass="message-error">
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="MaxValInsertSubjectEmpty" ControlToValidate="sigvTxtBoxInsertSubject" runat="server"
ErrorMessage="Maximumn length is 80." ValidationGroup="InsertSubjectValidationEmpty" Display="Dynamic" CssClass="message-error"
ValidationExpression="^.{1,80}$" >
</asp:RegularExpressionValidator>
</td>
<td>
<asp:Button ID="sigvAddButtonEmpty" runat="server" CommandName="Add" Text="Add Subject" Width="90%" CausesValidation="true"
CssClass="gridActionbutton" ValidationGroup="InsertSubjectValidationEmpty" >
</asp:Button>
</td>
</tr>
<div>
<table>
<tr>
<td>
<asp:Label runat="server" text="Search"></asp:Label>
</td>
<td>
<asp:TextBox runat="Server" placeholder="Enter EmpId" id="txtSearch">
</asp:TextBox>
</td>
<td>
<asp:Button ID="btnGo" runat="server" Text="Go" onclick="btnGo_Click"/>
</td>
<td>
<asp:Button ID="btnShowAll" runat="server" Text="ShowAll"
onclick="btnShowAll_Click" />
</td>
</tr>
</table>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField HeaderText="EmpId" DataField="EmpId"/>
<asp:BoundField HeaderText="Employee Name" DataField="EmpName"/>
<asp:BoundField HeaderText="Designation" DataField="EmpDesgn"/>
<asp:BoundField HeaderText="Salary" DataField="Sal"/>
<asp:TemplateField HeaderText="Salary Status">
<ItemTemplate>
<asp:Button runat="Server" id="btnPay" text="Pay" CommandName="Pay"
Visible='<%#Eval("Status").Equals("Paid")?false:true %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
I want to pay the salary of unpaid employees on clicking the pay button as pay button is showing only for unpaid salaries.
You can do this using OnRowCommand event. Add the event handler to the gridview
OnRowCommand="GridView1_RowCommand"
Bind the command argument to your button
<asp:TemplateField HeaderText="Salary Status">
<ItemTemplate>
<asp:Button runat="Server" id="btnPay" text="Pay" CommandName="Pay"
Visible='<%#Eval("Status").Equals("Paid")?false:true %>'
CommandArgument = '<%#Eval("EmpId")%>'
/>
</ItemTemplate>
</asp:TemplateField>
Then in the RowCommand event you can catch the EmpId from the command argument, pay the salary and rebind the grid view
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if(e.CommandName=="Pay")
{
// get the command argument.
string empId = e.CommandArgument as string;
//you code here to pay the salary
//ReBind Gridview to refresh
}
}
<asp:Repeater ID="RptrSearchedPhotographer" runat="server"
onitemcommand="RptrSearchedPhotographer_ItemCommand"
onitemdatabound="RptrSearchedPhotographer_ItemDataBound">
<ItemTemplate>
<tr>
<td>
<asp:Label ID="LblContactInfo" runat="server" Text='<%# Eval("ContactInfo")%>'/>
<asp:TextBox ID="TxtContactInfo" runat="server" Text='<%#Eval("ContactInfo") %>' Visible="false" ></asp:TextBox>
</td>
<td>
<asp:LinkButton ID="LnkDelete" runat="server" CommandArgument='<%#Eval("Id") %>' CommandName="delete">Delete</asp:LinkButton>
<asp:LinkButton ID="lnkEdit" runat="server" CommandArgument='<%#Eval("Id") %>' CommandName="edit" EnableViewState ="true">Edit</asp:LinkButton>
<asp:LinkButton ID="lnkUpdate" runat="server" CommandArgument='<%#Eval("Id") %>' CommandName="update" Visible="false" EnableViewState="true">Update</asp:LinkButton>
<asp:LinkButton ID="LinkCancel" runat="server" CommandName="cancel" Visible="false">cancel</asp:LinkButton>
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
my .cs code is...
if (e.CommandName.Equals("update"))
{
TextBox DetailNote = (TextBox)e.Item.FindControl("txtDetailNote");
string s = DetailNote.Text;
}
But here... It gives the me old value of s from textbox. I want new value which is inserted during run time... I googled a lot... but it doesn't work...
I had this issue, I solved it by adding an "if(!Page.IsPostBack)" before databinding my repeater in the page_load function.
I have a DataGrid with 4 columns and a DataList with 5 columns. The DataList resides inside the DataGrid as another separate column by itself.
Everything is coming out fine, except that the first row in the datagrid does not display the contents of the datalist. It's as if everything in my datalist should be pushed up by a 1 row to display the data correctly.
I have validated (during debugging) that the data is coming out fine in the datalist for the corresponding first row of the datagrid, but it doesn't get rendered on the first row of the datagrid. It starts to get rendered on the second row of the datagrid.
I've been over this numerous times with the markup and the codebehind, and can't figure out why this is happening. Any help would be appreciated.
Below is my code:
HTML
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="referrals.ascx.cs" Inherits="dpbrokers.dpbrokers.referrals"
TargetSchema="http://schemas.microsoft.com/intellisense/ie5" %>
<div align="center">
<asp:Label ID="errormessage" runat="server" Visible="False" /></div>
<asp:DataGrid ID="lstReferrals" runat="server" DataKeyField="ReferringAffiliateID"
AutoGenerateColumns="false" CellPadding="4" OnItemDataBound="lstReferrals_ItemDataBound">
<AlternatingItemStyle Font-Size="9pt" CssClass="small" BackColor="#C2D6FA"></AlternatingItemStyle>
<ItemStyle Font-Size="9pt" CssClass="small" BackColor="White"></ItemStyle>
<HeaderStyle Font-Size="11pt" Font-Bold="True" ForeColor="White" BackColor="#ABACAD">
</HeaderStyle>
<Columns>
<asp:TemplateColumn HeaderText="Referring Affiliate">
<ItemTemplate>
<asp:HyperLink Text='<%# DataBinder.Eval(Container.DataItem, "ReferringAffiliateName") %>'
NavigateUrl='<%# EditURL("Referral",DataBinder.Eval(Container.DataItem, "ReferralID").ToString(),"Edit",0) %>'
runat="server" ID="Hyperlink1" />
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="SkyCard Awarded">
<ItemTemplate>
<asp:Label ID="itemAward" runat="server" Text='<%# IsAwarded(DataBinder.Eval(Container.DataItem, "IsAwarded").ToString()) %>' />
</ItemTemplate>
</asp:TemplateColumn>
<asp:BoundColumn DataField="DSMAffiliateName" HeaderText="District Sales Manager">
</asp:BoundColumn>
<asp:BoundColumn DataField="DSMAffiliatePhone" HeaderText="DSM Phone"></asp:BoundColumn>
<asp:TemplateColumn>
<ItemTemplate>
<asp:DataList ID="DetailList" ItemStyle-CssClass="small" DataSource="<%# riReferrals %>"
runat="server" Width="100%">
<HeaderTemplate>
<table width="100%" cellpadding="4" border="1">
<tr bgcolor="#ABACAD" class="normalwhite">
<td width="25%">
Referral Name
</td>
<td width="20%">
Phone Number
</td>
<td width="30%">
Email
</td>
<td>
Referred On
</td>
<td>
Is Member?
</td>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr class="small">
<td>
<asp:HyperLink Text='<%# DataBinder.Eval(Container.DataItem, "ContactName") %>' NavigateUrl='<%# EditURL("ReferralID",DataBinder.Eval(Container.DataItem, "ReferralID").ToString(),"Edit",0) %>'
runat="server" ID="Hyperlink2" />
</td>
<td>
<%# FormatPhone(DataBinder.Eval(Container.DataItem,"Phone").ToString()) %>
</td>
<td>
<%# FormatForEmail(DataBinder.Eval(Container.DataItem, "Email").ToString())%>
</td>
<td>
(<%# DataBinder.Eval(Container.DataItem,"Created", "{0:g}") %>)
</td>
<td>
(<%# IsMember(DataBinder.Eval(Container.DataItem, "JoinedON").ToString())%>)
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:DataList>
<div align="right">
<asp:ImageButton ID="Button1" CommandName="award" ImageUrl="~/images/dpbbuttons/awardbutton.gif"
AlternateText="Award SkyCard" runat="server" /></div>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
<PagerStyle Mode="NumericPages"></PagerStyle>
</asp:DataGrid>
CODE BEHIND
public ArrayList riReferrals;
protected void Page_Load(System.Object sender, System.EventArgs e)
{
if (!Page.IsPostBack)
LoadReferrals();
}
private void LoadReferrals()
{
try
{
ReferralController objReferral = new ReferralController();
lstReferrals.DataSource = objReferral.GetReferrals();
lstReferrals.DataBind();
}
catch (Exception ex)
{
Response.Write(ex);
CLogError clsLogError = new CLogError(ex, Request, Session, Context.User.Identity.Name);
clsLogError.LogError();
}
}
public void lstReferrals_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
switch (e.Item.ItemType)
{
case ListItemType.Item:
case ListItemType.AlternatingItem:
lbl1 = (Label)e.Item.FindControl("itemAward");
GetDtlReferrals(Convert.ToInt32(lstReferrals.DataKeys[e.Item.ItemIndex]));
button.Visible = true;
if (lbl1.Text.ToLower() == "No")
button.Attributes.Add("onClick", "javascript:return confirm(\'Are You Sure You Wish To Award a SkyCard to this Agent ?\');");
else
{
button.ImageUrl = "~/images/dpbbuttons/revokebutton.gif";
button.Attributes.Add("onClick", "javascript:return confirm(\'Are You Sure You Wish To Revoke the SkyCard Award for this Agent ?\');");
}
break;
}
}
public ArrayList GetDtlReferrals(Int32 KeyField)
{
riReferrals = null;
try
{
// Obtain a list of discussion messages for the module
ReferralController objReferral = new ReferralController();
riReferrals = objReferral.GetReferralsByAgentID(KeyField);
}
catch (Exception ex)
{
Response.Write(ex);
CLogError clsLogError = new CLogError(ex, Request, Session, Context.User.Identity.Name);
clsLogError.LogError();
}
return riReferrals;
}
Got it!
In the GetDtlsReferrals method, I added the following code snippet which produced the display data I was looking for:
DataList DetailList = (DataList)e.Item.FindControl("DetailList");
DetailList.DataBind();
I have an ASP.NET GridView that uses an EmptyDataTemplate. This template is used to collect data in the event that no records exist in my data source. My GridView source looks like this:
<asp:GridView ID="myGridView" runat="server"
DataKeyNames="ID" OnRowEditing="myGridView_RowEditing"
OnRowCancelingEdit="myGridView_RowCancelingEdit"
OnRowUpdating="myGridView_RowUpdating"
ShowFooter="True" EnableModelValidation="True">
<Columns>
<asp:BoundField DataField="ID" Visible="false" />
<asp:TemplateField HeaderText="Name">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Name") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Name") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="nameFooterTextBox" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Age">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("Age") %>' />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("Age") %>' />
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="ageTextBox" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText="Options" HeaderStyle-HorizontalAlign="Left"
ButtonType="Link" ShowEditButton="true" ShowDeleteButton="true" >
</asp:CommandField>
</Columns>
<EmptyDataTemplate>
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td>Name</td>
<td>Age</td>
<td>Options</td>
</tr>
<tr>
<td><asp:TextBox ID="nameTextBox" runat="server" /></td>
<td><asp:TextBox ID="ageTextBox" runat="server" /></td>
<td><asp:LinkButton ID="saveLinkButton" runat="server" Text="save" OnClick="saveLinkButton_Click" /></td>
</tr>
</table>
</EmptyDataTemplate>
When a user clicks the "saveLinkButton" in the EmptyDataTemplate, I want to get the values from the TextBoxes and insert a new record into my data source. My question is, how do I get the values of those text fields when somebody clicks the "saveLinkButton"?
Thank you!
This thread over at asp.net proposes a solution to this problem (Note: I haven't tried it out)
http://forums.asp.net/p/1436652/3240106.aspx
You need to handle the RowCommand event, get the parent naming container of the control that raise the event (your linkbutton) and then search for the textboxes using FindControl within that.
Try this to get the values of the name and age in row command of the grid..
Before doing this set the command name of the saveLinkbutton to MyInsert and remove the onlcik event as u may not need it.
protected void yourGridview_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("MyInsert"))
{
TextBox nameTextBox= gvEligibility.Controls[0].Controls[0].FindControl("nameTextBox") as TextBox;
TextBox ageTextBox= gvEligibility.Controls[0].Controls[0].FindControl("ageTextBox") as TextBox;
string name=nameTextBox.Text();
string age=ageTextBox.Text();
//save code here
}
}