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*/
}
}
Related
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);
}
}
I have a grid view within a grid view. When I click on edit of parent grid view the child grid view displays a checkbox. When I click on next page button of child grid view the controls that were made visible become invisible again. This is not the behaviour I require. I would like the controls that are made visible by clicking edit to remain visible through paging of the child grid view while parent grid view is in edit mode.
My markup:
<asp:GridView
ID="grdImages"
runat="server"
AllowPaging="true"
ShowFooter="true"
PageSize="5"
AutoGenerateColumns="false"
OnPageIndexChanging="grdImages_PageIndexChanging"
OnRowCancelingEdit="grdImages_RowCancelingEdit"
OnRowCommand="grdImages_RowCommand"
OnRowEditing="grdImages_RowEditing"
OnRowUpdating="grdImages_RowUpdating"
OnRowDeleting="grdImages_RowDeleting"
EmptyDataText="No Data Available at this Time"
OnRowDataBound="grdImages_RowDataBound"
DataKeyNames="productID" RowStyle-VerticalAlign="Top" RowStyle-HorizontalAlign="Center">
<AlternatingRowStyle BackColor="White" ForeColor="#284775"></AlternatingRowStyle>
<Columns>
<asp:TemplateField AccessibleHeaderText="Product ID" HeaderText="Product ID" FooterText="Product ID">
<ItemTemplate>
<asp:Label ID="lblProdId" runat="server" Text='<%# Eval("ProductId") %>' ></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="lstAddProdId" runat="server" AppendDataBoundItems="true" >
<asp:ListItem>Select a product</asp:ListItem>
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField AccessibleHeaderText="Product Main Image" FooterText="Product Main Image" HeaderText="Product Main Image">
<ItemTemplate>
<asp:Label ID="lblMainImgId" runat="server" Text='<%# Eval("ImageId") %>' ></asp:Label>
<asp:Label ID="lblMainImgName" runat="server" Text='<%# Eval("ImageName") %>' ></asp:Label> <br />
<asp:Image ID="imgMain" runat="server" Height="250" Width="250" ImageUrl='<%# Eval("ImagePath") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:Label runat="server" Font-Bold="true" Text="Current main image" ></asp:Label> <br />
<asp:Image ID="imgMain" runat="server" Height="250" Width="250" ImageUrl='<%# Eval("ImagePath") %>' /> <br />
<asp:Label runat="server" Font-Bold="true" Text="Upload a new image to replace the current main image." ></asp:Label> <br />
<asp:FileUpload ID="flupEditMain" runat="server" />
</EditItemTemplate>
<FooterTemplate>
<asp:FileUpload ID="flupMain" runat="server" AllowMultiple="false" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField AccessibleHeaderText="Supporting Images" FooterText="Supporting Images" HeaderText="Supporting Images">
<ItemTemplate>
<asp:Label ID="lblSupImages" runat="server" Visible="false" Font-Bold="true" Text="Select images to delete"></asp:Label><br />
<asp:GridView
ID="grdSupImages"
runat="server"
ShowHeader="false"
CellPadding="4"
ForeColor="#333333"
GridLines="None"
AutoGenerateColumns="False"
AllowPaging="true"
PageSize="4"
OnPageIndexChanging="grdSupImages_PageIndexChanging"
OnRowEditing="grdSupImages_RowEditing"
EnableViewState="true"
DataKeyNames="productID"
RowStyle-VerticalAlign="Top"
RowStyle-HorizontalAlign="Center"
EmptyDataText="No Supporting Images Found">
<AlternatingRowStyle BackColor="White" ForeColor="#284775"></AlternatingRowStyle>
<Columns>
<asp:TemplateField >
<ItemTemplate>
<asp:Image ID="imgSup" runat="server" ToolTip='<%# Eval("ImgId") %>' AlternateText='<%# Eval("ImageName") %>' ImageUrl='<%# Eval("ImagePath") %>' Height="125" Width="125" />
<asp:Label ID="imgSupName" runat="server" Text='<%# Eval("ImageName") %>' AssociatedControlID="imgSup"></asp:Label>
<asp:CheckBox ID="chkSupImages" runat="server" Visible="false" Text="Select Image" CommandName="Select" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#999999"></EditRowStyle>
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White"></FooterStyle>
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White"></HeaderStyle>
<PagerStyle HorizontalAlign="Center" BackColor="#284775" ForeColor="White"></PagerStyle>
<RowStyle BackColor="#F7F6F3" ForeColor="#333333"></RowStyle>
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333"></SelectedRowStyle>
<SortedAscendingCellStyle BackColor="#E9E7E2"></SortedAscendingCellStyle>
<SortedAscendingHeaderStyle BackColor="#506C8C"></SortedAscendingHeaderStyle>
<SortedDescendingCellStyle BackColor="#FFFDF8"></SortedDescendingCellStyle>
<SortedDescendingHeaderStyle BackColor="#6F8DAE"></SortedDescendingHeaderStyle>
</asp:GridView>
<div style="clear:both;"> </div>
<asp:Label ID="lblFlupSupImages" runat="server" Font-Bold="true" Text="Add extra images" Visible="false" />
<br />
<asp:FileUpload ID="flupSupImages" runat="server" AllowMultiple="true" Visible="false" />
</ItemTemplate>
<FooterTemplate>
<asp:FileUpload ID="flupExtra" runat="server" AllowMultiple="true" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:LinkButton ID="btnEdit" Text="Edit" runat="server" CommandName="Edit" />
<br />
<span onclick="return confirm('Are you sure you want to delete these images?')">
<asp:LinkButton ID="btnDelete" Text="Delete" runat="server" CommandName="Delete" />
</span>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="btnUpdate" Text="Update" runat="server" CommandName="Update" />
<br />
<asp:LinkButton ID="btnCancel" Text="Cancel" runat="server" CommandName="Cancel" />
</EditItemTemplate>
<FooterTemplate>
<asp:Button ID="btnAddRecord" runat="server" Text="Add" CommandName="Add"></asp:Button>
</FooterTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#999999"></EditRowStyle>
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White"></FooterStyle>
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White"></HeaderStyle>
<PagerStyle HorizontalAlign="Center" BackColor="#284775" ForeColor="White"></PagerStyle>
<RowStyle BackColor="#F7F6F3" ForeColor="#333333"></RowStyle>
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333"></SelectedRowStyle>
<SortedAscendingCellStyle BackColor="#E9E7E2"></SortedAscendingCellStyle>
<SortedAscendingHeaderStyle BackColor="#506C8C"></SortedAscendingHeaderStyle>
<SortedDescendingCellStyle BackColor="#FFFDF8"></SortedDescendingCellStyle>
<SortedDescendingHeaderStyle BackColor="#6F8DAE"></SortedDescendingHeaderStyle>
</asp:GridView>
My code behind:
protected void grdImages_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
GridView grd = (GridView)e.Row.FindControl("grdSupImages"); // find controls
Label prodId = (Label)e.Row.FindControl("lblProdId");
grd.ToolTip = prodId.Text;
int product = Convert.ToInt32(prodId.Text); // assign values to variables.
BindNestedGrid(product, grd); // call the function.
}
if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowIndex == grdImages.EditIndex)
{
//Find Child GridView
GridView supImagesGrd = (GridView)e.Row.Cells[2].FindControl("grdSupImages");
if (supImagesGrd != null)
{
// find grid header label and make visible
Label gridHead = (Label)e.Row.Cells[2].FindControl("lblSupImages");
gridHead.Visible = true;
// find fileupload header label and make visible.
Label fileUpHead = (Label)e.Row.Cells[2].FindControl("lblFlupSupImages");
fileUpHead.Visible = true;
// find fileupload control and make it visible.
FileUpload flup = (FileUpload)e.Row.Cells[2].FindControl("flupSupImages");
flup.Visible = true;
//Loop through the GridView
foreach (GridViewRow row in supImagesGrd.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
//Find the CheckBox
CheckBox chb = (CheckBox)row.Cells[0].FindControl("chkSupImages");
if (chb != null)
{
chb.Visible = true;
}
}
}
}
}
}
protected void grdSupImages_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView gv = (GridView)sender;
gv.PageIndex = e.NewPageIndex;
BindNestedGrid(Convert.ToInt32(gv.ToolTip), gv);
}
If any more information or code is required please let me know.
For anyone who wants to know, I disabled paging of the child grid when edit button is clicked so all check boxes show on all rows of child grid now.
I am not getting the point why this is happening.
I have a Gridview, inside that I have implemented a pagerTemplate. It is showing me the correct records which are coming from the database.
First of All, I took the logic of implementing the gridview pager part from here. And I implemented the same as described their.
Now the scenario which I came up with is that, When I change the dropdown selection, my gridview gets postback and all the Row of the grid gets disturbed. I dont know why this is happening.
See the code which I implemented:-
<asp:GridView ID="grdCSRPageData" runat="server" Width="100%" border="1" Style="border: 1px solid #E5E5E5;" CellPadding="3"
AutoGenerateColumns="False" OnDataBound="grdCSRPageData_DataBound" AllowPaging="true" CssClass="hoverTable" EmptyDataText="No Records Found"
OnPageIndexChanging="grdCSRPageData_PageIndexChanging" DataKeyNames="Id" OnRowDeleting="grdCSRPageData_RowDeleting"
PageSize="4" ShowFooter="true" OnRowEditing="grdCSRPageData_RowEditing" OnRowUpdating="grdCSRPageData_RowUpdating"
OnRowCancelingEdit="grdCSRPageData_RowCancelingEdit">
<AlternatingRowStyle CssClass="k-alt" BackColor="#f5f5f5" />
<Columns>
<asp:TemplateField HeaderText="Select" HeaderStyle-Width="5%" HeaderStyle-CssClass="k-grid td">
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" AutoPostBack="false" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="page_title" HeaderText="Page Title" ItemStyle-Width="30" HeaderStyle-CssClass="k-grid td" />
<asp:BoundField DataField="page_description" HeaderText="Page Description" ItemStyle-Width="30" HeaderStyle-CssClass="k-grid td" />
<asp:BoundField DataField="meta_title" HeaderText="Meta Title" ItemStyle-Width="30" HeaderStyle-CssClass="k-grid td" />
<asp:BoundField DataField="meta_keywords" HeaderText="Meta Keywords" ItemStyle-Width="30" HeaderStyle-CssClass="k-grid td" />
<asp:BoundField DataField="meta_description" HeaderText="Meta Description" ItemStyle-Width="30" HeaderStyle-CssClass="k-grid td" />
<asp:BoundField DataField="Active" HeaderText="Active" ItemStyle-Width="30" HeaderStyle-CssClass="k-grid td" />
<asp:TemplateField HeaderText="Action" HeaderStyle-Width="15%" HeaderStyle-CssClass="k-grid td">
<ItemTemplate>
<asp:ImageButton ID="btnDelete" AlternateText="Delete" ImageUrl="~/images/delete.png" runat="server" Width="15" Height="15" CommandName="Delete" CommandArgument='<%# Eval("Id") %>' CausesValidation="false" OnClientClick="return confirm('Are you sure you want to delete this record?')" />
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ButtonType="Image" ItemStyle-Width="15" EditImageUrl="~/images/edit.png" ShowEditButton="True" ControlStyle-Width="15" ControlStyle-Height="15" CancelImageUrl="~/images/close.png" UpdateImageUrl="~/images/update.png">
<ControlStyle Height="20px" Width="20px"></ControlStyle>
</asp:CommandField>
</Columns>
<pagerstyle />
<pagerTemplate>
<table style="width:100%">
<tr>
<td>
<asp:label id="MessageLabel" Text="Select a page:" runat="server"/>
<asp:dropdownlist id="PageDropDownList" AutoPostBack="true" OnSelectedIndexChanged="PageDropDownList_SelectedIndexChanged"
runat="server"/>
<td style="width:70%; text-align:right">
<asp:label id="CurrentPageLabel" runat="server"/>
</td>
</td>
</tr>
</table>
</pagerTemplate>
</asp:GridView>
The code is added with PagerTemplate. Also see my code behind as given their:-
Cs Code for the PagerTemplate:-
protected void grdCSRPageData_DataBound(object sender, EventArgs e)
{
GridViewRow pagerRow = grdCSRPageData.BottomPagerRow;
DropDownList pageList = (DropDownList)pagerRow.Cells[0].FindControl("PageDropDownList");
Label pageLabel = (Label)pagerRow.Cells[0].FindControl("CurrentPageLabel");
if (pageList != null)
{
for (int i = 0; i < grdCSRPageData.PageCount; i++)
{
int pageNumber = i + 1;
ListItem item = new ListItem(pageNumber.ToString());
if (i == grdCSRPageData.PageIndex)
{
item.Selected = true;
}
pageList.Items.Add(item);
}
}
if (pageLabel != null)
{
int currentPage = grdCSRPageData.PageIndex + 1;
pageLabel.Text = "Page " + currentPage.ToString() +
" of " + grdCSRPageData.PageCount.ToString();
}
}
protected void PageDropDownList_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow pagerRow = grdCSRPageData.BottomPagerRow;
DropDownList pagelist = (DropDownList)pagerRow.Cells[0].FindControl("PageDropDownList");
grdCSRPageData.PageIndex = pagelist.SelectedIndex;
}
Please help. Any help would be appreciable
try changing the AutoPostBack="true" to false of your dropDownList and be sure to load data in Page_Load inside
if (!IsPostBack){
//bind gridview
}
update
try inserting your dropDownList (with AutoPostBack="true") and your GridView inside an UpdatePanel with "UpdateMode=Conditional" like this
<asp:UpdatePanel runat="server" ID="up1" UpdateMode="Conditional">
<ContentTemplate>
//put here gridview
<ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="PageDropDownList" EventName="SelectedIndexChanged" />
</Triggers>
</asp:UpdatePanel>
update
try this solution with your code
aspx page
<asp:GridView ID="grdUser"
AllowPaging="true"
AutoGenerateColumns="False"
OnDataBound="grdUser_DataBound"
OnRowDeleting="grdUser_RowDeleting"
OnPreRender="PreRenderGrid"
runat="server"
Width="100%"
border="1"
DataKeyNames="Id"
PageSize="2"
OnPageIndexChanging="grdUser_PageIndexChanging"
EnableSortingAndPagingCallbacks="false"
CssClass="pagi" OnRowCommand="grdUser_RowCommand">
<Columns>
<asp:TemplateField HeaderText="Select" ItemStyle-Width="30" HeaderStyle-CssClass="k-grid td">
<ItemTemplate>
<asp:CheckBox ID="chkDelete" runat="server" />
</ItemTemplate>
<HeaderStyle CssClass="k-grid td"></HeaderStyle>
<ItemStyle Width="30px"></ItemStyle>
</asp:TemplateField>
<asp:BoundField DataField="username" HeaderText="UserName" ItemStyle-Width="30" HeaderStyle-CssClass="k-grid td">
<HeaderStyle CssClass="k-grid td"></HeaderStyle>
<ItemStyle Width="30px"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="email" HeaderText="Email Id" ItemStyle-Width="30" HeaderStyle-CssClass="k-grid td">
<HeaderStyle CssClass="k-grid td"></HeaderStyle>
<ItemStyle Width="30px"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="usertype" HeaderText="UserType" ItemStyle-Width="30" HeaderStyle-CssClass="k-grid td">
<HeaderStyle CssClass="k-grid td"></HeaderStyle>
<ItemStyle Width="30px"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="active" HeaderText="Active" ItemStyle-Width="30" HeaderStyle-CssClass="k-grid td">
<HeaderStyle CssClass="k-grid td"></HeaderStyle>
<ItemStyle Width="30px"></ItemStyle>
</asp:BoundField>
<asp:TemplateField HeaderText="Action" HeaderStyle-Width="5%" ItemStyle-Width="20" HeaderStyle-CssClass="k-grid td">
<ItemTemplate>
<asp:ImageButton ID="btnDelete" AlternateText="Delete" ImageUrl="~/images/delete.png" runat="server" Width="15" Height="15" CommandName="eEdit" CommandArgument='<%# Eval("Id") %>' CausesValidation="false" OnClientClick="return confirm('Are you sure you want to delete this record?')" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="btnEdit" AlternateText="Edit" ImageUrl="~/images/edit.png" runat="server" Width="15" Height="15" CommandName="eEdit" CommandArgument='<%# Eval("Id") %>' CausesValidation="false" />
</ItemTemplate>
<HeaderStyle CssClass="k-grid td" Width="15%"></HeaderStyle>
<ItemStyle Width="30px"></ItemStyle>
</asp:TemplateField>
</Columns>
<PagerStyle ForeColor="#e3e3e3"
BackColor="#e3e3e3" CssClass="grid-pagi" />
<PagerTemplate>
<table runat="server" id="testTable1" style="width: 100%" class="k-grid td">
<tr>
<td class="col-md-7 pull-left">
<asp:Label ID="MessageLabel"
Text="Select a page:"
runat="server" />
<asp:LinkButton ID="FirstLB" runat="server" CommandName="Page" CommandArgument="First" ToolTip="First" CssClass="btn-pager btn-default"><<</asp:LinkButton>
<asp:LinkButton ID="PrevLB" runat="server" CommandName="Page" CommandArgument="Prev" ToolTip="Previous" CssClass="btn-pager btn-default"><</asp:LinkButton>
<asp:DropDownList runat="server" ID="PageDropDownList" AutoPostBack="true" EnableViewState="true" OnSelectedIndexChanged="PageDropDownList_SelectedIndexChanged" CssClass="selectpicker form-control-drp"></asp:DropDownList>
<asp:LinkButton ID="NextLB" runat="server" CommandName="Page" CommandArgument="Next" ToolTip="Next" CssClass="btn-pager btn-default">></asp:LinkButton>
<asp:LinkButton ID="LastLB" runat="server" CommandName="Page" CommandArgument="Last" ToolTip="Last" CssClass="btn-pager btn-default">>></asp:LinkButton>
</td>
<td class="col-md-3 pull-right">
<asp:Label ID="PageSizeLabel" runat="server" Text="Select Page Size: "></asp:Label>
<asp:DropDownList ID="ddlPageSize" runat="server" OnSelectedIndexChanged="ddlPageSize_SelectedIndexChanged" AutoPostBack="true" CssClass="selectpicker form-control-drp">
<%-- <asp:ListItem Value="0" Text="0" />--%>
<asp:ListItem Value="1" Text="1" />
<asp:ListItem Value="2" Text="2" />
<asp:ListItem Value="3" Text="3" />
</asp:DropDownList>
</td>
<td class="col-md-2">
<asp:Label ID="CurrentPageLabel" runat="server" />
</td>
</tr>
</table>
</PagerTemplate>
</asp:GridView>
code behind
protected void grdUser_DataBound(object sender, EventArgs e)
{
GridViewRow pagerRow = grdUser.BottomPagerRow;
DropDownList pageSizeList = (DropDownList)pagerRow.Cells[0].FindControl("ddlPageSize");
if (Context.Session["PageSize"] != null)
{
pageSizeList.SelectedValue = Context.Session["PageSize"].ToString();
}
DropDownList pageList = (DropDownList)pagerRow.Cells[0].FindControl("PageDropDownList");
Label pageLabel = (Label)pagerRow.Cells[0].FindControl("CurrentPageLabel");
if (pageList != null)
{
for (int i = 0; i < grdUser.PageCount; i++)
{
int pageNumber = i + 1;
ListItem item = new ListItem(pageNumber.ToString());
if (i == grdUser.PageIndex)
{
item.Selected = true;
}
pageList.Items.Add(item);
}
}
if (pageLabel != null)
{
int currentPage = grdUser.PageIndex + 1;
pageLabel.Text = "View " + currentPage.ToString() + " of " + grdUser.PageCount.ToString();
}
}
protected void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow pagerRow = grdUser.BottomPagerRow;
DropDownList pageSizeList = (DropDownList)pagerRow.Cells[0].FindControl("ddlPageSize");
//
grdUser.PageSize = Convert.ToInt32(pageSizeList.SelectedValue);
Context.Session["PageSize"] = pageSizeList.SelectedValue;
BindGrid();
}
protected void PageDropDownList_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow pagerRow = grdUser.BottomPagerRow;
DropDownList pageList = (DropDownList)pagerRow.Cells[0].FindControl("PageDropDownList");
grdUser.PageIndex = pageList.SelectedIndex;
BindGrid();
}
protected void PreRenderGrid(object sender, EventArgs e)
{
GridViewRow pagerRow = grdUser.BottomPagerRow;
DropDownList pageList = (DropDownList)pagerRow.Cells[0].FindControl("PageDropDownList");//error
Label pageLabel = (Label)pagerRow.Cells[0].FindControl("CurrentPageLabel");
if (pageList != null)
{
for (int i = 0; i < grdUser.PageCount; i++)
{
int pageNumber = i + 1;
ListItem item = new ListItem(pageNumber.ToString());
if (i == grdUser.PageIndex)
{
item.Selected = true;
}
pageList.Items.Add(item);
}
}
if (pageLabel != null)
{
int currentPage = grdUser.PageIndex + 1;
pageLabel.Text = "View " + currentPage.ToString() + " of " + grdUser.PageCount.ToString();
}
this.grdUser.Controls[0].Controls[this.grdUser.Controls[0].Controls.Count - 1].Visible = true;
BindGrid();
}
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
}
}
I've a grid view with three columns Employee name Employee details and Employee age.
I want to add a check box at each row and after selection of each check box i want to fire a insert query associated to that employee.
Can you tell me how to add this dynamic functionality to the grid view.
also if we use <%# EVAL %> i don't know how to implement it with checkbox.
ASPX:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="SqlDataSource1">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="name" HeaderText="name" SortExpression="name" />
<asp:BoundField DataField="details" HeaderText="details"
SortExpression="details" />
<asp:BoundField DataField="age" HeaderText="age" SortExpression="age" />
</Columns>
</asp:GridView>
<br />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="OK" />
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:connApps %>"
SelectCommand="SELECT [name], [details], [age] FROM [tblA]">
</asp:SqlDataSource>
<br />
<asp:Label ID="Label1" runat="server"></asp:Label>
Code behind:
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "Selected item name:<br>";
foreach (GridViewRow item in GridView1.Rows)
{
CheckBox chk = (CheckBox)item.FindControl("CheckBox1");
if (chk != null)
{
if (chk.Checked)
{
Label1.Text += item.Cells[1].Text + "<br>";
}
}
}
}
Output:
Here is an example ,
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
BackColor="White" BorderColor="#336699" BorderStyle="Solid" BorderWidth="1px"
CellPadding="0" CellSpacing="0" DataKeyNames="CategoryID" Font-Size="10"
Font-Names="Arial" GridLines="Vertical" Width="40%">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkStatus" runat="server"
AutoPostBack="true" OnCheckedChanged="chkStatus_OnCheckedChanged"
Checked='<%# Convert.ToBoolean(Eval("Approved")) %>'
Text='<%# Eval("Approved").ToString().Equals("True") ? " Approved " : " Not Approved " %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="CategoryID" HeaderText="CategoryID" />
<asp:BoundField DataField="CategoryName" HeaderText="CategoryName" />
</Columns>
<HeaderStyle BackColor="#336699" ForeColor="White" Height="20" />
For more information , check Here !
you can use TemplateFields for the GridView:
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField >
<ItemTemplate>
<asp:CheckBox ID="myCheckBox" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and in code behind use below code:
ClusterName = GV.Rows(1).Cells(2).FindControl("myLabelinTheGridViewTemplateField")