MultiView and GridView Paging issue - c#

I have a Multi View with two views in it. View1 has a Grid View and the grid-view allow paging by ten records.
The problem is i have to press page number tow times to go to that page.
The first click nothing happen the second click the grid view goes to the page what is the issue
<asp:GridView ID="gridusers" AutoGenerateColumns="false" runat="server" AllowPaging="true" OnPageIndexChanging="OnPageIndexChanging" PageSize="10" CssClass="table table-bordered text-nowrap" OnSelectedIndexChanged="gridusers_SelectedIndexChanged" OnRowDeleting="gridusers_RowDeleting">
<Columns>
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CssClass="btn btn-primary btn-xs" CausesValidation="False" CommandName="Select" Text="" ><i class="glyphicon glyphicon-pencil"></i></asp:LinkButton>
</ItemTemplate>
<controlstyle cssclass="btn btn-primary" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" OnClientClick="return confirm('Are you sure you want to delete this record ?');" CssClass="btn btn-primary btn-xs" CommandName="Delete" Text="Delete"><i class="glyphicon glyphicon-trash"></i></asp:LinkButton>
</ItemTemplate>
<controlstyle cssclass="btn btn-danger" />
</asp:TemplateField>
<asp:BoundField DataField="ID" HeaderText="Customer ID" SortExpression="Customer ID" />
<asp:BoundField DataField="Name" HeaderText="Customer Name" SortExpression="Name" />
<asp:BoundField DataField="Contact Person" HeaderText="Contact Person" SortExpression="Contact Person" />
<asp:BoundField DataField="P.O.Box" HeaderText="P.O.Box" SortExpression="P.O.Box" />
<asp:BoundField DataField="Address" HtmlEncodeFormatString="false" HeaderText="Address" SortExpression="Address" />
<asp:BoundField DataField="Mobile No" HeaderText="Mobile No" SortExpression="Mobile No" />
</Columns>
<SelectedRowStyle BackColor="#D1DDF1" ForeColor="#333333" />
</asp:GridView>
protected void Page_Load(object sender, EventArgs e)
{
CustomerClass c = new CustomerClass();
if (!this.IsPostBack)
{
gridusers.DataSource = c.getcst();
gridusers.DataBind();
}
}
protected void OnPageIndexChanging(object sender, GridViewPageEventArgs e)
{
gridusers.PageIndex = e.NewPageIndex;
this.c.getcst();
}

You are not rebinding the grid once the page number changes.
Your code is this:
protected void OnPageIndexChanging(object sender, GridViewPageEventArgs e)
{
gridusers.PageIndex = e.NewPageIndex;
this.c.getcst();
}
You need to do this instead:
protected void OnPageIndexChanging(object sender, GridViewPageEventArgs e)
{
gridusers.PageIndex = e.NewPageIndex;
gridusers.DataSource = c.getcst();
gridusers.DataBind();
}

Related

How to retrieve the value in GridView when I click on LinkButton of GridView

I am using gridview to display of data from database, in each row of the gridview I am having delete and edit link button. How can I get value of “NAME” and "DESCRIPTION" when I click on Delete or Edit Button in gridview.
The following is my code.
List.aspx
<div align="center" style="margin-top:50px">
<asp:GridView ID="gvDetails" runat="server" AutoGenerateColumns="false" CellPadding="5" runat="server">
<Columns>
<asp:BoundField HeaderText="Report Name" DataField="NAME" />
<asp:BoundField HeaderText="Report Description" DataField="DESCRIPTION" />
<asp:BoundField HeaderText="Report Group" DataField="REPORT_GROUP" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="btnDelete" Text="Delete" runat="server" OnClick="Btn_Delete_Click" />
<asp:LinkButton ID="btnEdit" Text="Edit" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />
</asp:GridView>
</div>
List.aspx.cs
protected void Btn_Delete_Click(object sender, EventArgs e)
{
}
use command argument like this
<ItemTemplate>
<asp:LinkButton ID="btnDelete" Text="Delete" runat="server" CommandArguman='<%# Eval("Name")+","+Eval("DESCRIPTION") %>' OnClick="Btn_Delete_Click" />
<asp:LinkButton ID="btnEdit" Text="Edit" runat="server" CommandArguman='<%# Eval("Name")+","+Eval("DESCRIPTION") %>' OnClick="btnEdit_Click" />
</ItemTemplate>
in onclick
protected void Btn_Delete_Click(object sender, EventArgs e)
{
string strName=((LinkButton)sender).CommandArgument.Split(',')[0];
string strDescription=((LinkButton)sender).CommandArgument.Split(',')[1];
}
protected void btnEdit_Click_Click(object sender, EventArgs e)
{
string strName=((LinkButton)sender).CommandArgument.Split(',')[0];
string strDescription=((LinkButton)sender).CommandArgument.Split(',')[1];
}

