Onselect in Dropdown send mail to respective user - c#

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

Related

Column sum of only visible row

I am trying to calculate the sum of the grand total column and showing it to the footer of the gridview, which I am able to achieve it. However I have a condition which makes some rows invisible from the gridview, but it is also summing the value of the rows which are invisible. How to sum the column value only for the rows which are visible?
Below is my gridview:
<asp:GridView ID="GridView9" runat="server" AllowPaging="false" AutoGenerateColumns="False"
ShowFooter="true" BackColor="White" DataKeyNames="ID" BorderColor="#999999" CssClass="tableUserInfo"
GridLines="Vertical" ShowHeaderWhenEmpty="True" PageSize="10" OnRowDataBound="GridView9_RowDataBound">
<AlternatingRowStyle BackColor="#CCCCCC" />
<Columns>
<asp:TemplateField HeaderText="SessionId" Visible="true">
<ItemTemplate>
<asp:TextBox ID="txt_GSessionId" runat="server" Text='<%# Eval("SessionId") %>' ReadOnly="true"
Visible="false"></asp:TextBox>
</ItemTemplate>
<HeaderStyle Width="10%" />
<ItemStyle Width="10%" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Customer" Visible="true">
<ItemTemplate>
<asp:Label ID="lblCustomerName" Font-Size="11px" runat="server" Text='<%# Eval("CustomerName") %>'></asp:Label>
</ItemTemplate>
<HeaderStyle Width="8%" />
<ItemStyle Width="8%" />
</asp:TemplateField>
<asp:TemplateField HeaderText="G_Total" Visible="true">
<ItemTemplate>
<asp:Label ID="lblGTotal" Font-Size="11px" runat="server" Text='<%# Eval("GTotal","{0:n}") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="lblTotal" runat="server" Text="Label"></asp:Label>
</FooterTemplate>
<FooterStyle Width="30%" />
<HeaderStyle Width="8%" />
<ItemStyle Width="8%" />
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="Black" ForeColor="Red" Width="100%" Wrap="false" />
<HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
</asp:GridView>
Here is my code behind:
decimal grdTotal;
protected void GridView9_RowDataBound(object sender, GridViewRowEventArgs e)
{
txt_SessionId.Text = ddlSession.SelectedValue;
foreach (GridViewRow row2 in GridView9.Rows)
{
TextBox sid = row2.FindControl("txt_GSessionId") as TextBox;
int a, b;
a = int.Parse(sid.Text);
b = int.Parse(txt_SessionId.Text);
if (a == b)
{
row2.Visible = true;
}
else
{
row2.Visible = false;
}
}
if (e.Row.Visible && e.Row.RowType == DataControlRowType.DataRow)
{
decimal rowTotal = Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "GTotal"));
grdTotal = grdTotal + rowTotal;
}
if (e.Row.RowType == DataControlRowType.Footer)
{
Label lbl = (Label)e.Row.FindControl("lblTotal");
Label lbl1 = (Label)e.Row.FindControl("lblLabourTotal");
lbl.Font.Size = 12;
lbl.Text = "Rs. " + grdTotal.ToString("0");
lbl.ForeColor = System.Drawing.Color.White;
}
}

How to find TextBox in GridViewRow edit mode

