onclick event for telerik radgrid row - c#

I want to make an event occur when I click a row in my rad grid, I basically want to replace the 'editform' with an on click row event.
I've done a bit of searching online, but what works for others is having no impact for me.
The first piece of code is in ASP.NET, the second piece is in C#.
<div id="rgUser" runat="server" style="width: 300px; float: left; margin-left: 15px;">
<telerik:RadGrid ID="rgEffectivePermissions" runat="server" AutoGenerateColumns="false"
AllowSorting="True" Visible="true" AllowPaging="True"
OnPageIndexChanged="rgEffectivePermissions_PageIndexChanged"
OnItemDataBound="rgEffectivePermissions_ItemDataBound"
OnItemCommand="rgEffectivePermissions_ItemCommand">
<ClientSettings>
<Resizing AllowColumnResize="true"></Resizing>
</ClientSettings>
<MasterTableView AllowSorting="true" DataKeyNames="SystemUserID">
<CommandItemSettings ShowAddNewRecordButton="false" ShowRefreshButton="false" ShowExportToExcelButton="false" />
<SortExpressions>
<telerik:GridSortExpression FieldName="ClientCode" SortOrder="Ascending" />
</SortExpressions>
<Columns>
<telerik:GridTemplateColumn UniqueName="UserName" DataField="UserName" HeaderText="User Name" SortExpression="UserName">
<HeaderStyle HorizontalAlign="Center" />
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="100" />
<ItemTemplate>
<asp:Label ID="lblUsername" runat="server"><%# DataBinder.Eval(Container.DataItem, "UserName") %></asp:Label>
<asp:HoverMenuExtender ID="hmeSystemUserInfo" runat="server" TargetControlID="lblUsername" PopupControlID="pnlSystemUserInfo" PopupPosition="Bottom" />
<asp:Panel ID="pnlSystemUserInfo" runat="server" Style="visibility: hidden;">
<asp:Label runat="server" BackColor="Black" ForeColor="White" BorderColor="Black" Font-Bold="true" BorderStyle="Solid">
Last Updated By: <%# DataBinder.Eval(Container.DataItem, "LastUpdatedBy") %><br />
Last Update Date: <%# DataBinder.Eval(Container.DataItem, "LastUpdateDate") %><br />
Is Service Account: <%# DataBinder.Eval(Container.DataItem, "IsServiceAccount") %><br />
Is Account Manager: <%# DataBinder.Eval(Container.DataItem, "IsAccountManager") %>
</asp:Label>
</asp:Panel>
</ItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridBoundColumn UniqueName="SystemUserID" DataField="SystemUserID" HeaderText="SystemUserID" SortExpression="SystemUserID" ReadOnly="true" Visible="true" Display="false">
<HeaderStyle HorizontalAlign="Center" />
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</telerik:GridBoundColumn>
<telerik:GridTemplateColumn UniqueName="EmailAddress" DataField="EmailAddress" HeaderText="Email Address" SortExpression="EmailAddress">
<HeaderStyle HorizontalAlign="Center" />
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="100" />
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem, "EmailAddress") %>
</ItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridButtonColumn ButtonType="ImageButton" UniqueName="EditButton" HeaderText="Edit"
HeaderStyle-HorizontalAlign="Center" CommandName="EditForm" ImageUrl="~/Images/editPencil.png">
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</telerik:GridButtonColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
</div>
protected void rgEffectivePermissions_ItemCommand(object source, GridCommandEventArgs e)
{
switch (e.CommandName)
{
case ("EditForm"):
{
GridDataItem item = (GridDataItem)e.Item;
String SystemUserID = item["SystemUserID"].Text;
rgSecurityGroup.DataSource = AdminManager.GetClientGroupBySUSystemUserID(SystemUserID);
rgSecurityGroup.DataBind();
//int clientID = Convert.ToInt32(ddlClient1.SelectedValue);
//rgProductGroup.DataSource = AdminManager.GetActivityGroupsByClientGroupID(41);
//rgProductGroup.DataBind();
break;
}
}
}

