I'm trying to use SQLite in my application, and it's been bumpy. A few things, first off.
Due to having VS 2008 Express, SQLite design-time support is nonexistent. I've done some reading and i'm rather confused about how to use command-based sql connections with standard data controls, ie gridview. If the views ask for data sources, what data source do I choose to use my custom SQL statements with? And how do I choose it, given that I can't use the design time support?
Thank you,
Cameron
I've never used design support in Visual Studio and with SQLite I wonder if it is possible at all so I would suggest you to get into coding :-) Here's a sample illustrating the basic ideas. You start off by creating your database:
Global.asax:
public class Global : System.Web.HttpApplication
{
public string GetDbFile()
{
return Path.Combine(Server.MapPath("~/App_Data"), "data.db3");
}
public string GetConnectionString()
{
return "Data Source=" + GetDbFile() + ";Version=3;";
}
protected void Application_Start(object sender, EventArgs e)
{
var dbFile = GetDbFile();
if (File.Exists(dbFile))
{
File.Delete(dbFile);
}
ExecuteCommand("create table users (usr_id integer primary key, usr_name string)");
ExecuteCommand("insert into users (usr_id, usr_name) values (1, 'user 1')");
ExecuteCommand("insert into users (usr_id, usr_name) values (2, 'user 2')");
}
public void ExecuteCommand(string sql)
{
using (var connection = new SQLiteConnection(GetConnectionString()))
using (var command = connection.CreateCommand())
{
connection.Open();
command.CommandText = sql;
command.ExecuteNonQuery();
}
}
}
Of course you could skip this step if you already have an SQLite database file. You won't need to recreate it every time your application starts :-)
Once you have the database filled with data you could show it in a grid.
default.aspx:
<%# Page Language="C#" %>
<%# Import Namespace="System.Linq" %>
<%# Import Namespace="System.Collections.Generic" %>
<%# Import Namespace="System.Data.SQLite" %>
<script type="text/C#" runat="server">
private class User
{
public int Id { get; set; }
public string Name { get; set; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
usersGrid.DataSource = GetUsers();
usersGrid.DataBind();
}
}
private IEnumerable<User> GetUsers()
{
using (var connection = new SQLiteConnection(ApplicationInstance.GetConnectionString()))
using (var command = connection.CreateCommand())
{
connection.Open();
command.CommandText = "select usr_id, usr_name from users";
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
yield return new User { Id = reader.GetInt32(0), Name = reader.GetString(1) };
}
}
}
}
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="usersGrid" runat="server" />
</div>
</form>
</body>
</html>
Related
I am having a problem with my asp.net project setting up a connection to the ms sql server.
Here's my aspx code:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="OnlineAppSyss.aspx.cs" Inherits="SoftwareAnalysisAndDesign.SAD.OnlineAppSyss" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Online AppSyss System</title>
<meta charset="utf-8"/>
<link rel="stylesheet" href="css/style.css" />
<script src="js/index.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body bgcolor="#339966">
<div class="wrapper">
<div class="container">
<h1>Welcome to Online AppSess System</h1>
<form id="form1" runat="server">
<input type="text" id="Username" runat="server" placeholder="Username" />
<input type="text" id="Password" runat="server" placeholder="Password" />
<button type="submit" id="login-button" onserverclick="Button1_Click">Login</button>
</form>
</div>
</div>
<ul class="bg-bubbles">
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</body>
</html>
And my aspx code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Threading.Tasks;
namespace SoftwareAnalysisAndDesign.SAD
{
public partial class OnlineAppSyss : System.Web.UI.Page
{
public class MSConnector
{
public String ConnectionString { get; set; }
public DataSet ExecuteQuery(String sqlStatement)
{
try
{
DataSet results = new DataSet();
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
if (conn.State == System.Data.ConnectionState.Closed)
{
conn.Open();
}
using (SqlDataAdapter da = new SqlDataAdapter(sqlStatement, conn))
{
da.Fill(results);
}
if (conn.State == System.Data.ConnectionState.Open)
{
conn.Close();
}
}
return results;
}
catch (Exception ex)
{
throw ex;
}
}
}
public static string query = null;
private DataSet selectedData;
private DataTable dt;
private MSConnector connector = new MSConnector();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Login();
}
public void Login()
{
//ConnectionString for accessing into MSSql
connector.ConnectionString = "SERVER=KEITH;UID=KEITH/LaurenceKeith;Password=;DATABASE=Student;";
string username = (this.Username.Value);
string password = (this.Password.Value);
if (username == "" && password == "")
{
query = "select * from Student where StudentID = 2011017997'";
query = "select * from Student where Password = 'lalbano' '";
}
}
}
}
this is my code for setting up a connection using this class MSConnector
public class MSConnector
{
public String ConnectionString { get; set; }
public DataSet ExecuteQuery(String sqlStatement)
{
try
{
DataSet results = new DataSet();
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
if (conn.State == System.Data.ConnectionState.Closed)
{
conn.Open();
}
using (SqlDataAdapter da = new SqlDataAdapter(sqlStatement, conn))
{
da.Fill(results);
}
if (conn.State == System.Data.ConnectionState.Open)
{
conn.Close();
}
}
return results;
}
catch (Exception ex)
{
throw ex;
}
}
}
I can't retrieve my data in my database even though I have no error in my code behind.
Is there a problem with my connection string? I don't have a password in my ms sql server though. Is this the correct code of connection string? Please Help.
//ConnectionString for accessing into MSSql
connector.ConnectionString = "SERVER=KEITH;UID=KEITH/LaurenceKeith;Password=;DATABASE=Student;";
Try this as connection string, will use Windows Authentication for login.
connector.ConnectionString = "data source=KEITH;initial catalog=Student;Integrated Security=SSPI;providerName=System.Data.SqlClient";
This is assuming Keith is your SQL server and the database is Student
i followed the tutorial to from one of the online blog and am able get the application out with out error, but main issue is its not giving error as well as output.
My hub class looks like this
public void NotifyAllClients(string msg)
{
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<NotificationsHub>();
context.Clients.All.displayNotification(msg);
}
My ASPX.CS page looks like this
protected void Page_Load(object sender, EventArgs e)
{
SendNotifications();
}
public void SendNotifications()
{
string message = string.Empty;
string conStr = ConfigurationManager.ConnectionStrings["TestDB"].ConnectionString;
using (SqlConnection connection = new SqlConnection(conStr))
{
string query = "SELECT [Message] FROM [dbo].[MessageBuffer]";
using (SqlCommand command = new SqlCommand(query, connection))
{
command.Notification = null;
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
reader.Read();
message = reader[0].ToString();
}
}
}
NotificationsHub nHub = new NotificationsHub();
nHub.NotifyAllClients(message);
}
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
if (e.Type == SqlNotificationType.Change)
{
SendNotifications();
}
}
and My aspx page is --
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<script src="Scripts/jquery-1.8.2.min.js"></script>
<script src="Scripts/jquery.signalR-2.1.2.js"></script>
<script src="signalr/hubs"></script>
<script type="text/javascript">
$(function () {
var notify = $.connection.notificationsHub;
notify.client.displayNotification = function (msg) {
$('#newData').append('<li><strong>' + msg + '</li>');
};
$.connection.hub.start();
});
</script>
<div style="padding:10px 0px 10px 10px">
New Messages:
<ul id="newData"></ul>
</div>
</body>
</html>
i have done different samples, i have used same format to display, i am able to get those out in a hand, but here i am stuck with this. i am getting value in aspx.cs page, it calling the DB, which i have given in global.asax. and i have added sqldependency as well, enbabled broker in DB. but issue is still there. i cant see anything in UI.
Thanks in advance
I had a similar problem a while back. I just used the hub method name attribute and it worked for me. So you want something like
[HubMethodName("SendNotifications")]
public string SendNotifications()
And then at the front end just do
$.connection.hub.start(function () {
notify.server.SendNotifications();
});
Update
You could have a span the way I have in my code. so something like
<div>
<ul>
<li>New Messages:<span id="newData">0</span></a></li>
</ul>
</div>
Then do
$('#newData').text(msg);
I have a large pdf file (upto 2 GBs) on a database server which I want to send to client for download. Also, I have size limitations on my web server and cannot store complete file on it, after requesting from data server. I am using asp.net mvc 3. Any suggestions on how can I accomplish this? Also I want it to be asynchronous since I don't want to block the user from clicking other buttons on the web page.
I have tried using this code.
//code for getting data from data server into inputstream
HttpContext.Response.ContentType = "application/pdf";
HttpContext.Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
HttpContext.Response.BufferOutput = false;
try
{
using (Stream inputStream = resp.GetResponseStream())
{
byte[] buffer = new byte[SegmentSize];
int bytesRead;
while ((bytesRead = inputStream.Read(buffer, 0, SegmentSize)) > 0)
{
HttpContext.Response.OutputStream.Write(buffer, 0, bytesRead);
HttpContext.Response.Flush();
}
}
}
catch (Exception ex)
{
//some code
}
This downloads the file but then I don't know how to make it asynchronous? Also is there any other way to do the download that would be asynchronous too?
You can use AJAX which is Asynchronous. For that use a library like JqueryUI and a plugin, take a look a this example
http://www.plupload.com/example_custom.php
Im sure this will do! :D
Turns out in my final application I did not use web service but simple AJAX and ASPX pages this is how I got it done!
Default.ASPX file
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="CloudWF._Default"
Culture="auto" meta:resourcekey="PageResource1" UICulture="auto" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link type="text/css" href="css/redmond/jquery-ui-1.8.21.custom.css" rel="stylesheet" />
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="jsEng" runat="server">
<Scripts>
<asp:ScriptReference Path="~/js/jquery-1.7.2.min.js" />
<asp:ScriptReference Path="~/js/jquery-ui-1.8.21.custom.min.js" />
</Scripts>
</asp:ScriptManager>
<input type='submit' value='Process New Records' id='trigger' onclick='BeginProcess(); return false;' />
</div>
</form>
</body>
<script type="text/javascript">
var btnStart;
$(function () {
btnStart = $("#trigger").button();
imgLoad = $("#loader").hide();
});
function BeginProcess() {
btnStart.val("Collecting Data...");
//to get the value of the radiobuttons
//alert($('input[name=A]:checked').val()) --> [name=*] where *= whatever the name of the radioset
// Create an iframe.
var iframe = document.createElement("iframe");
// Point the iframe to the location of
// the long running process.
iframe.src = "process.aspx";
// Make the iframe invisible.
iframe.style.display = "none";
// Add the iframe to the DOM. The process
// will begin execution at this point.
document.body.appendChild(iframe);
btnStart.val("Processing...");
imgLoad.show();
btnStart.button("disable");
}
function UpdateProgress(RecordComplete, Message, step) {
btnStart.val("Downloaded Record " + RecordComplete + Message);
$("#progressbar").progressbar({
value: step
});
if (step >= 100) {
imgLoad.hide();
btnStart.val("Download Complete!");
}
}
</script>
Process.aspx.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
public partial class process : System.Web.UI.Page
{
WebClient wc = new WebClient();
Dictionary<string, string> AudioURLs = new Dictionary<string, string>();
protected void Page_Load(object sender, EventArgs e)
{
// Padding to circumvent IE's buffer*
Response.Write(new string('*', 256));
Response.Flush();
ProcessRecords();
}
public void ProcessRecords()
{
int recTotal;
recordList = (IQueryable<Record>)(Session["UNPROCESSED"]);
recTotal = recordList.Count();
if (recordList.Count() > 0)
{
foreach (Record record in recordList)
{
try
{
curRow++;
step = ((decimal)curRow / (decimal)recTotal) * 100;
CreateDictionary();
CreateFolderwithAudios(record.tSessionID);
//record.processed = true;
db.SubmitChanges();
UpdateProgress(curRow, " of " + recTotal, step);
}
catch (Exception x)
{
HttpContext.Current.Response.Write("Exception: " + x.Message);
}
}
Session["UNPROCESSED"] = null;
}
}
public Dictionary<string, string> CreateDictionary()
{
AudioURLs.Clear();
#region Add Values to Dictionary
return AudioURLs;
}
public void DownloadAudios(string _subFolder, Dictionary<string, string> _AudioSources)
{
foreach (KeyValuePair<string, string> kvp in _AudioSources)
{
if (kvp.Value.StartsWith("http://"))
{
try
{
wc.DownloadFile(kvp.Value, audiosPath + "\\" + _subFolder + "\\" + kvp.Key + ".wav");
}
catch (WebException webex)
{
throw new WebException(webex.Message);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
}
}
public void CreateFolderwithAudios(string folderName)
{
try
{
//create the folder where the audios are going to be saved
Directory.CreateDirectory(audiosPath + folderName);
//create and read the Dictionary that contains the URLs for the audio files
DownloadAudios(folderName, AudioURLs);
}
catch (AccessViolationException ae)
{
HttpContext.Current.Response.Write(ae.Message);
}
catch (System.Exception x)
{
HttpContext.Current.Response.Write(x.Message);
}
}
protected void UpdateProgress(int PercentComplete, string Message, decimal step)
{
// Write out the parent script callback.
Response.Write(String.Format(
"<script>parent.UpdateProgress({0}, '{1}',{2});</script>",
PercentComplete, Message, step));
// To be sure the response isn't buffered on the server.
Response.Flush();
}
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I'm an C# ASP.NET beginner, so please excuse anything that's... not quite right!
In short, I want to create a really basic login system: one which runs through a database and uses sessions so that only logged in users can access certain pages. I know how to do most of that, but I'm stuck with querying data with LINQ on the login page.
On the login page, I have a DropDownList to select a username, a Textbox to type in a password and a button to login (I also have a literal for errors). The DropDownList is databound to a datatable called DT_Test. DT_Test contains three columns: UsernameID (int), Username (nchar(30)) and Password (nchar(30)). UsernameID is the primary key.
I want to make the button's click event query data from the database with the DropDownList and Textbox, in order to check if the username and password match. But I don't know how to do this...
Current Code (not a lot!):
Front End:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Login_Test.aspx.cs" Inherits="Login_Login_Test" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Login Test</title>
</head>
<body>
<form id="LoginTest" runat="server">
<div>
<asp:DropDownList ID="DDL_Username" runat="server" Height="20px"
DataTextField="txt">
</asp:DropDownList>
<br />
<asp:TextBox ID="TB_Password" runat="server" TextMode="Password"></asp:TextBox>
<br />
<asp:Button ID="B_Login" runat="server" onclick="B_Login_Click" Text="Login" />
<br />
<asp:Literal ID="LI_Result" runat="server"></asp:Literal>
</div>
</form>
</body>
</html>
Back End:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Login_Login_Test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Binder();
}
}
private void Binder()
{
using (DataClassesDataContext db = new DataClassesDataContext())
{
DDL_Username.DataSource = from x in db.DT_Honeys select new { x.UsernameID, txt = x.Username };
DDL_Username.DataBind();
}
}
protected void B_Login_Click(object sender, EventArgs e)
{
if (TB_Password.Text != "")
{
using (DataClassesDataContext db = new DataClassesDataContext())
{
}
}
}
}
I have spent hours searching and trying different code, but none of it seems to fit in for this context.
Anyway, help and tips appreciated, thank you very much!
I am aware of security risks etc. but this is not a live website or anything, it is simply for testing purposes as a beginner. *
Updated code:
Back End:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Login_Page_Test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Tester();
}
}
private void Tester()
{
using (DataClassesDataContext db = new DataClassesDataContext())
{
DDL_Username.DataSource = from x in db.DT_Honeys select new { id = x.UsernameID, txt = x.Username };
DDL_Username.DataValueField = "id";
DDL_Username.DataTextField = "txt";
DDL_Username.DataBind();
}
}
protected void B_Login_Click(object sender, EventArgs e)
{
if (TB_Password.Text != "")
{
using (DataClassesDataContext db = new DataClassesDataContext())
{
DT_Honey blah = new DT_Honey();
blah = db.DT_Honeys.SingleOrDefault(x => x.UsernameID == int.Parse(DDL_Username.SelectedValue.ToString()));
if (blah != null)
{
if (TB_Password.Text.ToString().Trim() == blah.Password.ToString())
{
LI_Result.Text = "Credentials correct.";
}
else
{
LI_Result.Text = "Error: credentials are incorrect.";
}
}
else
{
LI_Result.Text = "Error: null value.";
}
}
}
}
}
Front End:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Login_Page_Test.aspx.cs" Inherits="Login_Page_Test" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Logi Page Test</title>
</head>
<body>
<form id="LoginPageTest" runat="server">
<div>
</div>
<asp:DropDownList ID="DDL_Username" runat="server">
</asp:DropDownList>
<br />
<asp:TextBox ID="TB_Password" runat="server"></asp:TextBox>
<br />
<asp:Button ID="B_Login" runat="server" onclick="B_Login_Click" Text="Login" />
<br />
<asp:Literal ID="LI_Result" runat="server"></asp:Literal>
</form>
</body>
</html>
I have checked the database aspects, and it is all fine in terms of primary key, columns, actual data, and dataclasses.
Same with textbox:
Back End:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Login_Login_Page_2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void B_Login_Click(object sender, EventArgs e)
{
if (TB_Username.Text.ToString().Trim() != "" && TB_Password.Text.ToString().Trim() != "")
{
using (DataClassesDataContext db = new DataClassesDataContext())
{
DT_Honey Login = new DT_Honey();
Login = db.DT_Honeys.SingleOrDefault(y => y.UsernameID == int.Parse(TB_Username.Text.ToString().Trim()));
if (Login != null)
{
if (TB_Password.Text.Trim() == Login.Password.ToString().Trim())
{
LI_Result.Text = "Yeah! The credentials you entered were correct!";
}
}
else
{
LI_Result.Text = "Oops! There was an error with the credentials you entered; please try again.";
}
}
}
else
{
LI_Result.Text = "Wow! Please fill out <b>both</b> the Username and Password text fields to login; thank you.";
}
}
}
Front End:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Login_Page_2.aspx.cs" Inherits="Login_Login_Page_2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Login Page 2</title>
</head>
<body>
<form id="LoginPage2" runat="server">
<div>
<asp:TextBox ID="TB_Username" runat="server"></asp:TextBox>
<br />
<asp:TextBox ID="TB_Password" runat="server"></asp:TextBox>
<br />
<asp:Button ID="B_Login" runat="server" onclick="B_Login_Click" Text="Login" />
<br />
<asp:Literal ID="LI_Result" runat="server"></asp:Literal>
</div>
</form>
</body>
</html>
Since you're a self-described beginner, I'd really recommend using the native asp.net login controls. It's very likely that your code is less secure than the login control that 100's of engineers have spent years working on. Is there really a compelling reason for you to build your own custom login?? To begin with, doing what you're doing relies on storing unencrypted passwords....
You're introducing potentially serious security vulnerabilities in your application by redoing the login control yourself!!
Maybe this will help you?:
protected void B_Login_Click(object sender, EventArgs e)
{
if (TB_Password.Text != "")
{
using (DataClassesDataContext db = new DataClassesDataContext())
{
var user = db.DT_Test.SingleOrDefault(x => x.Username == DDL_Username.SelectedText);
if (user == null)
{
// whoops something's wrong (no matching username in db)
}
if (user.Password == TB_Password.Text)
{
// do something (correct password)
}
else
{
// something else (incorrect password)
}
}
}
}
However, best practice would be to use a standard membership provider for ASP.NET. Then you don't have to be in the business of setting up your own membership schema in a database. (It looks as though you're storing passwords in clear text, but a membership provider will fix that and handle the details for you.)
MSDN Introduction to Membership
Edit You'll probably want to change the Binder code so that your drop down items' IDs match up with the database ID numbers:
private void Binder()
{
using (DataClassesDataContext db = new DataClassesDataContext())
{
DDL_Username.DataSource = from x in db.DT_Honeys select new { id = x.UsernameID, txt = x.Username };
DDL_Username.DataValueField = "id";
DDL_Username.DataTextField = "txt";
DDL_Username.DataBind();
}
}
I am trying to do the following
I have a dynamic table in my asp page
and I want to show the table in multi pages like google results
any useful suggestion please
note:
I don't to use gridview
so any another way ??
If you want more flexibility in the output than GridView provides, take a look at Repeater.
Since the Repeater doesn't directly implement paging, you'll have to supply your own Next and Previous buttons. As noted by Sundararajan S if you have many records you'll want to use the current page number and page size to return only the current page's records to the browser rather than all of them.
Below is an example (I didn't know what your data source would be like, so I just used a list as an example. Substitute with something more appropriate.)
Hope that helps.
Default.aspx:
<asp:Button ID="PrevPageButton" runat="server" Text="Prev"
onclick="PrevPageButton_Click" />
<asp:Label ID="CurrentPageLabel" runat="server" />
<asp:Button ID="NextPageButton" runat="server" Text="Next"
onclick="NextPageButton_Click" />
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<h2> <%# Eval("Name") %> </h2>
<p>
<%# Eval("Description") %>
</p>
</ItemTemplate>
</asp:Repeater>
Default.aspx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace RepeaterPaging
{
public partial class _Default : System.Web.UI.Page
{
private const int PageSize = 10;
private const int MaxPage = 4;
public int CurrPage
{
get
{
if (this.ViewState["CurrPage"] == null )
this.ViewState["CurrPage"] = 0;
return (int) this.ViewState["CurrPage"];
}
set { this.ViewState["CurrPage"] = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindItems();
}
}
protected void BindItems()
{
int currPage = CurrPage;
List<Book> books = new List<Book>();
int startItem = (currPage * PageSize) + 1;
for (int i = startItem; i < startItem+PageSize; i++)
{
books.Add(new Book("Title " + i, "Description " + i + " ..................."));
}
Repeater1.DataSource = books;
Repeater1.DataBind();
CurrentPageLabel.Text =
string.Format(" Page {0} of {1} ", CurrPage + 1, MaxPage + 1);
}
protected void NextPageButton_Click(object sender, EventArgs e)
{
if (CurrPage < MaxPage)
{
CurrPage++;
BindItems();
}
}
protected void PrevPageButton_Click(object sender, EventArgs e)
{
if (CurrPage > 0)
{
CurrPage--;
BindItems();
}
}
}
public class Book
{
public string Name { get; set; }
public string Description { get; set; }
public Book(string name, string desc)
{
Name = name;
Description = desc;
}
}
}
You can use the jquery tablesorter plugin and the jquery.tablesorter.pager plugin to accomplish this. It will work on a standard html table, and has a lot of options such as alternate row hilighting, sorting, etc.
It depends on how many records at max will be returned. The most efficient way would be
Implement Pagination numbers as links which differ in query parameter.
Based on the query parameter, in the server side, fetch the records corresponding to that page alone. eg. if your page size is 10 and the current page is 2 , fetch only 11,20 records from the server and bind it to html table.
If you are using LINQ to SQL , use Take and SKIP methods as in http://blog.ofiryaron.com/blog/post/Pagination-on-Linq-to-SQL-childs-play!.aspx
If you are using direct SQL queries or Stored procs , make use of RowID to fetch that pages records.