I have tried several so called answers for this and it has me lost. I am simply trying to default a TextBox Text value with today's date and time, but I cannot find the control when I click LinkButton with CommandName "Edit".
Here is my gridview...
<asp:GridView ID="gvSignInRegister" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" CellPadding="3"
DataSourceID="sdsSignInRegister" ForeColor="Black" BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" GridLines="Vertical" OnRowCommand="gvSignInRegister_RowCommand1">
<Columns>
<asp:TemplateField HeaderText="Returned" SortExpression="DateTimeReturned">
<EditItemTemplate>
<asp:TextBox ID="txtReturned" runat="server"></asp:TextBox>
<asp:ImageButton runat="Server" ID="calImg" ImageUrl="~/images/Calendar_scheduleHS.png" AlternateText="Click to show calendar" CausesValidation="False" />
<asp:RequiredFieldValidator ID="rfv1" runat="server" SetFocusOnError="true" ValidationGroup="vg1" ControlToValidate="txtReturned" ErrorMessage="Required"></asp:RequiredFieldValidator>
<ajaxToolkit:CalendarExtender ID="ce1" runat="server" PopupButtonID="calImg" Enabled="true" Format="dd/MM/yyyy" TargetControlID="txtReturned" PopupPosition="TopRight" OnClientDateSelectionChanged="AppendTime"></ajaxToolkit:CalendarExtender>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label9" runat="server" Text='<%# Eval("DateTimeReturned","{0:dd/MM/yyyy HH:mm}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<EditItemTemplate>
<asp:Button ID="btnCAN" runat="server" CausesValidation="false" CommandName="Cancel" Text="CANCEL" />
<asp:Button ID="btnUPD" runat="server" ValidationGroup="vg1" CausesValidation="true" CommandName="Update" Text="UPDATE" />
</EditItemTemplate>
<ItemTemplate>
<asp:Button ID="btnEDT" runat="server" CausesValidation="false" CommandName="Edit" CommandArgument='<%# Container.DataItemIndex %>' Text="SIGN IN" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#CCCCCC" />
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="#CCCCCC" />
</asp:GridView>
The LinkButton btnEDT works and puts the gridview in edit mode. But in code behind I cannot find "txtReturned".
This is what I've tried so far...
protected void gvSignInRegister_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Edit")
{
int rowIdx = Convert.ToInt32(e.CommandArgument);
GridViewRow row = gvSignInRegister.Rows[rowIdx];
if (row != null && row.RowType == DataControlRowType.DataRow)
{
TextBox tb = (TextBox)row.FindControl("txtReturned");
if (tb != null) tb.Text = DateTime.Now.ToString("dd/MM/yyyy HH:mm");
//I've tried this too but it does not work. Interestingly, it does not crash, so cells[4] must exist!
//row.Cells[4].Text = DateTime.Now.ToString("dd/MM/yyyy HH:mm");
}
}
}
For some reason the rowIdx is always 0. Why? I thought a row index of 0 meant the header of the gridview control.
I've also tried using the NamingContainer that most other people have suggested in other posts, but that returns a blank (I suspect new?) GridViewRow.
ie
GridViewRow row = (GridViewRow)((GridViewRow)(e.CommandSource).NamingContainer);
UPDATE
I found this, which is exactly the problem I am having, but the solution via the RowEditing still does not find the textbox!
However the RowDataBound() solved it! Read my answer below.
The answer was in getting into the editmode version of the GridView itself and then find the control!
As per this post...
<asp:GridView ID="gvSignInRegister" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" CellPadding="3"
DataSourceID="sdsSignInRegister" ForeColor="Black" BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" GridLines="Vertical" OnRowDataBound="gvSignInRegister_RowDataBound">
<Columns> ...etc...
protected void gvSignInRegister_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
TextBox tb = (TextBox)e.Row.FindControl("txtReturned");
if (tb != null) tb.Text = DateTime.Now.ToString("dd/MM/yyyy HH:mm");
}
}
}
Use Container.DisplayIndex instead of Container.DataItemIndex
But I dont think you will get textBox control if you are placing it in EditItemTemplate
If your expectation is editing operation then please use the below code
HTML
<asp:GridView ID="gvSignInRegister" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" CellPadding="3" ForeColor="Black" BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" OnRowEditing="gvSignInRegister_RowEditing" OnRowCancelingEdit="gvSignInRegister_RowCancelingEdit" OnRowUpdating ="gvSignInRegister_RowUpdating" GridLines="Vertical">
<Columns>
<asp:TemplateField HeaderText="Returned" SortExpression="DateTimeReturned">
<EditItemTemplate>
<asp:TextBox ID="txtReturned" Text='<%#Bind("DateTimeReturned", "{0:dd/MM/yyyy HH:mm}")%>' runat="server"></asp:TextBox>
<asp:ImageButton runat="Server" ID="calImg" ImageUrl="~/images/Calendar_scheduleHS.png" AlternateText="Click to show calendar" CausesValidation="False" />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label9" runat="server" Text='<%# Eval( "DateTimeReturned","{0:dd/MM/yyyy HH:mm}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="true" />
</Columns>
<FooterStyle BackColor="#CCCCCC" />
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="#CCCCCC" />
</asp:GridView>
Code Behind:
protected void gvSignInRegister_RowEditing(object sender, GridViewEditEventArgs e)
{
gvSignInRegister.EditIndex = e.NewEditIndex;
List<QuotationDetail> itemList = (List<QuotationDetail>)ViewState["ItemList"];
gvSignInRegister.DataSource = itemList;
gvSignInRegister.DataBind();
}
protected void gvSignInRegister_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
}
protected void gvSignInRegister_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
var txtQty = (TextBox)gvSignInRegister.Rows[e.RowIndex].FindControl("txtQuantity");
decimal qty = 0;
decimal.TryParse(txtQty.Text, out qty);
if (qty < 0)
{
lblErrorSummary.InnerText = "Please provide valid Quantity";
lblErrorSummary.Visible = true;
return;
}
itemList[e.RowIndex].Quantity = qty
ViewState["ItemList"] = itemList;
gvSignInRegister.EditIndex = -1;
gvSignInRegister.DataSource = itemList;
gvSignInRegister.DataBind();
}