One option would be to use the OnRowClick client event of RadGrid to run a script which will fire a command of your choice, and then process it in the code behind.
<telerik:RadGrid ID="rgEffectivePermissions" runat="server"
<ClientSettings>
<ClientEvents OnRowClick="onRowClik" />
</ClientSettings>
</telerik:RadGrid>
<telerik:RadCodeBlock ID="RadCodeBlock1" runat="server">
<script>
function onRowClik(sender, args) {
$find("<%= rgEffectivePermissions.ClientID %>").get_masterTableView().fireCommand("MyCommand", args.get_item().getDataKeyValue("SystemUserID"));
}
</script>
</telerik:RadCodeBlock>
In the code behind:
protected void rgEffectivePermissions_ItemCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
{
if(e.CommandName == "MyCommand")
{
rgSecurityGroup.DataSource = GetGridSource(int.Parse(e.CommandArgument.ToString()));
rgSecurityGroup.Rebind();
}
}
Another option would be to use the approach mentioned by aghilpro. Utilizing the OnSelectedIndexChanged server event of RadGrid.
<telerik:RadGrid ID="rgEffectivePermissions" runat="server"
OnSelectedIndexChanged="rgEffectivePermissions_SelectedIndexChanged">
<ClientSettings EnablePostBackOnRowClick="true">
<Selecting AllowRowSelect="true" />
</ClientSettings>
</telerik:RadGrid>
Code behind:
protected void rgEffectivePermissions_SelectedIndexChanged(object sender, EventArgs e)
{
if(((RadGrid)sender).SelectedItems.Count > 0)
{
rgSecurityGroup.DataSource = GetGridSource(int.Parse(((GridDataItem)((RadGrid)sender).SelectedItems[0])["SystemUserID"].Text));
rgSecurityGroup.Rebind();
}
}

