Thursday, April 19, 2012

C# Linq to Sql Simple MVC Gridview - Complete paging solution

LINQ TO SQL ASP.NET MVC - Simple paged Gridview

Every application that works with any kind of data requires paging. In C# WebForms and WinForms you can use Gridviews, Pagers and so on but sometimes project requires different design where you can't use these or when you are working with ASP.NET MVC.

So lets say you have SQL database with 1000 rows and now you need to diplay it in you custom made gridView, html table, divs..etc but you also need way to show more pages to users.

Assuming you are already know Linq To Sql and ASP.NET MVC,
Here is method for grabbing products from database using Linq To Sql:

public static PaginatedList<Product> GetProducts(int page, int pageSize)
{
using (ProductDataContext context = new ProductDataContext())
{
var query = from p in context.Products select p;

var paginatedProducts = new PaginatedList<Product>(query, page, pageSize);

return paginatedProducts;
}
}

Here is my custom class that extends generic List called PaginatedList, this class can be used with any database data retrival techique:

public class PaginatedList : List
{
public int PageIndex { get; private set; }
public int PageSize { get; private set; }
public int TotalCount { get; private set; }
public int TotalPages { get; private set; }
public List<int> PreviousPages { get; private set; }
public List<int> NextPages { get; private set; }

public PaginatedList(IQueryable source, int pageIndex, int pageSize)
{
PageIndex = pageIndex;
PageSize = pageSize;
TotalCount = source.Count();
TotalPages = (int)Math.Ceiling(TotalCount / (double)PageSize);
this.AddRange(source.Skip((pageIndex - 1) * PageSize).Take(PageSize));

PreviousPages = new List<int>();
NextPages = new List<int>();

for (int i = 6; i >= 1; i--)
{
if ((pageIndex - i) >= 1)
PreviousPages.Add(pageIndex - i);
}

for (int i = 1; i < 6 && (i + pageIndex) <= TotalPages; i++)
{
NextPages.Add(pageIndex + i);
}
}

public bool HasPreviousPage
{
get
{
return (PageIndex > 1);
}
}

public bool HasNextPage
{
get
{
return (PageIndex + 1 <= TotalPages);
}
}
}

Custom GridView in ASP.NET C# MVC Usage Example:


Controller

public ActionResult Index(int page = 1, int size = 100)
{
var products = ProductsManipulation.Products(page, size);

return View(products);
}
View

@model PaginatedList<Product>
@{
ViewBag.Title = "Index";
}

<table style="border:1px solid Gray; width:100%;">
<tr>
<td>Product Nametd>

<td>Product Pricetd>
tr>
@foreach (var product in Model)
{
<tr>
<td>@product.Nametd>
<td>@product.Pricetd>
tr>
}
table>

<div>
@if (Model.HasPreviousPage)
{
<a href="?page=@(Model.PageIndex-1)">Previousa>
}

@foreach (var pageNum in Model.PreviousPages)
{
<a href="?page=@(pageNum)">@pageNuma>
}

<span>@Model.PageIndexspan>

@foreach (var pageNum in Model.NextPages)
{
<a href="?page=@(pageNum)">@pageNuma>
}

@if (Model.HasNextPage)
{
<a href="?page=@(Model.PageIndex + 1)">Nexta>
}
div>

I will be adding more examples using T-SQL, EF and WebForms examples.



Tuesday, July 6, 2010

Programming Introduction lesson 2 - Other Variables

NOTE 1 : Instead od default text on button,you can replace it with "Convert Celsius.." by selecting button1 an going to properties on right and changing Text field of button.
NOTE 2 : You can add labels just for nicer design like I did and change their default text the same way as on button.
NOTE 3 : You can make textBox2 Read-only because we will only need it for output,and we want to pervent users for writing in it.
NOTE 4 : You can change Title by selecting Form(clicking somewhere in form) and going to properties and changing Text Field


In this example Programming Introduction Lesson I will show you how and why can you convert variables of type string,integer and decimal.This simple program converts temperature from Celsius to Fahrenheit.

So we have usual code that IDE generates:


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Programming_Introduction_Lesson_2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
/* here goes code
* you will
* writte */
}
}


So we enter designer,and create new button, button1 and 2 Text Boxes,textBox1 and textBox2.
Double click button like in first lesson and designer should create new event for you automatically and take you to code.