Gridview rowcommand

I have a little problem when I go to my gridview in website my button for row command doesn't work. I don't know why.
This is my code for the page:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Ver")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow selectedRow = GridView1.Rows[index];
Session["Imagem"] = GridView1.DataKeys[index]["Imagem"];
Session["Nome"] = GridView1.DataKeys[index]["Nome"];
Session["Preço"] = GridView1.DataKeys[index]["Preço"];
Session["Descricao"] = GridView1.DataKeys[index]["Descricao"];
Session["Categoria"] = GridView1.DataKeys[index]["Categoria"];
Session["id"] = GridView1.DataKeys[index]["Id"];
Session["estado"] = GridView1.DataKeys[index]["estado"];
GridView1.DataBind();
Response.Redirect("Detalhes.aspx");
}
}
And my gridview markup is this:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="Imagem ,Nome,Preço,Descricao,Categoria,id,estado"
DataSourceID="SqlShop" OnRowCommand="GridView1_RowCommand"
BackColor="White" BorderColor="#3366CC" BorderStyle="None"
BorderWidth="1px" CellPadding="4" style="margin-top: 0px">
<Columns>
<asp:TemplateField HeaderText="Imagem" SortExpression="Imagem">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Imagem") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Image ID="Image1" runat="server" ImageUrl='<%# Eval("Imagem") %>' Height="8%" Width="8%" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Nome" HeaderText="Nome" SortExpression="Nome" />
<asp:BoundField DataField="Preço" HeaderText="Preço" SortExpression="Preço" />
<asp:BoundField DataField="Descricao" HeaderText="Descricao" SortExpression="Descricao" />
<asp:BoundField DataField="Categoria" HeaderText="Categoria" SortExpression="Categoria" />
<asp:ButtonField ButtonType="Button" CommandName="Select" Text="ver" />
</Columns>
<FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
<HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="#CCCCFF" />
<PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Left" />
<RowStyle BackColor="White" ForeColor="#003399" />
<SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
<SortedAscendingCellStyle BackColor="#EDF6F6" />
<SortedAscendingHeaderStyle BackColor="#0D4AC4" />
<SortedDescendingCellStyle BackColor="#D6DFDF" />
<SortedDescendingHeaderStyle BackColor="#002876" />
</asp:GridView>
<asp:SqlDataSource ID="SqlShop" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT * FROM [Produtos]">
</asp:SqlDataSource>
Command name is incorrect in the C# code
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select") //this part
{
int index = Convert.ToInt32(e.CommandArgument);
...
...
Response.Redirect("Detalhes.aspx");
}
}
Or
You can change the values ButtonField parameters as
<asp:ButtonField ButtonType="Button" CommandName="ver" Text="Select" />

PagerTemplate in gridview not working properly

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();
}

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