Try this:
I use SelectionChanged event to get row changing and SelectedRows to access the selected rows.
radGridView1.SelectionChanged += new System.EventHandler(radGridView1_SelectionChanged);
private void radGridView1_SelectionChanged(object sender, EventArgs e)
{
try
{
if (this.radGridView1.SelectedRows.Count > 0)
{
int selectedIndex = radGridView1.SelectedRows[0].Index;
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}

Related

Avoid page refresh when clicking on LinkButton in GridView

I have a GridView control, and inside of this control I have defined a link button using GridView.ItemTemplate.
I am using this to open a new window on click. When I click on the link button, however, the page refreshes before opening the new window.
How can I stop the page from refreshing after the link button is clicked?
HTML
<asp:UpdatePanel ID="UpdatePanel4" runat="server">
<ContentTemplate>
<asp:GridView ID="DataGrid1" style="visibility:visible" runat="server" AlternatingRowStyle-BackColor="#E9EDF5" Font-Names="Arial"
ForeColor="#09538A" Font-Size="12px" BackColor="#ffffff" BorderColor="DarkGray" Font-Bold="true"
HeaderStyle-BackColor="#298DC7" EnableViewState="false" CellSpacing="20"
CellPadding="10" HeaderStyle-Font-Bold="true" AutoGenerateColumns="False" OnRowCommand="DataGrid1__RowCommand" OnRowDataBound="DataGrid1__RowDataBound" >
<HeaderStyle Font-Names="Arial;" CssClass="MyHeaderStyle" Font-Size="13px" ForeColor="White" Font-Bold="True" Height="20" BackColor="#298DC7" ></HeaderStyle>
<asp:templatefield headertext="NDC" ItemStyle-CssClass="col" ItemStyle-HorizontalAlign="Justify" HeaderStyle-Width="10%" ItemStyle-Width="10%"> <Columns>
<itemtemplate>
<asp:linkbutton id="productcode" ForeColor="#09538A" runat="server" text='<%#Eval("product code")%>'></asp:linkbutton>
</itemtemplate>
</asp:templatefield>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
<AjaxToolkit:ModalPopupExtender ID="ModalPopupExtender1" BackgroundCssClass="modalBackground" CancelControlID="cancel" TargetControlID="Button3" runat="server" PopupControlID="pnlpopup"> </AjaxToolkit:ModalPopupExtender>
<asp:Button ID="Button3" runat="server" style="visibility:hidden" Text="Button" />
<asp:Panel ID="pnlpopup" CssClass="PanelPopup" runat="server">
<div style="width:inherit;text-align:center;">Products of <%=ndc %> Product Family</div>
<asp:GridView ID="GridView1" runat="server" AlternatingRowStyle-BackColor="#f1f4f8" Width="980px" Font-Names="Arial"
Font-Bold="True" ForeColor="#09538A" Font-Size="13px" BackColor="#ffffff" BorderColor="DarkGray"
HeaderStyle-BackColor="#99cccc" EnableViewState="false" CellSpacing="0" style="padding:10px;"
CellPadding="3" ShowFooter="false" AllowPaging="True" AutoGenerateColumns="False" OnRowDataBound="productInfo_RowDataBound" >
<HeaderStyle Height="10%" CssClass="MyHeaderStyle" Font-Size="13px" ForeColor="#FFFFFF" Font-Bold="true" BackColor="#298DC7"></HeaderStyle>
<rowstyle Height="20px" />
<alternatingrowstyle Height="20px"/>
<Columns>
<asp:boundfield datafield="product code" sortexpression="customers " ItemStyle-CssClass="col" headertext="NDC"/>
<div id="div<%# Convert.ToString(Eval("customer"))+ Convert.ToString(Eval("ManufacturingPartner"))+ Convert.ToString(Eval("product code"))+ Convert.ToString(Eval("Sales Person")) %>" style="display: none; position: relative; left: 15px; overflow: auto">
<asp:GridView ID="gvOrderInfo" runat="server" ForeColor="#09538A" AutoGenerateColumns="false" BorderStyle="Double" BorderColor="#df5015" Width="500px" OnRowDataBound="gvOrderInfo_RowDatabound">
<HeaderStyle CssClass="MyHeaderStyle" Font-Size="13px" ForeColor="#FFFFFF" Font-Bold="True" BackColor="#298DC7"></HeaderStyle>
<RowStyle BackColor="#E1E1E1" />
<AlternatingRowStyle BackColor="White" />
<HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />
<Columns>
<asp:BoundField DataField="Order Number" HeaderText="Order Number" ItemStyle-Width="75px" ItemStyle-CssClass="col" HeaderStyle-HorizontalAlign="Left" />
</Columns>
</Columns>
</asp:GridView>
</div>
</asp:GridView>
</asp:Panel>
Codebehind
protected void DataGrid1__RowDataBound(Object sender, GridViewRowEventArgs e)
{
this.UpdatePanel4.Update();
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton lnk = e.Row.FindControl("ppp") as LinkButton;
lnk.Click += new EventHandler(link_Click);
//ScriptManager.GetCurrent(this).RegisterPostBackControl(lnk);
// string a = String.Format("0:N}",Convert.ToDecimal(e.Row.Cells[3].Text));
if (e.Row.Cells[0].Text != "Total")
{
//M1-Fmodification starts from here
if (ListBox2.Items.Count > 0)
//if (DataGrid1.Columns[0].Visible == true)
{
}
}
}
}
I would not use a LinkButton, but a straight html link.
<ContentTemplate>
<a href="#" ID='<%#Eval("product code")%>' onclick="doSomething();">
<%#Eval("productcode")%>
</a>
</ContentTemplate>
And then you can define some javascript in the page.
function doSomething(ProductCode) {
// enter the code here to open the window
}
Also, I would stay away from using UpdatePanel, but that's just my preference.

Onselect in Dropdown send mail to respective user

I have a gridview in which I have a column name "Selection". I want whenver a admin selects Not Selected option the respective user should get an email on his ID that he has been rejected. Please see the gridview code for your reference:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" AllowPaging="true" Width="920"
PageSize="5" OnPageIndexChanging="gv_Applicants_PageIndexChanging" OnRowCommand="gv_Applicants_RowCommand"
EmptyDataText="No Applicants Found."
AllowSorting="true"
OnSorting="gv_Applicants_Sorting"
OnRowDataBound="gv_Applicants_RowDataBound" RowStyle-CssClass="a12" AlternatingRowStyle-CssClass="a22" ForeColor="#333333" GridLines="None" CssClass="table_box" HeaderStyle-Height="35px">
<AlternatingRowStyle BackColor="#F0F0F0" />
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="First Name" HeaderStyle-Width="84" />
<asp:BoundField DataField="LastName" HeaderText="Last Name" HeaderStyle-Width="106" />
<asp:BoundField DataField="ContactNumber" HeaderText="Contact" HeaderStyle-Width="98" />
<asp:BoundField DataField="Email" HeaderText="Email" HeaderStyle-Width="150" />
<asp:TemplateField HeaderText="Position" SortExpression="Position" HeaderStyle-Width="107">
<ItemTemplate>
<%# Eval("Job.Position") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Location" SortExpression="Location" HeaderStyle-Width="100">
<ItemTemplate>
<%# Eval("Job.Location") %>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="AppliedDate" DataFormatString="{0:MMMM dd, yyyy}" HeaderText="Date of Application" ReadOnly="true" HeaderStyle-Width="121" />
<asp:TemplateField HeaderText="Action" HeaderStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:LinkButton ID='lnkView' CommandName='v' Text='View' runat='server' CommandArgument='<%# Eval("ApplicantId") %>'></asp:LinkButton>
|
<asp:LinkButton ID='lnkdel' CommandName='d' Text='Delete' runat='server' CommandArgument='<%# Eval("ApplicantId") %>' OnClientClick="return confirm('Are you sure to delete?');"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Selection">
<ItemTemplate>
<asp:Label ID="lblCountry" runat="server" Visible="true" />
<asp:DropDownList ID="ddlCountries" runat="server">
<asp:ListItem Text="None" Value="1"></asp:ListItem>
<asp:ListItem Text="Selected" Value="2"></asp:ListItem>
<asp:ListItem Text="Not Selected" Value="3"></asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#2461BF" />
<FooterStyle BackColor="#D8DADA" Font-Bold="True" />
<HeaderStyle BackColor="#D8DADA" Font-Bold="True" />
<PagerStyle BackColor="#D8DADA" HorizontalAlign="Center" />
<RowStyle BackColor="white" BorderStyle="Solid" BorderColor="#a8a8a8" BorderWidth="1px" Height="35" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
Eidted code:-
private void SendMail()
{
StringBuilder sbuilder = new StringBuilder();
sbuilder.Append("<div>");
sbuilder.Append("<p>Thanks for applying at RBL. You have been rejected</p>");
sbuilder.Append("</div>");
string str = sbuilder.ToString();
string ccEmail = "";
Common objCom = new Common();
string toId = ConfigurationManager.AppSettings["ddlEmail"].ToString();
objCom.SendEMail(toId, "Rejection Mail", sbuilder.ToString(), ccEmail, false, "");
}
protected void ddlSelection_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList)sender;
GridViewRow row = (GridViewRow)ddl.Parent.Parent;
if (ddl.SelectedValue == "Not Selected")
{
SendMail();
}
}
Try this,
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddl = e.Row.FindControl("ddlCountries") as DropDownList;
if(ddl != null)
{
ddl.SelectedIndexChanged += new EventHandler(ddlCountries_SelectedIndexChanged);
}
}
}
protected void ddlCountries_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedValue = ((DropDownList)sender).SelectedValue;
if(selectedValue== "Not Selected")
{
// Write code here for sending mail
}
}