Get Particular Grid Column value on button click?

MY grid view code
<asp:GridView ID="grdAccidentMaster" runat="server" AutoGenerateColumns="False"
Width="80%" BackColor="White" BorderColor="#DEDFDE" BorderStyle="Solid" BorderWidth="1px"
EmptyDataText="No Records found" CellPadding="4" ForeColor="Black" GridLines="Both"
DataKeyNames="IncidentNo" OnRowDataBound="grdAccidentMaster_RowDataBound">
<Columns>
<asp:BoundField DataField="IncidentNo" HeaderText="IncidentNo" />
<asp:BoundField DataField="CreatedDate" HeaderText="Created Date" />
<asp:BoundField DataField="AccidentDate" HeaderText="Accident Date" />
<asp:BoundField DataField="PoliceStation" HeaderText="Police Station" />
<asp:BoundField DataField="City" HeaderText="City Name" />
<asp:BoundField DataField="RoadCondition" HeaderText="Road Condition" />
<asp:BoundField DataField="RoadFeature" HeaderText="Road Feature" />
<asp:TemplateField HeaderText="Print">
<ItemTemplate>
<asp:Button runat="server" Text="Click" ID="btnClick" OnClick="btnPrint_click" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
MY grid view Output
If i click the Click button under Print column. I need to get the IncidentNo value '4022' on onclick function.
Add an event in Gridview :
OnRowCommand="grdAccidentMaster_OnRowCommand"
Change template for button :
<ItemTemplate>
<asp:Button runat="server" Text="Click" ID="btnClick"
CommandName="SendIncidentNo" CommandArgument='<%# Eval("IncidentNo") %>' />
</ItemTemplate>
Code behind :
protected void grdAccidentMaster_OnRowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName != "SendIncidentNo") return;
int incidentNo = Convert.ToInt32(e.CommandArgument);
// do something
}

Delete and Update Row from GridView on Image Button

