|
|
|
สอบถามการ paging Gridview Asp.net รบกวนผู้รู้ช่วยแนะนำด้วยครับ |
|
|
|
|
|
|
|
ผมต้องการทำ paging gridview ตังต่อไปนี้นะครับ
ตอนโหลดข้อมูลตอนแรกไม่มีปัญหาครับ ทำการแบ้งหน้าได้ครับ
>>>> ปัญหามันอยู่ที่ตอนที่ค้นหาข้อมูลตามเงื่อนไขในช่วงเวลาที่ต้องการคือเมื่อคลิกหน้าที่สองข้อมูลไม่เปลี่ยน
การคลิกครั้งแรก ดังภาพประกอบที่ 1 นะครับข้อมูล
พอคลิกครั้งที่สอบที่หน้าสอง ปรากฎว่าหลือข้อมูลแค่แถวเดียวครับ
โค๊ดที่เขียน
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
// currentIndex_ =+ GridView1.PageIndex;
if (IsPostBack)
{
if (Session["ds"] != null && Session["de"] != null)
{
dateStart_ = Session["dateStart"].ToString();
dateEnd_ = Session["dateEnd"].ToString();
loadDataforGV_C_p_(dateStart_, dateEnd_);
}
}
}
private void loadDataforGV_C_p_(string dateStart_, string dateEnd)
{
DateTime dateStartNew_ ,dateEndNew_;
dateStartNew_ = Convert.ToDateTime(dateStart_);
dateEndNew_ = Convert.ToDateTime(dateStart_);
var qr = (from tra in db.Transactions
where tra.Deposit_account.M_id == userID_
&& tra.Tras_date >= dateStartNew_
&& tra.Tras_date <= dateEndNew_
select new
{
tra.Tras_id,
tra.Amount,
tra.Balance,
tra.Tras_date,
tra.Acc_id,
tra.Act_id,
tra.Actioncode.Act_code,
nameManager = tra.Member.M_name,
lastNameManager = tra.Member.M_lastname,
M_id = tra.Deposit_account.M_id,
M_name = tra.Deposit_account.Member.M_name,
M_lastname = tra.Deposit_account.Member.M_lastname
});
if (qr.Count() > 0)
{
GridView1.DataSourceID = null;
GridView1.DataSource = null;
qr.Skip(GridView1.PageIndex).Take(GridView1.PageSize);
GridView1.DataSource = qr;
GridView1.DataBind();
Panel1.Visible = true;
loadSum_();
return;
}
else
{
GridView1.DataSourceID = null;
GridView1.DataSource = null;
Panel1.Visible = false;
ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", nodata, true);
}
}
รบกวนช่วยแนะนำทีครับ มีตัวอย่างด้วยยิ่งดีครับ ขอบคุณครับ
Tag : .NET, Web (ASP.NET), LINQ, VS 2012 (.NET 4.x), Windows
|
ประวัติการแก้ไข 2014-10-12 22:36:56
|
|
|
|
|
Date :
2014-10-12 22:34:52 |
By :
ธนวัต |
View :
1790 |
Reply :
2 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Default.aspx
<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="StaffDirectory_Default" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
<script type="text/javascript">
function autocomplete_Populated(sender, e) {
if (sender._currentPrefix != null) {
var list = sender.get_completionList();
var search = sender._currentPrefix.replace(" ", "").toLowerCase();
for (var i = 0; i < list.childNodes.length; i++) {
var text = list.childNodes[i].innerHTML;
var index = text.toLowerCase().indexOf(search);
if (index != -1) {
var value = text.substring(0, index);
value += '<span style="color: black;">';
value += text.substr(index, search.length);
value += '</span>';
value += text.substring(index + search.length);
list.childNodes[i].innerHTML = value;
}
}
}
}
function autocomplete_Selected(sender, e) {
var SelectedText;
// Check for IE - should really check for the availabbility of the property... if(e._item.innerText)
if (document.all)
SelectedText = e._item.innerText;
else
SelectedText = e._item.textContent;
// Set the value of the textbox
sender.get_element().value = SelectedText;
// Get the value selected
SelectedValue = e.get_value();
}
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<div class="Staff">
<h1>ระบบค้นหาบุคคลากร</h1><br />
<asp:TextBox ID="TextBoxStaff" Width="400px" runat="server" autocomplete="off"></asp:TextBox>
<ajaxToolkit:AutoCompleteExtender ID="TextBoxStaff_AutoCompleteExtender" BehaviorID="AutoCompleteEx" runat="server"
TargetControlID="TextBoxStaff"
ServicePath="~/AutoComplete.asmx"
ServiceMethod="GetStaffList"
CompletionInterval="100"
CompletionSetCount="12"
DelimiterCharacters=""
Enabled="true"
EnableCaching="true"
MinimumPrefixLength="1"
CompletionListCssClass="autocomplete_completionListElement"
CompletionListItemCssClass="autocomplete_listItem"
CompletionListHighlightedItemCssClass="autocomplete_highlightedListItem"
OnClientPopulated="autocomplete_Populated"
OnClientItemSelected="autocomplete_Selected"
ShowOnlyCurrentWordInCompletionListItem="true">
</ajaxToolkit:AutoCompleteExtender>
<asp:Button ID="ButtonSearch" runat="server" ValidationGroup="staff" Text="ค้นหา" OnClick="ButtonSearch_Click" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" ControlToValidate="TextBoxStaff" CssClass="failureNotification" runat="server" ErrorMessage="*" ValidationGroup="staff"></asp:RequiredFieldValidator>
<asp:UpdateProgress ID="UpdateProgress1" DynamicLayout="false" runat="server">
<ProgressTemplate>
<asp:Image ID="Image1" ImageUrl="~/images/loading.gif" runat="server" />
</ProgressTemplate>
</asp:UpdateProgress>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="ButtonSearch" EventName="Click" />
</Triggers>
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" PageSize="25"
OnRowDataBound="GridView1_RowDataBound" OnPageIndexChanging="GridView1_PageIndexChanging" OnRowCommand="GridView1_RowCommand">
<Columns>
<asp:TemplateField HeaderText=" ">
<EditItemTemplate>
<asp:TextBox ID="TextBoxUserID" runat="server"></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:ImageButton ID="ImageButtonDetail" runat="server" CausesValidation="false" ToolTip="แสดงรายละเอียด"
ImageUrl="~/images/details.png" CommandName="ShowDetail" CommandArgument='<%# Bind("StaffID") %>' />
</ItemTemplate>
<HeaderStyle Width="3%" />
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:TemplateField>
<asp:BoundField HeaderText="#">
<HeaderStyle HorizontalAlign="Center" Width="3%" />
<ItemStyle HorizontalAlign="Right" VerticalAlign="Middle" />
</asp:BoundField>
<asp:BoundField HeaderText="ชื่อ" DataField="StaffName">
<HeaderStyle HorizontalAlign="Center" Width="25%" />
<ItemStyle HorizontalAlign="Left" VerticalAlign="Middle" />
</asp:BoundField>
<asp:BoundField HeaderText="ตำแหน่ง" DataField="PositionName">
<HeaderStyle HorizontalAlign="Center" Width="29%" />
<ItemStyle HorizontalAlign="Left" VerticalAlign="Middle" />
</asp:BoundField>
<asp:BoundField HeaderText="หน่วยงาน" DataField="SectionName">
<HeaderStyle HorizontalAlign="Center" Width="30%" />
<ItemStyle HorizontalAlign="Left" VerticalAlign="Middle" />
</asp:BoundField>
<asp:BoundField HeaderText="โทรศัพท์" DataField="IpPhone">
<HeaderStyle HorizontalAlign="Center" Width="10%" />
<ItemStyle HorizontalAlign="Right" VerticalAlign="Middle" />
</asp:BoundField>
</Columns>
</asp:GridView>
<asp:Button ID="ButtonHidden" runat="server" Text="Button" style="display: none;" />
<ajaxToolkit:ModalPopupExtender runat="server" ID="ModalPopupExtender1"
TargetControlID="ButtonHidden" PopupControlID="PanelPopup" CancelControlID="ImageButtonClose"
BackgroundCssClass="modalBackground" DropShadow="True"
RepositionMode="RepositionOnWindowScroll">
</ajaxToolkit:ModalPopupExtender>
<asp:Panel ID="PanelPopup" CssClass="modalPopup" style="display: none; padding: 0px;" runat="server">
<asp:Panel ID="PanelClose" CssClass="close" runat="server">
<asp:ImageButton ID="ImageButtonClose" ImageUrl="~/images/close.png" ToolTip="Close" runat="server" />
</asp:Panel>
<asp:Panel ID="PanelFrame" CssClass="Frame" runat="server">
<asp:Panel ID="PanelDetail" CssClass="Detail" runat="server">
<fieldset class="dataDetail">
<legend>ข้อมูลเจ้าหน้าที่:</legend>
<table class="tableDetail">
<tr>
<td style="width: 20%;">ชื่อ:</td>
<td style="width: 60%;">
<asp:Label ID="LabelName" runat="server" Font-Bold="true" Text="Label"></asp:Label>
</td>
<td style="width: 20%; text-align: right; vertical-align: top;" rowspan="3">
<asp:Image ID="ImageAvatar" Width="100" Height="125" BorderWidth="1px" BorderStyle="Solid" BorderColor="#cccccc" runat="server" ImageUrl="~/images/male-icon-120x150.jpg" />
</td>
</tr>
<tr>
<td>ตำแหน่ง:</td>
<td>
<asp:Label ID="LabelPosition" runat="server" Text="Label"></asp:Label>
</td>
</tr>
<tr>
<td style="vertical-align: top;">สังกัด:</td>
<td>
<asp:BulletedList ID="BulletedListSection" CssClass="Section" runat="server">
</asp:BulletedList>
</td>
</tr>
<tr>
<td>ผู้บังคับบัญชา:</td>
<td colspan="2">
<asp:Label ID="LabelBoss" runat="server" Text="Label"></asp:Label>
</td>
</tr>
<tr>
<td style="vertical-align: top;">สถานที่ทำงาน:</td>
<td colspan="2">
<asp:Label ID="LabelAddress" runat="server" style="line-height: 24px;" Text="Label"></asp:Label>
</td>
</tr>
<tr>
<td>จังหวัด:</td>
<td colspan="2">
<asp:Label ID="LabelProvince" runat="server" Text="Label"></asp:Label>
</td>
</tr>
<tr>
<td style="vertical-align: top;">โทรศัพท์:</td>
<td colspan="2">
<asp:Label ID="LabelPhone" runat="server" Text="Label"></asp:Label>
</td>
</tr>
<tr>
<td style="vertical-align: top;">โทรศัพท์เคลื่อนที่:</td>
<td colspan="2">
<asp:Label ID="LabelMobile" runat="server" Text="Label"></asp:Label>
</td>
</tr>
<tr>
<td style="vertical-align: top;">โทรสาร:</td>
<td colspan="2">
<asp:Label ID="LabelFax" runat="server" Text="Label"></asp:Label>
</td>
</tr>
<tr>
<td style="vertical-align: top;">อีเมล:</td>
<td colspan="2">
<asp:Label ID="LabelEmail" runat="server" Text="Label"></asp:Label>
</td>
</tr>
</table>
</fieldset>
</asp:Panel>
</asp:Panel>
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</asp:Content>
Default.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 StaffDirectory_Default : System.Web.UI.Page
{
protected void Page_PreInit(object sender, EventArgs e)
{
if (Request.Cookies["userSetting"] == null)
this.Page.Theme = "Default";
else
this.Page.Theme = Request.Cookies["userSetting"]["Theme"].ToString();
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GridView1.DataSource = new DataTable();
GridView1.DataBind();
}
}
protected void ButtonSearch_Click(object sender, EventArgs e)
{
GridView1.DataSource = GetStaff(TextBoxStaff.Text.Replace("[", string.Empty).Replace("]", string.Empty).Replace("#", string.Empty));
GridView1.DataBind();
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
GridView gv = (GridView)sender;
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[2].ToolTip = e.Row.Cells[2].Text;
e.Row.Cells[3].ToolTip = e.Row.Cells[3].Text;
e.Row.Cells[4].ToolTip = e.Row.Cells[4].Text;
e.Row.Cells[5].ToolTip = e.Row.Cells[5].Text;
e.Row.Cells[1].Text = string.Format("{0}.", ((e.Row.RowIndex + 1) + (gv.PageIndex * gv.PageSize)).ToString());
e.Row.Cells[2].Text = (e.Row.Cells[2].Text.Trim().Length > 25) ? string.Format("{0}...", e.Row.Cells[2].Text.Substring(0, 25)) : e.Row.Cells[2].Text;
e.Row.Cells[3].Text = (e.Row.Cells[3].Text.Trim().Length > 25) ? string.Format("{0}...", e.Row.Cells[3].Text.Substring(0, 25)) : e.Row.Cells[3].Text;
e.Row.Cells[4].Text = (e.Row.Cells[4].Text.Trim().Length > 25) ? string.Format("{0}...", e.Row.Cells[4].Text.Substring(0, 25)) : e.Row.Cells[4].Text;
e.Row.Cells[5].Text = (e.Row.Cells[5].Text.Trim().Length > 6) ? string.Format("{0}...", e.Row.Cells[5].Text.Substring(0, 6)) : e.Row.Cells[5].Text;
}
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.DataSource = GetStaff(TextBoxStaff.Text.Replace("[", string.Empty).Replace("]", string.Empty).Replace("#", string.Empty));
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataBind();
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "ShowDetail")
{
DataRow Staff = GetStaffDetail(Convert.ToInt32(e.CommandArgument)).Rows[0];
ImageAvatar.ImageUrl = (!string.IsNullOrEmpty(Staff["ImagePath"].ToString())) ? Staff["ImagePath"].ToString() : ImageDefault(Convert.ToInt32(Staff["PrefixID"]));
LabelName.Text = Staff["StaffName"].ToString();
LabelPosition.Text = Staff["PositionName"].ToString();
BulletedListSection.DataSource = GetSection(Staff["SectionName"].ToString(), Staff["ParentCode"].ToString());
BulletedListSection.DataBind();
LabelBoss.Text = (!string.IsNullOrEmpty(Staff["BossID"].ToString())) ? GetBossName(Convert.ToInt32(Staff["BossID"])) : "-";
LabelAddress.Text = (!string.IsNullOrEmpty(Staff["Address"].ToString())) ? Staff["Address"].ToString() : "-";
LabelProvince.Text = (!string.IsNullOrEmpty(Staff["Province"].ToString())) ? Staff["Province"].ToString() : "-";
LabelPhone.Text = (!string.IsNullOrEmpty(Staff["IpPhone"].ToString())) ? Staff["IpPhone"].ToString() : "-";
LabelMobile.Text = (!string.IsNullOrEmpty(Staff["Mobile"].ToString())) ? Staff["Mobile"].ToString() : "-";
LabelFax.Text = (!string.IsNullOrEmpty(Staff["Fax"].ToString())) ? Staff["Fax"].ToString() : "-";
LabelEmail.Text = (!string.IsNullOrEmpty(Staff["Email"].ToString())) ? Staff["Email"].ToString() : "-";
ModalPopupExtender1.Show();
}
}
protected DataTable GetStaffDetail(int StaffID)
{
Intranet2012DataContext intranet2012 = new Intranet2012DataContext();
var staff = from s in intranet2012.Staff
join pf in intranet2012.Prefix on s.PrefixID equals pf.ID
join p in intranet2012.Position on s.PositionID equals p.ID
join c in intranet2012.CommandLine on s.CommandCode equals c.CommandCode
join st in intranet2012.Section on s.SectionCode equals st.SectionCode
join pv in intranet2012.Province on s.ProvinceID equals pv.ID into pvLeftJoin
from pv in pvLeftJoin.DefaultIfEmpty()
where s.ID == StaffID
select new
{
ImagePath = s.ImagePath,
PrefixID = s.PrefixID,
StaffName = string.Format("{0} {1} {2}", pf.PrefixName, s.Name, s.LastName),
Address = s.Address,
Province = pv.ProvinceName,
PositionName = p.PositionName,
BossID = c.StaffID,
SectionName = st.SectionName,
ParentCode = st.ParentCode,
IpPhone = GetIpPhone(s.ID, 1),
Mobile = GetIpPhone(s.ID, 2),
Fax = GetIpPhone(s.ID, 3),
Email = s.Email
};
return Intranet2012Datebase.LINQToDataTable(staff);
}
protected string GetBossName(int BossID)
{
Intranet2012DataContext intranet2012 = new Intranet2012DataContext();
string boss = (from s in intranet2012.Staff
join pf in intranet2012.Prefix on s.PrefixID equals pf.ID
join p in intranet2012.Position on s.PositionID equals p.ID
where s.ID == BossID
orderby s.Name
select new
{
BossName = string.Format("{0} {1} {2} [{3}]", pf.PrefixName, s.Name, s.LastName, p.PositionName)
}).Select(b => b.BossName).First();
return boss;
}
protected string[] GetSection(string SectionName, string ParentCode)
{
Intranet2012DataContext intranet2012 = new Intranet2012DataContext();
List<string> section = new List<string>();
string parentCode = ParentCode;
if (SectionName != "ไม่ระบุ") section.Add(SectionName);
while (Convert.ToInt32(parentCode) > 0)
{
TableSection aSection = (from s in intranet2012.Section
where s.SectionCode == parentCode
select s).First();
if (aSection.SectionName != "ไม่ระบุ") section.Add(aSection.SectionName);
parentCode = aSection.ParentCode;
}
return section.ToArray();
}
protected DataTable GetStaff(string prefixText)
{
Intranet2012DataContext intranet2012 = new Intranet2012DataContext();
string keyWord = prefixText.Trim().Replace(" ", string.Empty);
var staff = from s in intranet2012.Staff
join p in intranet2012.Position on s.PositionID equals p.ID
join ss in (from sss in intranet2012.Section where sss.SectionCode.EndsWith("00") select sss) on s.SectionCode.Substring(0, s.SectionCode.Length - 2) equals ss.SectionCode.Substring(0, ss.SectionCode.Length - 2)
join pv in intranet2012.Province on s.ProvinceID equals pv.ID into pvLeftJoin
from pv in pvLeftJoin.DefaultIfEmpty()
where s.Status == true && ((s.Name.Trim().Replace(" ", string.Empty) + s.LastName.Trim().Replace(" ", string.Empty)).StartsWith(keyWord) ||
s.LastName.Trim().Replace(" ", string.Empty).StartsWith(keyWord) ||
ss.SectionName.Trim().StartsWith(keyWord) || ss.SectionShortName.Trim().StartsWith(keyWord) || s.Email.Trim().StartsWith(keyWord) ||
p.PositionName.Trim().StartsWith(keyWord) || pv.ProvinceName.Trim().StartsWith(keyWord)) ||
(from pt in intranet2012.Phone where pt.StaffID == s.ID && pt.TypeID == 1 && pt.Number.Trim().StartsWith(keyWord) select pt).Count() > 0 ||
(from pt in intranet2012.Phone where pt.StaffID == s.ID && pt.TypeID == 2 && pt.Number.Trim().StartsWith(keyWord) select pt).Count() > 0 ||
(from pt in intranet2012.Phone where pt.StaffID == s.ID && pt.TypeID == 3 && pt.Number.Trim().StartsWith(keyWord) select pt).Count() > 0
orderby ss.SectionCode, s.Name ascending
select new
{
StaffID = s.ID,
StaffName = string.Format("{0} {1}", s.Name.Trim(), s.LastName.Trim()),
PositionName = p.PositionName,
SectionName = ss.SectionName,
IpPhone = GetIpPhone(s.ID, 1)
};
return Intranet2012Datebase.LINQToDataTable(staff);
}
protected string GetIpPhone(int StaffID, int TypeID)
{
Intranet2012DataContext intranet2012 = new Intranet2012DataContext();
string number = string.Empty;
(from p in intranet2012.Phone
where p.TypeID == TypeID && p.StaffID == StaffID
select p).ToList().ForEach(p => number += string.Format("{0}, ", NumberFormat(p.Number)));
return (number.Length > 0) ? number.Substring(0, number.Length - 2) : number;
}
protected string NumberFormat(string Number)
{
string result = string.Empty;
if (Number.Substring(0, 2) == "02")
{
result = string.Format("{0} {1} {2}", Number.Substring(0, 1), Number.Substring(1, 4), Number.Substring(5));
}
else if (Number.Substring(0, 2) == "08")
{
result = string.Format("{0} {1} {2}", Number.Substring(0, 2), Number.Substring(2, 4), Number.Substring(6));
}
else
{
result = Number;
}
return result;
}
protected string ImageDefault(int PrefixID)
{
string imageDefalut;
switch (PrefixID)
{
case 2:
case 3:
case 8:
imageDefalut = "~/images/female-icon-120x150.jpg";
break;
default:
imageDefalut = "~/images/male-icon-120x150.jpg";
break;
}
return imageDefalut;
}
}
|
|
|
|
|
Date :
2014-10-13 08:05:18 |
By :
ห้ามตอบเกินวันละ 2 กระทู้ |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
ขอบคุณครับ สำหรับคำตอบแต่ยังทำไม่ได้ครับท่านใดมีวิธีอื่นมาชี้แนะรบกวนหน่อยครับ
|
|
|
|
|
Date :
2014-10-13 16:18:12 |
By :
ธนวัต |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Load balance : Server 04
|