why on clicking on edit button of childgridview the childgridview hides?

This is what I have done for nested gridview :
The jQuery I have used to maintain this show hide is as:
<script type="text/javascript">
// Method for managing opening of gridview on + image and - image
$("[src*=plus]").live("click", function() {
$(this).closest("tr").after("<tr><td></td><td colspan = '999'>" + $(this).next().html() + "</td></tr>")
$(this).attr("src", "../Image/minus.gif");
});
$("[src*=minus]").live("click", function() {
$(this).attr("src", "../Image/plus.gif");
$(this).closest("tr").next().remove();
});
</script>
<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" DataKeyNames="num"
AutoGenerateColumns="False" Style="font-size: x-small" OnSelectedIndexChanging="GridView1_SelectedIndexChanging"
OnRowCancelingEdit="GridView1_RowCancelling" OnRowUpdating="GridView1_RowUpdating" OnRowCommand="GridView1_RowCommand"
OnRowDeleting="GridView1_RowDeleting" ShowFooter="True"
OnRowEditing="GridView1_RowEditing" OnRowDataBound="GridView1_RowDataBound" OnSorting="GridView1_Sorting"
AllowSorting="true">
<RowStyle BackColor="#E3EAEB" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<img alt="" style="cursor: pointer" src="../Image/plus.gif" />
<asp:Panel ID="pnlOrders" style="display:none;">
<asp:GridView ID="GridView3" runat="server" CellPadding="4" ForeColor="#333333" DataKeyNames="sno"
OnRowCancelingEdit="GridView3_RowCancelling" OnRowUpdating="GridView3_RowUpdating"
OnRowEditing="GridView3_RowEditing" AutoGenerateColumns="False" Style="font-size: x-small">
<RowStyle BackColor="#E3EAEB" />
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:TemplateField>
<HeaderTemplate>
Detailed Head
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="empdetails" Width="200px" runat="server" Text='<%# Eval("Details") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtempdetail" Width="200px" runat="server" MaxLength="9" Text='<%# Eval("Details") %>'>
</asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="sal" HeaderText="salary" />
<asp:CommandField ShowEditButton="true" EditText="Edit" />
</Columns>
<FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#7C6F57" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="View" runat="server" Text="View" CommandName="view"
CommandArgument='<%#Container.DataItemIndex+1 %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
Age</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblage" Width="80px" runat="server" MaxLength="4" Text='<%# Eval("age") %>'>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtage" runat="server" Text='<%# Eval("age") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
BloodGroup</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblBloodGroup" Width="100px" runat="server" MaxLength="9" Text='<%# Eval(" BloodGroup") %>'>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtBloodGroup" runat="server" Text='<%# Eval(" BloodGroup") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowSelectButton="True" SelectText="Select" />
<asp:CommandField DeleteText="Reject" ShowDeleteButton="True" />
<asp:CommandField ShowEditButton="true" EditText="Edit" />
</Columns>
<FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#7C6F57" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
On server side this is what I am doing:
protected void GridView3_RowEditing(object sender, GridViewEditEventArgs e)
{
DataSet ds = new DataSet();
tBL objBL = new tBL();
GridViewRow editedRow = GridView1.Rows[e.NewEditIndex];
//now search row for your control...
GridView GridView3 = (GridView)editedRow.FindControl("GridView3");
GridView3.EditIndex = e.NewEditIndex;
objtxtToTableBL.ViewBL(dt);
GridView3.DataSource = dt;
GridView3.DataBind();
}
protected void GridView3_RowCancelling(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
}
protected void GridView3_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
}
I am binding the nested gridview on rowdatabound of GridView1 and that works fine.
The problem with all this is when I click on the edit button of innergridview(child) it get hide as the page postback .
What should I do so that when I click on its edit button the child gridview remains open and it gets hides only when I click on minus button. Please help it has already taken 3 days of mine.