I want to delete the records from the Gridview on the click of ImageButton. Please see the GridView Code for your reference:-
<asp:GridView ID="grdCSRPageData" runat="server" Width="100%" border="1" Style="border: 1px solid #E5E5E5;" CellPadding="3" AutoGenerateColumns="false" OnDataBound="grdCSRPageData_DataBound" PageSize="5" AllowPaging="true" OnPageIndexChanging="grdCSRPageData_PageIndexChanging" OnRowCommand="grdCSRPageData_RowCommand">
<AlternatingRowStyle BackColor="#CCCCCC" />
<Columns>
<asp:TemplateField ItemStyle-Width="30">
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="page_title" HeaderText="Page Title" ItemStyle-Width="30" />
<asp:BoundField DataField="page_description" HeaderText="Page Description" ItemStyle-Width="30" />
<asp:BoundField DataField="meta_title" HeaderText="Meta Title" ItemStyle-Width="30" />
<asp:BoundField DataField="meta_keywords" HeaderText="Meta Keywords" ItemStyle-Width="30" />
<asp:BoundField DataField="meta_description" HeaderText="Meta Description" ItemStyle-Width="30" />
<asp:BoundField DataField="Active" HeaderText="Active" ItemStyle-Width="30" />
<asp:TemplateField HeaderText="Action" HeaderStyle-Width="15%">
<ItemTemplate>
<asp:ImageButton ID="btnEdit" runat="server" ImageUrl="~/images/edit.png" Width="15" Height="15" />
<span onclick="return confirm('Are you sure want to delete?')">
<asp:ImageButton ID="btnDelete" AlternateText="Delete" ImageUrl="~/images/delete.png" runat="server" Width="15" Height="15" CommandName="DeleteRow" />
</span>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="btnUpdate" Text="Update" runat="server" CommandName="Update" />
<asp:LinkButton ID="btnCancel" Text="Cancel" runat="server" CommandName="Cancel" />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Tried with 'RowCommand' property of GridView and stucked how to delete the Row
See the code:-
protected void grdCSRPageData_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "DeleteRow")
{
//incase you need the row index
int rowIndex = ((GridViewRow)((ImageButton)e.CommandSource).NamingContainer).RowIndex;
int Id = Convert.ToInt32(e.CommandArgument);
//followed by your code
}
}
try this
protected void grdCSRPageData_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "DeleteRow")
{
int rowIndex = ((GridViewRow)((ImageButton)e.CommandSource).NamingContainer).RowIndex;
grdCSRPageData.Rows.RemoveAt(rowIndex);
//delete from database
using (SqlConnection connection = new SqlConnection(connectionString))
{
int Id = Convert.ToInt32(e.CommandArgument);
string sql = "DELETE FROM YourTable WHERE ID = #ID";
SqlCommand cmd = new SqlCommand(sql,connection);
cmd.Parameters.AddWithValue("#ID",Id);
cmd.ExecuteNonQuery();
}
}
}
refer here for documentation about GridView remove.
SqlCommand documentation
update
to get the gridView from its row you can call this function
public static GridView GetParentGridView(GridViewRow row)
{
GridView gridView = (GridView)row.NamingContainer;
return gridView;
}
use it to get the gridview in my code
replace
grdCSRPageData.Rows.RemoveAt(rowIndex)
with
GetParentGridView((GridViewRow)((ImageButton)e.CommandSource).NamingContainer).Rows.RemoveAt(rowIndex)
be sure also to bind the grid only if there is no postback on page load
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//bind the gridView
}
}
Tried with Something like this and it worked.:-
<asp:GridView ID="grdCSRPageData" runat="server" Width="100%" border="1" Style="border: 1px solid #E5E5E5;" CellPadding="3" AutoGenerateColumns="False" OnDataBound="grdCSRPageData_DataBound" AllowPaging="True" OnPageIndexChanging="grdCSRPageData_PageIndexChanging" DataKeyNames="Id" OnRowDeleting="grdCSRPageData_RowDeleting" OnClientClick="return confirm('Are you sure you want to delete this record?')">
<AlternatingRowStyle BackColor="#CCCCCC" />
<Columns>
<%-- <asp:TemplateField ItemStyle-Width="30">
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
</ItemTemplate>
</asp:TemplateField>--%>
<asp:BoundField DataField="page_title" HeaderText="Page Title" ItemStyle-Width="30" />
<asp:BoundField DataField="page_description" HeaderText="Page Description" ItemStyle-Width="30" />
<asp:BoundField DataField="meta_title" HeaderText="Meta Title" ItemStyle-Width="30" />
<asp:BoundField DataField="meta_keywords" HeaderText="Meta Keywords" ItemStyle-Width="30" />
<asp:BoundField DataField="meta_description" HeaderText="Meta Description" ItemStyle-Width="30" />
<asp:BoundField DataField="Active" HeaderText="Active" ItemStyle-Width="30" />
<asp:TemplateField HeaderText="Action" HeaderStyle-Width="15%">
<ItemTemplate>
<%-- <asp:LinkButton ID="lbtnEdit" runat="server" CommandName="Edit" Text="Edit" />--%>
<asp:ImageButton ID="btnEdit" runat="server" ImageUrl="~/images/edit.png" Width="15" Height="15" />
<%-- <span onclick="return confirm('Are you sure want to delete?')"> -- %>
<%--<asp:LinkButton ID="btnDelete" Text="Delete" runat="server" CommandName="Delete" ></asp:LinkButton>--%>
<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>
<EditItemTemplate>
<asp:LinkButton ID="btnUpdate" Text="Update" runat="server" CommandName="Update" />
<asp:LinkButton ID="btnCancel" Text="Cancel" runat="server" CommandName="Cancel" />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Also see the code behind:-
protected void grdCSRPageData_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
bool IsDeleted = false;
//getting key value, row id
int Id = Convert.ToInt32(grdCSRPageData.DataKeys[e.RowIndex].Value.ToString());
using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "DELETE FROM tbl_Pages WHERE Id=#ID";
cmd.Parameters.AddWithValue("#ID", Id);
cmd.Connection = conn;
conn.Open();
IsDeleted = cmd.ExecuteNonQuery() > 0;
conn.Close();
}
}
if (IsDeleted)
{
//record has been deleted successfully!
//call here gridview bind method and replace it..
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Page Succesfully deleted');window.location ='csrpage.aspx';", true); ;
grdCSRPageData.DataBind();
}
else
{
//Error while deleting record
Response.Write("Some error");
}
}
Also the binding of the data should be inside the '(!IsPostBack)' method