So in above example instead of /* here goes code.. you should now have

private void button1_Click(object sender, EventArgs e)
{

}


This part defines what will happen when user press button.
So we define new Integer ( round number),we assume that user will write value in Celsius as Round number,not decimal.So when if we stated int celsius; we would only define it,now we want to put some value (=) in our variable celsius.We want to put value of textBox1 into celsius but we can't do it directly so we need to convert text to round number,and we write

Convert.ToInt32(textBox1.Text); After that we define decimal result; we have to define as decimal because result in fahrenheit is often decimal number,we don't write any value to it because we didnt convert it yet so we just define it for now and later we will assign value to it.

private void button1_Click(object sender, EventArgs e)
{
int celsius = Convert.ToInt32(textBox1.Text);
decimal result;
}

Mathematical formula for Converting celsius to fahrenheit is ((C x 9) /5)+32 = F so we want to simulate exactly that in our program and we write that same formula only C from above is celsius in our program,we need to convert all numbers to decimal,if we don't result will lack decimal places.When result is calculated we want to show user what is result so we need to convert decimal result to string and display it in textBox2.So we write: textBox2.Text = (result).ToString(); Remember to Always put .ToString(); when you are trying to display non string value in label or text box!

private void button1_Click(object sender, EventArgs e)
{
int celsius = Convert.ToInt32(textBox1.Text);
decimal result;

result = ((Convert.ToDecimal(celsius) * Convert.ToDecimal(9)) /
Convert.ToDecimal(5) + Convert.ToDecimal(32));

textBox2.Text = (result).ToString();

}

Upper code is heart of our simple program,Full code is posted below:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Programming_Introduction_Lesson_2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
int celsius = Convert.ToInt32(textBox1.Text);
decimal result;

result = ((Convert.ToDecimal(celsius) * Convert.ToDecimal(9)) /
Convert.ToDecimal(5) + Convert.ToDecimal(32));
textBox2.Text = (result).ToString();

}
}
}

Programming Introduction - Note

In one of previous posts I said that I will be using SharpDevlop 4.0,because SharpDevelop 2,3 were fantastic.On outside SD looks good like it was but when you start to write programs you can notice that it cotains so much bugs that so you can't really use it,I was working recently on bigger program just to see how SD will handle it and discovered numerus bugs,the worst ones were: SD report error message and If you proceed working in it,nothing what you write gets saved,and save button is disabled(I reported this bug but I can't see that someone tryed to change it..So my advice is if SD fails do not proceed just close it and restart),SD not reading saved solutions,you have to open it manually,partial clasess don't get compiled so SD reports bugs in your code.. and so on,after I gived up on writing something serious in SD In widows application templates,I was curious that maybe and just maybe SD team gived advantage to WPF applications and cuted down bug number because that is new future technology of C#.After opening new solution and working 5 minutes It failed couple of times,so I decided to install Visual Studio 2010 Ultimate,works like charm.So from now on I will be using VS 2010 Ultimate,don't worry code is the same,but In VS you can be sure that error is in your code,not in IDEs code...


I don't want to insult anyone but SD 4.0 should be marked as Pre-alpha!
I fully understand that Microsoft is releasing new technology too fast for One open-source project to follow,and just when they clean SD of bugs new version on framework is released so they have to start all over agian.I also noticed that they made changes to SD UI,time they used for altering UI could be use better used for bug fixing.

Tuesday, June 22, 2010

Programming Introduction lesson 1 - Your First program in C#

My First Program In C#


This is code automaticly created by IDE,that saves us lot of time because with can start writing our code right away!
/*
* Created by SharpDevelop.
* User: User
* Date: 30.6.2010
* Time: 6:57
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;

namespace My_First_program_in_C_
{
/// <summary>
/// Description of MainForm.
/// </summary>
public partial class MainForm : Form
{
public MainForm()
{
//
// The InitializeComponent() call is required for Windows Forms designer support.
//
InitializeComponent();

//
// TODO: Add constructor code after the InitializeComponent() call.
//
}
}
}
Variables - Programming Introduction

In programming variables are empty space in our program that we reserve so something can be writen in them and changed when you like.So how can you get your program to remember something?Use variables to store whatever was your or users input and when it's stored you can do with them what ever you want,read them,change them...etc.

So we had for exemple String,strings are variables in which text can be writen.There are two main types of variables in C# string and int,int marks Integer so they are variables in which numbers can be writen.

So for exemple in our first program we had :

string Name = textBox1.Text;So we declared string called Name,and we wanted that when user input their name in our textbox object we store that information for later use in program.So we put textBox1 to declare to compiler from which of our object we would like to use text,when you press dot SharpDevelop will offer you many functions and parametars,parametars can be changed dinamically,like for example color of our textbox,width,height etc.So we want to read text that user put in our textBox1 when he presses button which tells to us he is over writting.Cleaner code lines would be:

string Name;
string
Name = textBox1.Text;

So when we declare the string,it's empty after that we write whatever we want to it,in this case textBox1.Text.

So when we store variable that declares user's name we want to use it to display it somwhow in our program:

MessageBox.Show("Hello " + Name + ",welcome to first lesson of Programming Introduction examples." +
"Powerd By programmingintroduction.blogspot.com",
"Example messagebox Title",MessageBoxButtons.OK,MessageBoxIcon.Asterisk);


Syntax code for function MessageBox.Show is MessageBox.Show(Message you want to display in body of messageBox,Title of the MessageBox,Buttons we want to have on out messageBox,Icon in the MessageBox).

When we want to tell our IDE we want to display our own text that is static,we use quoutes(""),So that compiler would know we would like to display it as is.We use quotes so Compiler would know when we would like to display static text,and we don't use it when we want to display contents of string,so if I write :

MessageBox.Show("Hello " + "Name" + ",welcome to first lesson of Programming Introduction examples." +
"Powerd By programmingintroduction.blogspot.com",
"Example messagebox Title",MessageBoxButtons.OK,MessageBoxIcon.Asterisk);

The Output would be the same whatever the user input,because compiler would assume that we wanted to writte "Hello Name,welcome.." but when we remove the quotes from name,compiler knows that we are trying to display string.ALL TEXT THAT IS FIXED IN C# NEEDS TO BE ENCLOSED BY QUOTES LIKE THIS : "This is some text";

MessageBox

Syntax in C#

Function(parametar1,parametar2,parametar3.....);

Every line in C# has to be closed with ";" except statements,but I will explain that when we come to that!You can see that parametars are separated with ","!In case of MessageBox.Show parametars are MessageBox.Show(bodytext,title,buttons,icon); and they are different for every function!

We can change the icon as well by changing parametar4 in our MessageBox.Show,If you would like try changing our code a little bit a put instead of MessageBoxIcon.Asterisk,MessageBoxIcon and then put dot SharpDevelop should offer you available icons :

MessageBoxIcon.Asterisk
MessageBoxIcon.Error
MessageBoxIcon.Exclamation
MessageBoxIcon.Hand
MessageBoxIcon.Information
MessageBoxIcon.None
MessageBoxIcon.Question
MessageBoxIcon.Stop
MessageBoxIcon.Warning

So try to change this parametar and recompile program by pressing green arrow as shown on pictures and see how you MessageBox looks change!

Monday, June 21, 2010

Choosing the right IDE

So after we installed framework that we need,it is time to move on and to choose integrated development environment (IDE) you like.IDEs are applications where you will code and design your own programs.There are some free tools on the Internet for writing C# programs where visual design isn't available so you have to write everything in code.That is not practical for designing,this tools are only useful if you are experienced or just want to get the job done without hassle of visual design.There are two good C# IDEs available on the internet,one is open source and other is commercial :
  • Microsoft Visual Studio - Commercial
  • Sharp Develop - Open Source tool - Freeware
There is not really any difference in these two IDEs,but you will get some complicated things done easier with Visual Studio,but in reality Sharp develop is great tool and can seriously compete with Visual studio.I will use Sharp Develop 4.0,altought I have Visual Studio 2010 Ultimate Beta 2 because I'm a member of MSDN Academic Alliance.

Sharp Develop

Microsoft Visual Studio

Friday, June 18, 2010

Before we choose IDE


Before we move to choosing IDE you will have to download and install:
In order for user to run program that you have compiled with Microsoft .NET framework 4 on his system he will need to have Microsoft .NET framework 4 installed as well,this is only limitation to C# but you can later include it when you create installation files and put automatic download of the missing component.

You can choose to compile your programs with older version because users will more likely to have it installed already.But if you want to get full functionality or write for newer OS (Operating System) you should get Microsoft .NET framework 4 and besides you can include automatic download of a it in installation process of program you will make.

.NET enables C# language to stay simple and small,in there complicated functions get shorter and more simple but stay as powerfull.Note that you can run file compiled with framework 3 if you have framework 4 installed but that doesn't go reverse.

I will write my examples with Microsoft .NET framework 4

Openning of Programming Introduction Blog

Hello everyone I would like to give you basic programming introduction as well as some advanced stuff over the time,look on it like a course of programming that you can follow without any pressure.If you are interested in programming and have strong will you will learn it very quickly.So for introduction I will tell you little about myself.I have about 6 years of experince in programming in different programming languages such as : C/C++,assembler,Visual Basic,C#,Java,Jscript,php.But my main passion is C# (C-sharp) programming language so this introduction guide and blog will be based on it.I will start with GUI programming from beginning because I don't like that old console applications.I will write posts as often as I can and provide detailed explanations with all the examples I post.If you miss any part you can easly go to posts archive and check it out,in my next post I will talk about integrated development environment (IDE) where you will do all the magic of writing your programs.That's it for now,remember to follow blog for new posts and try searching Google for C#.

Vote