Link button inside nested gridview invoking the wrong row

I have a expand collapse nested grid view like below.
The childgrid (gvChild) column is a linkbutton column on the click of which I need to get the name of the city which was clicked. My rowcommand event to capture that on the child gridview is like this:
protected void gvChild_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "ShowDetails")
{
int index = Convert.ToInt32(e.CommandArgument);
GridView gridChild = (GridView)gvwParent.Rows[index].FindControl("gvChild");
foreach (GridViewRow row in gridChild .Rows)
{
string aCity= ((LinkButton)row.Cells[1].FindControl("lnkSelectedCity")).Text;
}
}
}
I understand the findcontrol line is def wrong, but how else would I do the findcontrol of the child grid to get the right link button that was clicked? Right now if I select "London", the Index value is 1 and the String "aCity" is taking it as "Utah". Will appreciate inputs on this. Thank you.
Code on my aspx page:
<asp:GridView ID="gvParent" runat="server"
AllowPaging="True" AutoGenerateColumns="False"
DataKeyNames="CountryID"
OnRowDataBound="gvParent_RowDataBound" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<a href="javaScript:divexpandcollapse('div<%# Eval("CountryID") %>');">
<img id='imgdiv<%# Eval("CountryID") %>' width="9px" border="0" src="expand_white.gif"
alt="" /></a>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="CountryDesc">
<ItemTemplate>
<asp:Label ID="lblEmpID" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "CountryDesc") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<tr>
<td colspan="100%">
<div id='div<%# Eval("CountryID") %>' style="display: none; position: relative; left: 15px; overflow: auto">
<asp:GridView ID="gvChild" runat="server" AutoGenerateColumns="False" PageSize="5"
Width="100%" Height="270px" ShowHeader="False" OnRowDataBound="gvChild_RowDataBound">
<Columns>
<asp:BoundField DataField="CityID" HeaderText="CityID">
<HeaderStyle CssClass="Invisible" />
<ItemStyle CssClass="Invisible" HorizontalAlign="Left" />
</asp:BoundField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkSelectedCity" runat="server" Text='<% # Eval("CityName") %>'
CommandName="ShowDetails" CommandArgument='<%# Container.DataItemIndex %>' ToolTip="Select x"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Assigned" HeaderText="Assigned">
<HeaderStyle CssClass="Invisible" />
<ItemStyle CssClass="Invisible" HorizontalAlign="Left" />
</asp:BoundField>
<asp:BoundField DataField="CountryID" HeaderText="Assigned">
<HeaderStyle CssClass="Invisible" />
<ItemStyle CssClass="Invisible" HorizontalAlign="Left" />
</asp:BoundField>
<asp:BoundField DataField="ClassID" HeaderText="ClassID">
<HeaderStyle CssClass="Invisible" />
<ItemStyle CssClass="Invisible" HorizontalAlign="Left" />
</asp:BoundField>
<asp:BoundField DataField="UOM" HeaderText="UOM">
<HeaderStyle CssClass="Invisible" />
<ItemStyle CssClass="Invisible" HorizontalAlign="Left" />
</asp:BoundField>
</Columns>
</asp:GridView>
</div>
</td></tr>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I assume CityID is a unique key. If so, you can assign CityID to CommandArgument.
Then you can retrieve the CityID back from CommandArgument after post back.
<asp:GridView ID="gvChild" ... DataKeyNames="CityID">
<Columns>
...
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkSelectedCity"
...
CommandArgument='<%# Eval("CityID") %>'
ToolTip="Select x" />
</ItemTemplate>
</asp:TemplateField>
protected void gvChild_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "ShowDetails")
{
int cityId = Convert.ToInt32(e.CommandArgument);
}
}

