This is my first time for using ASP.NET to develop website.
I want to show my data from database in a GridView with Paging function and I can implement it by using OnPageIndexChanging="GridView1_PageIndexChanging" but I want to use my own pager so the question is
"How can I link my pager (the right bottom in the pic) to the gridview instead the pager which generated by the ASP.NET"
Pics:
This is my code in aspx
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" CssClass="table table-bordered table-condensed table-striped table-primary table-vertical-center"
PageSize="3" AllowPaging="True"
OnPageIndexChanging="GridView1_PageIndexChanging">
<Columns>
<asp:BoundField DataField="UNIT_ID" HeaderText="รหัส" SortExpression="unitid">
<HeaderStyle CssClass="center" />
<ItemStyle Width="10%" CssClass="center" />
</asp:BoundField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
Code in cs
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
bindGridView();
}
protected void bindGridView() {
string sqltxt = "select * from drug_units"; //where UNIT_ID =:unitid";
CommandData comm = new CommandData();
comm.SetCommandText(sqltxt);
//comm.AddInputParameter("unitid", "5");
List<DrugsUnit> dy = new List<DrugsUnit>();
comm.ExecuteNonQuery();
dy = comm.ExecuteToList<DrugsUnit>();
GridView1.DataSource = dy;
/*BoundField boundField = new BoundField();
boundField.DataField = "UNIT_ID";
boundField.HeaderText = "ID";
boundField.SortExpression = "ID";
boundField.HeaderStyle.CssClass = "center";
boundField.ItemStyle.CssClass = "center";
GridView1.Columns.Add(boundField);*/
GridView1.DataBind();
GridView1.HeaderRow.TableSection = TableRowSection.TableHeader;
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
bindGridView();
}
}
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Pager)
{
upGridPager.Update();
e.Row.SetRenderMethodDelegate(new RenderMethod((w, r) =>
{
e.Row.SetRenderMethodDelegate(null);
using (var ms = new StringWriter())
using (var writer = new HtmlTextWriter(ms))
{
e.Row.RenderControl(writer);
GridPager.InnerHtml = "<table>" + ms.ToString() + "</table>";
}
}));
}
The aspx could look like this (outside of your grid)
<asp:UpdatePanel ID="upGridPager" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<div runat="server" id="GridPager" />
</ContentTemplate>
</asp:UpdatePanel>
Related
This is my current design in my GridView, the cells becomes orange on hover, this is achieved by using css. But my problem is how can I changed the cell background color if it is the one that is active?
Image: Current Design
HTML Code: (Only GridView)
<asp:GridView ID="GridView1" runat="server" PageSize="20" OnPageIndexChanging="GridView1_PageIndexChanging"
AllowPaging="True" OnDataBound="GridView1_DataBound"
Style="position: static">
<PagerSettings Position="Top" Mode="Numeric" />
<PagerStyle ForeColor="Black" HorizontalAlign="Center" Font-Underline="False" CssClass="pager" />
<PagerTemplate>
<table id="tablePager">
<tr style="background-color: #F8F8F8;">
<td>
<asp:LinkButton ID="First" CommandName="Page" CommandArgument="First" runat="server"
Text="<< First" Style="color: black" ForeColor="Black" Font-Underline="False"></asp:LinkButton>
</td>
<td>
<asp:LinkButton ID="Previous" CommandName="Page" CommandArgument="Prev" runat="server"
Text="< Previous" Style="color: black" ForeColor="Black" Font-Underline="False"></asp:LinkButton>
</td>
<asp:Repeater ID="Repeater1" runat="server" OnItemCommand="Repeater_ItemCommand" OnItemDataBound="Repeater_ItemDataBound" OnLoad="Repeater_Load">
<ItemTemplate>
<td id="cell">
<asp:LinkButton ID="lnkPageNumber" CommandName="Page" runat="server" ForeColor="Black" Font-Underline="False" />
</td>
</ItemTemplate>
</asp:Repeater>
<td>
<asp:LinkButton ID="Next" CommandName="Page" CommandArgument="Next" runat="server"
Text="Next >" ForeColor="Black" Font-Underline="False"></asp:LinkButton>
</td>
<td>
<asp:LinkButton ID="Last" CommandName="Page" CommandArgument="Last" runat="server"
Text="Last >>" Style="color: black" ForeColor="Black" Font-Underline="False"></asp:LinkButton>
</td>
</tr>
</table>
</PagerTemplate>
</asp:GridView>
Code Behind:
Page Load
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
PopulateGridView();
}
}
PopulateGridView
public void PopulateGridView()
{
String constring = System.Configuration.ConfigurationManager.ConnectionStrings["sqlconnect"].ToString();
MySqlConnection con = new MySqlConnection(constring);
using (MySqlCommand cmd = new MySqlCommand("SELECT * FROM tabletester"))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
MySqlDataReader reader = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(reader);
con.Close();
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
Repeater_ItemCommand
protected void Repeater_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "Page")
{
GridView1.PageIndex = Convert.ToInt32(e.CommandArgument);
GridView1.DataBind();
PopulateGridView();
}
}
Repeater_ItemDataBound
protected void Repeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
LinkButton lnkPageNumber = new LinkButton();
System.Int32 pageNumber = (System.Int32)e.Item.DataItem;
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
lnkPageNumber = (LinkButton)e.Item.FindControl("lnkPageNumber");
lnkPageNumber.Text = pageNumber.ToString();
lnkPageNumber.CommandArgument = (pageNumber - 1).ToString();
}
}
Repeater_Load
protected void Repeater_Load(object sender, EventArgs e)
{
Repeater Repeater = (Repeater)sender;
Repeater.DataSource = Enumerable.Range(1, GridView1.PageCount);
Repeater.DataBind();
}
You could do something like this in Repeater_ItemDataBound
if (e.Item.ItemIndex == GridView1.PageIndex)
{
lnkPageNumber.ForeColor = Color.Red;
}
That said, do you now a GridView has a build-in paging system? Much easier that the overly complex stuff you are doing. Below is all the code it takes:
ASPX
<asp:GridView ID="GridView1" runat="server" AllowPaging="true" PageSize="5"
OnPageIndexChanging="GridView1_PageIndexChanging"></asp:GridView>
CODE
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
BindDataToGridView();
}
}
private void BindDataToGridView()
{
GridView1.DataSource = source;
GridView1.DataBind();
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
BindDataToGridView();
}
This is IT. All the code you need for a functional paging system.
I found implementation of my problem on a side but i dont know why it isn't working. When i put some value into textbox it should do me a postback but it does not.
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true" />
<div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="txt" />
</Triggers>
<ContentTemplate>
<asp:TextBox runat="server" ID="TextBox1" AutoPostBack="true" OnTextChanged="txt_TextChanged"></asp:TextBox>
<asp:GridView runat="server" ID="GridView2">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" ItemStyle-Font-Size="10px" />
<asp:BoundField DataField="regon" HeaderText="Regon" SortExpression="regon" ItemStyle-Font-Size="10px" />
<asp:BoundField DataField="nip" HeaderText="NIP" SortExpression="nip" ItemStyle-Font-Size="10px" />
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</div>
And code behind :
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
txt.Attributes.Add("onkeyup", "javascript:setTimeout('__doPostBack(\'txt\',\'\')', 0)");
string SelectCommand = "SELECT * " +
" FROM client_inf WHERE amount > 1000";
conn.Open();
OleDbDataAdapter da = new OleDbDataAdapter(SelectCommand, conn);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
conn.Close();
}
}
protected void txt_TextChanged(object sender, EventArgs e)
{
if (txt.Text != "")
{
string SelectCommand = "SELECT * " +
" FROM client_inf WHERE client_name Like '" + txt.Text + "%'"
conn.Open();
OleDbDataAdapter da = new OleDbDataAdapter(SelectCommand, conn);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
conn.Close();
}
}
http://www.infosearchshop.com/21-gridview-search-as-you-type-with-ajax
I would suggest to update the AsyncPostBackTrigger as follow to match the ID of the textbox = TextBox1 with the AutoPostBack reference but the control needs to be outside the UpdatePanel
<asp:AsyncPostBackTrigger ControlID ="TextBox1" EventName ="TextChanged" />
I would also suggest trying to use PostBackTrigger instead. This is mostly used for controls inside the UpdatePanel that makes a full post back
<asp:PostBackTrigger ControlID="TextBox1" />
TextBox 's id and GridView's ID don't match .
<div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="txt" />
</Triggers>
<ContentTemplate>
<asp:TextBox runat="server" ID="txt" AutoPostBack="true" OnTextChanged="txt_TextChanged"></asp:TextBox>
<asp:GridView runat="server" ID="GridView1">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" ItemStyle-Font-Size="10px" />
<asp:BoundField DataField="regon" HeaderText="Regon" SortExpression="regon" ItemStyle-Font-Size="10px" />
<asp:BoundField DataField="nip" HeaderText="NIP" SortExpression="nip" ItemStyle-Font-Size="10px" />
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</div>
aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
txt.Attributes.Add("onkeyup", "javascript:setTimeout('__doPostBack(\'txt\',\'\')', 0)");
GridView1.DataSource = GetDataSource();
GridView1.DataBind();
}
}
private DataTable GetDataSource()
{
var dt = new DataTable();
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("regon", typeof(string));
dt.Columns.Add("nip", typeof(string));
dt.Rows.Add("Name-1", "regon-1", "nip-1");
dt.Rows.Add("Name-2", "regon-1", "nip-1");
dt.Rows.Add("Name-3", "regon-1", "nip-1");
dt.Rows.Add("Name-4", "regon-1", "nip-1");
dt.Rows.Add("Name-5", "regon-1", "nip-1");
dt.Rows.Add("Name-6", "regon-1", "nip-1");
dt.Rows.Add("Name-7", "regon-1", "nip-1");
return dt;
}
protected void txt_TextChanged(object sender, EventArgs e)
{
if (txt.Text != "")
{
GridView1.DataSource = GetDataSource();
GridView1.DataBind();
}
}
I have a gridview which has paging but when I click on Page 2 - page refreshes and returns the first page and the page link also remains on page 1.
Any help will be really appreciated :)
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
onpageindexchanging="GridView1_PageIndexChanging"
onrowcommand="GridView1_RowCommand" AutoGenerateColumns="False"
onrowdatabound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="Sequence" HeaderText="Sequence" HeaderStyle-
Width="10%"/>
<asp:TemplateField HeaderStyle-Width="90%">
<ItemTemplate>
<asp:Label ID="lblTitle" runat="server" Text='<%# Eval("Title") %>' Font-
Strikeout='<%# ((Convert.ToBoolean(Eval("Obsolete")))?true:false) %>' />
</ItemTemplate>
</asp:TemplateField>
Codebehind:-
private void BuildResults()
{
DataTable dt01 = obSectionDefinition.List(_criteria.AuditDefinitionGUID,
_criteria.ParentGUID, _criteria.ShowObsolete);
GridView1.PageSize = 20;
ViewState["dt_data"] = dt01;
GridView1.DataSource = dt01;
GridView1.DataBind();
}
PageIndexChanging:-
public void GridView1_PageIndexChanging(object
sender,GridViewPageEventArgse)
{
GridView x = ((GridView)sender);
GridView1.DataSource = ViewState["dt_data"];
if (e.NewPageIndex > -1 && e.NewPageIndex <= x.PageCount)
{
x.PageIndex = e.NewPageIndex+1;
}
else
{
e.NewPageIndex--;
}
GridView1.DataBind();
}
Page Load:-
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
BuildResults();
}
}
modify PageIndexChanging code
public void GridView1_PageIndexChanging(object sender,GridViewPageEventArgse)
{
GridView1.DataSource = (DataTable)ViewState["dt_data"];
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataBind();
}
Set AllowPaging=”True” Properties of GridView to enable paging
Set PageSize property to mention how many records will be displayed on
each page.
HTML MARKUP :
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" PageSize="20"
onpageindexchanging="GridView1_PageIndexChanging"
onrowcommand="GridView1_RowCommand" AutoGenerateColumns="False"
onrowdatabound="GridView1_RowDataBound">
</asp:GridView>
private void BuildResults()
{
DataTable dt01 = obSectionDefinition.List(_criteria.AuditDefinitionGUID, _criteria.ParentGUID, _criteria.ShowObsolete);
// GridView1.PageSize = 20;
// ViewState["dt_data"] = dt01;
GridView1.DataSource = dt01;
GridView1.DataBind();
}
public void GridView1_PageIndexChanging(object sender,GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
BuildResults();
}
I had a Response.Write on the page elsewhere and this was causing the paging to fail - removed it and this now works
I'm having trouble with setting a HiddenField's value to a GridView item value. What I want to do is get the value of a BoundField (in this case, "FIPSCountyCode") in a GridView and store it in a HiddenField when the user clicks a button (in this case, "btnEdit") to make changes to a entry in the grid. I haven't used HiddenFields before, so I have forgotten what to do here.
The HiddenField is setup like this:
<asp:HiddenField ID="hdnFIPS" Value='<%#Eval("FIPSCountyCode")%>' runat="server" />
This is what the GridView is setup like:
<asp:GridView ID="CountyList" runat="server" AutoGenerateColumns="False" Width="90%" SkinId="PagedList" PagerSettings-Position="TopAndBottom" PagerStyle-Wrap="True">
<Columns>
<asp:BoundField HeaderText="County Code" DataField="FIPSCountyCode" />
<asp:BoundField HeaderText="State Code" DataField="StateCode" />
<asp:BoundField HeaderText="County Name" DataField="CountyName" />
<asp:BoundField HeaderText="Tax Rate" DataField="TaxRate" />
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="btnEdit" runat="server" SkinID="EditIcon" OnClick="EditInfo" CommandName="DoEdit" />
<asp:ImageButton ID="DeleteButton" runat="server" SkinID="DeleteIcon" CommandName="DoDelete"
OnClientClick="return confirm('Are you sure you want to remove this item and all of its options?')"
CausesValidation="false" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<AlternatingRowStyle CssClass="even" />
</asp:GridView>
And this is the code behind:
public partial class Admin_County_Info : CommerceBuilder.UI.AbleCommerceAdminPage
{
private string redirectString = String.Empty;
protected void Page_Load(object sender, System.EventArgs e)
{
if (!Page.IsPostBack)
PopulateCountyGrid();
}
protected void PopulateCountyGrid()
{
try
{
System.Data.SqlClient.SqlDataReader dr = null;
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["AbleCommerce"].ToString()))
{
SqlCommand cmd = new SqlCommand("SELECT [FIPSCountyCode], [StateCode], [CountyName], [TaxRate] FROM [baird_InfoCounty]", cn);
cmd.CommandType = CommandType.Text;
cn.Open();
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
CountyList.DataSource = dr;
CountyList.DataBind();
}
}
catch (Exception eX)
{
}
}
#region Clicks and Event Handlers
protected void EditInfo(object sender, System.EventArgs e)
{
if (Page.IsValid)
{
redirectString = "~/Admin/Taxes/AddEditCountyInfo.aspx?FIPSCountyCode=" + hdnFIPS.Value;
Response.Redirect(redirectString);
}
}
protected void AddInfo(object sender, System.EventArgs e)
{
if (Page.IsValid)
{
Response.Redirect("~/Admin/Taxes/AddEditCountyInfo.aspx");
}
}
}
This must be a really dumb question but I'm really not sure how to proceed. Any help would be great!
You can get the value of FIPSCountyCode from the BoundField this way:
protected void EditInfo(object sender, System.EventArgs e)
{
if (Page.IsValid)
{
GridViewRow gvr = ((ImageButton)sender).NamingContainer as GridViewRow;
hdnFIPS.Value = gvr.Cells[0].Text;
redirectString = "~/Admin/Taxes/AddEditCountyInfo.aspx?FIPSCountyCode=" + hdnFIPS.Value;
Response.Redirect(redirectString);
}
}
I will post you my code and i will explain what i want to do
<div>
<div>
<asp:GridView ID="gridView1" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
<asp:HiddenField ID="hdValue" runat="server" Value='<%#Eval("ID") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<div>
<asp:Button ID="btnMove" runat="server" Text="Add To Cart" OnClick="btnMove_Click" />
</div>
<div>
<asp:GridView ID="gridView2" runat="server">
<Columns>
<asp:TemplateField HeaderText="Quantity">
<ItemTemplate>
<asp:TextBox ID="tbQty" runat="server" Width="25px"
MaxLength="3" />
</ItemTemplate>
<ItemStyle Width="25px" HorizontalAlign="Center"/>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<br />
<asp:Button ID="Button1" runat="server" Text="Find the total" />
<asp:Label ID="Label7" runat="server" Text="Total"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server" ontextchanged="TextBox1_TextChanged"></asp:TextBox>
<br />
<br />
</div>
and the theo.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
public partial class theo : System.Web.UI.Page
{
const string key = "MyDataSource5";
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridView();
}
}
private void BindGridView()
{
if (Session[key] == null)
{
gridView1.DataSource = GetDataSource();
gridView1.DataBind();
}
else
{
gridView1.DataSource = (DataTable)Session[key];
gridView1.DataBind();
}
}
protected DataTable GetDataSource()
{
try
{
DataTable dt = new DataTable();
dt = new DataTable();
dt.Columns.Add("ID", typeof(int)).AutoIncrement = true;
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Price(Grouch)/Hectares", typeof(float));
DataColumn[] keys = new DataColumn[2];
keys[0] = dt.Columns["ID"];
dt.PrimaryKey = keys;
dt.Rows.Add("1", "Seaside Location", 1.5);
dt.Rows.Add("2", "Arable Land", 0.1);
dt.Rows.Add("3", "Foothills of the mountains", 1.5);
dt.Rows.Add("4", "Industrial Land", 0.1);
dt.Rows.Add("5", "Rolling Farmland", 0.5);
Session[key] = dt;
return dt;
}
catch
{
return null;
}
}
protected void btnMove_Click(object sender, EventArgs e)
{
try
{
DataTable dtMain = Session[key] as DataTable;
//copy the schema of source table
DataTable dtClone = dtMain.Clone();
foreach (GridViewRow gv in gridView1.Rows)
{
CheckBox chk = gv.FindControl("chkSelect") as CheckBox;
HiddenField hdValue = gv.FindControl("hdValue") as HiddenField;
if (chk.Checked)
{
//get only the rows you want
DataRow[] results = dtMain.Select("ID=" + hdValue.Value + "");
//populate new destination table
foreach (DataRow dr in results)
{
dtClone.ImportRow(dr);
}
}
gridView2.DataSource = dtClone;
gridView2.DataBind();
}
}
catch
{
BindGridView();
}
}
}
In this code when i check for example 2 choices from gridview 1 and click the button add to cart then these 2 choices are moving to the second gridview. As you see,I have a textbox for the quantity. I would like when i give the quantity to multiply it with the price.With the button 'find the total' i want to give me the result in the text box.How can i do that?
one simple solution may be useful to you.
protected void Button1_Click(object sender, EventArgs e)
{
int itemCount;
decimal itemPrice, itemTotal;
itemTotal = 0;
itemCount = 0;
itemPrice = 0;
foreach(GridViewRow gridView2Row in gridView2.Rows)
{
TextBox tbCount = gridView2Row.Cells[0].Controls[1] as TextBox;
itemCount = Convert.ToInt32(tbCount.Text);
itemPrice = Convert.ToDecimal(gridView2Row.Cells[3].Text);
itemTotal = itemTotal + (itemCount * itemPrice);
}
TextBox1.Text = itemTotal.ToString();
}