Imagebutton not giving an index off gridview so modal cant open

Hi i have a gridview with a button on each row that opens a modal and it works. For testing purposes i gave my imagebutton the same commandName to see if it would also open the modal. Unfortunately it did not...
After a little debugging i found that the imagebutton does not return a index (the row number) so my details modal can not display as i get error:
An exception of type 'System.FormatException' occurred in mscorlib.dll but was not handled in user code
Additional information: Input string was not in a correct format.
I was wondering how i can pass the index number of the row using imagebutton.
I have included my code below:
markup
<asp:UpdatePanel ID="UserGridViewControl" runat="server">
<ContentTemplate>
<asp:GridView ID="GridViewUsers" runat="server" Width="940px" HorizontalAlign="Center"
OnRowCommand="GridView1_RowCommand" OnRowDataBound="GridView1_RowDataBound" AutoGenerateColumns="false" AllowPaging="true"
DataKeyNames="Ref" CssClass="table table-hover table-striped" OnPageIndexChanging="GridViewUsers_PageIndexChanging"
AllowSorting="true" OnSorting="GridViewUsers_Sorting">
<Columns>
<asp:BoundField DataField="Ref" SortExpression="Ref" HeaderText="Ref #" HeaderStyle-HorizontalAlign="Left" />
<asp:BoundField DataField="Listed" SortExpression="Listed" HeaderText="Listed" HeaderStyle-HorizontalAlign="Left" />
<asp:BoundField DataField="DateListed" dataformatstring="{0:MMMM d, yyyy}" SortExpression="DateListed" HeaderText="Date Listed" HeaderStyle-HorizontalAlign="Left" />
<asp:BoundField DataField="Type" SortExpression="Type" HeaderText="Type" HeaderStyle-HorizontalAlign="Left" />
<asp:ButtonField CommandName="editRecord" ControlStyle-CssClass="btn btn-info" ButtonType="Button" Text="View Services" HeaderText="Additional Services">
<ControlStyle CssClass="btn btn-info"></ControlStyle>
</asp:ButtonField>
<asp:BoundField DataField="London" SortExpression="London" HeaderText="London" HeaderStyle-HorizontalAlign="Left" />
<asp:BoundField DataField="MoveInDate" dataformatstring="{0:MMMM d, yyyy}" SortExpression="MoveInDate" HeaderText="Movie in Date" HeaderStyle-HorizontalAlign="Left" />
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:ImageButton ID="ImageButton1" CommandName="detail" ButtonType="Button" runat="server" />
<asp:ImageButton ID="ImageButton2" runat="server" />
<asp:ImageButton ID="ImageButton3" runat="server" />
<asp:ImageButton ID="ImageButton4" runat="server" />
<asp:ImageButton ID="ImageButton5" runat="server" />
<asp:ImageButton ID="ImageButton6" runat="server" />
<asp:ImageButton ID="ImageButton7" runat="server" />
<asp:ImageButton ID="ImageButton8" runat="server" />
<asp:ImageButton ID="ImageButton9" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:ButtonField CommandName="detail" ControlStyle-CssClass="btn btn-info" ButtonType="Button" Text="Detail" HeaderText="Details">
<ControlStyle CssClass="btn btn-info"></ControlStyle>
</asp:ButtonField>
</Columns>
</asp:GridView>
</ContentTemplate>
<Triggers>
</Triggers>
</asp:UpdatePanel>
Codebehind
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("detail"))
{
LoadSortedDB();
int index = Convert.ToInt32(e.CommandArgument); // Breaks Here as there is no value in command argument
Int32 LoweredEmailCheck = Convert.ToInt32(GridViewUsers.DataKeys[index].Value);
IEnumerable<DataRow> query = from i in dt.AsEnumerable()
where i.Field<Int32>("Ref").Equals(LoweredEmailCheck)
select i;
DataTable detailTable = query.CopyToDataTable<DataRow>();
DetailsView1.DataSource = detailTable;
DetailsView1.DataBind();
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append(#"<script type='text/javascript'>");
sb.Append("$('#detailModal').modal('show');");
sb.Append(#"</script>");
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "DetailModalScript", sb.ToString(), false);
}
}
use find to get object of asp ajax modal popup
with id:
var modalobj=$find("<%=modalid.ClientID%>");
modalobj.show();
with Behaviourid:
var modalobj=$find("Behaviourid");
modalobj.show();
Working with your code:
sb.Append(#"<script type='text/javascript'>");
sb.Append("$find('detailModal').show();");
sb.Append(#"</script>");
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "DetailModalScript", sb.ToString(), false);
Finding modal popup with Behaviourid

How to call a command of a rad grid

i have a rad grid with the following code
<telerik:GridTemplateColumn>
<ItemTemplate>
<asp:LinkButton ID="Delete" Text="Remove &raquo"
CommandArgument='<%# Eval("ApartmentId") %>'
CommandName="RemoveItem" CssClass="Button" runat="server" />
</ItemTemplate>
</telerik:GridTemplateColumn>
and .CS code as follows
protected void radGrid_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Page")
{
}
else
{
if (e.CommandName == "RemoveItem")
{
Apartments apartAdmin = new Apartment();
bool deleted = apartAdmin.Delete(int.Parse(e.CommandArgument.ToString());
if (deleted)
{
radGrid.Rebind();
}
}
}
}
My problem is that when I debug it, say I add the breakpoint to this event, it is never fired, is like if it does not see the event for some reason... Can anyone see what the problem may be? This is the mark up of the grid at the top
<telerik:RadGrid ID="radGrid" ShowFooter="true" ShowHeader="true" CaptionAlign="Left"
runat="server" ForeColor="Black" CellPadding="4" AutoGenerateColumns="False"
CssClass="Grid" Width="100%" GridLines="None" OnRowCommand="radGrid_RowCommand"
OnNeedDataSource="radGrid_NeedDataSource" AllowPaging="True" AllowSorting="true">
<MasterTableView DataKeyNames="ApartmentID,ApartmentTypeID">
<CommandItemSettings ShowRefreshButton="true" ShowAddNewRecordButton="false" />
<Columns>
<telerik:GridTemplateColumn>
<ItemTemplate>
<asp:LinkButton ID="Delete" Text="Remove &raquo"
CommandArgument='<%# Eval("ApartmentId") %>'
CommandName="RemoveItem" CssClass="Button" runat="server" />
</ItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
<NoRecordsTemplate>
No related items found</NoRecordsTemplate>
</MasterTableView>
<FooterStyle CssClass="FooterStyle" />
<ItemStyle CssClass="RowStyle" />
<HeaderStyle CssClass="HeaderStyle" />
<AlternatingItemStyle CssClass="AlternatingRowStyle" />
<PagerStyle CssClass="PagerStyle" FirstPageText="First" LastPageText="Last" Mode="NextPrevAndNumeric"
AlwaysVisible="true" />
</telerik:RadGrid>
You have a linkbutton inside an itemtemplate, add a handler for OnClick on the linkbutton itself and the event will surely be fired.
For example:
protected void LinkButton1_Click(Object sender, EventArgs
{
LinkButton button = sender as LinkButton;
Apartments apartAdmin = new Apartment();
bool deleted = apartAdmin.Delete(int.Parse(button.CommandArgument.ToString());
if (deleted)
{
radGrid.Rebind();
}
}

Categories