Can't get gridview row once templatefield button is clicked

When a Button in the GridView is clicked I can't seem to get the row index or the row that is to be eliminated, I need the Id and the Complete route of the archive, both of them are on the bound fields of the GridView, here is the code I have:
Gridview Code:
<asp:GridView ID="gdvData"
AllowSorting="False"
AllowPaging="True"
AutoGenerateColumns="False"
AutoGenerateDeleteButton="False"
runat="server"
EmptyDataText="No existen archivos cargados."
Width="100%">
<AlternatingRowStyle CssClass="alternatingrowstyle" />
<Columns>
<asp:BoundField HeaderText="Id"
DataField="Id"
Visible="false" >
<HeaderStyle CssClass="left" />
<ItemStyle CssClass="left" />
</asp:BoundField>
<asp:BoundField HeaderText="RutaCompleta"
DataField="RutaCompleta"
Visible="false" >
<HeaderStyle CssClass="left" />
<ItemStyle CssClass="left" />
</asp:BoundField>
<asp:TemplateField HeaderText="Archivo">
<ItemTemplate>
<asp:HyperLink runat="server"
CssClass="left"
Target="_blank"
NavigateUrl='<%#Eval("RutaCompleta")%>'
Text='<%#Eval("Archivo")%>'>
</asp:HyperLink>
</ItemTemplate>
<HeaderStyle CssClass="left" />
<ItemStyle HorizontalAlign="left" />
</asp:TemplateField>
<asp:TemplateField HeaderImageUrl="~/Images/page_delete.ico"
HeaderText="Eliminar">
<ItemTemplate>
<asp:ImageButton ID="ImgDelete"
runat="server"
CommandArgument="Delete"
ImageUrl="~/Images/page_delete.ico"
OnClick="btnEliminar_Click"
OnClientClick="return confirm('¿Esta seguro de eliminar este archivo?');"
ToolTip="Borrar Documento"/>
</ItemTemplate>
<HeaderStyle CssClass="center" />
<ItemStyle CssClass="center"/>
</asp:TemplateField>
</Columns>
<HeaderStyle CssClass="headerstyle" />
<PagerStyle CssClass="pagerstyle" />
<PagerTemplate>
<asp:Label ID="Label1" runat="server" Text="Mostrar filas:" />
<asp:DropDownList ID="ddlPageSize"
runat="server"
AutoPostBack="true"
CssClass="CombosBox"
>
<asp:ListItem Value="10" />
<asp:ListItem Value="15" />
<asp:ListItem Value="20" />
</asp:DropDownList>
<asp:Label ID="lblDesde" runat="server" Text="Página" />
<asp:TextBox ID="txtGoToPage"
runat="server"
AutoPostBack="true"
CssClass="gotopage"
/>
<asp:Label ID="lblHasta" runat="server" Text="de " />
<asp:Label ID="lblTotalNumberOfPages" runat="server" />
<asp:Button ID="btnAnt"
runat="server"
CommandArgument="Prev"
CommandName="Page"
CssClass="previous"
ToolTip="ant. página" />
<asp:Button ID="btnProx"
runat="server"
CommandArgument="Next"
CommandName="Page"
CssClass="next"
ToolTip="prox. página" />
</PagerTemplate>
</asp:GridView>
Code Behind:
protected void btnEliminar_Click(object sender, EventArgs e)
{
try
{
Int64 intId = 0;
String strRutaCompleta = String.Empty;
GridViewRow row = (GridViewRow)(sender as Control).Parent.Parent;
Label lblId = (Label)row.FindControl("lblId");
Label lblRutaCompleta = (Label)row.FindControl("lblRutaCompleta");
intId = Convert.ToInt64(lblId.Text.ToString());
strRutaCompleta = lblRutaCompleta.Text.ToString();
/*Other part of the code*/
}
catch(Exception)
{
/*Other part of the code*/
}
}
I have tried various methods found here on StackOverflow, hope you guys can help me. Thanks.
Instead of using .Parent.Parent, I recommend using the CommandArgument property of the ImageButton and set the dataitem's Id.
Here is another post on StackOverflow that give a good bit of code: ASP.NET GridView RowIndex As CommandArgument
It appears to me that all you need is the Id of the data you want to delete. So instead of trying to use the row's index, just put the Id in the button's CommandArgument
Example:
<asp:ImageButton ID="ImgDelete"
runat="server"
CommandArgument="Delete"
ImageUrl="~/Images/page_delete.ico"
OnClick="btnEliminar_Click"
CommandArgument='<%#Eval("Id")%>'
OnClientClick="return confirm('¿Esta seguro de eliminar este archivo?');"
ToolTip="Borrar Documento"/>
Code Behind:
protected void btnEliminar_Click(object sender, EventArgs e)
{
try
{
Int64 intId = 0;
ImageButton btn = (sender as ImageButton)
if(btn != null)
{
Int64 tempId;
if(Int64.TryParse(btn.CommandArgument, out tempId))
{
intId = intId;
/*Other part of the code*/
}
}
}
catch(Exception)
{
/*Other part of the code*/
}
}

Categories

Resources