Paggeable Datagrid ItemSource throws null exception - c#

I want to create a generic Datagrid that can paginate. When I call the constructor of my DataGrid_UC and pass 20 Employees it does stores all 20 Employees in AllObject Observable Collection. And filter out the CurrentPageItems to be 5. But upon setting datagrid.ItemsSource = CurrentPageItems it throws null exception but CurrentPageItems does contain 5 items.
DataGrid_UC.xaml
public partial class DataGrid_UC : UserControl
{
private ObservableCollection<object> _currentPageItems;
public ObservableCollection<object> CurrentPageItems
{
get
{
return _currentPageItems;
}
private set
{
if (_currentPageItems != value)
{
_currentPageItems = value;
}
}
}
// Default Entries per page Number
private int _pageSize = 5;
public int PageSize
{
get
{
return _pageSize;
}
set
{
if (_pageSize != value)
{
_pageSize = value;
Reset();
}
}
}
public int TotalPagesNumber
{
get
{
if (AllObjects != null && PageSize > 0)
{
return (AllObjects.Count - 1) / PageSize + 1;
}
return 0;
}
}
private int _currentPageNumber = 1;
public int CurrentPageNumber
{
get
{
return _currentPageNumber;
}
protected set
{
if (_currentPageNumber != value)
{
_currentPageNumber = value;
}
}
}
protected ObservableCollection<object> AllObjects { get; set; }
public DataGrid_UC()
{
InitializeComponent();
dataGrid.ItemsSource = CurrentPageItems;
}
public DataGrid_UC(IEnumerable<object> allObjects, int? entriesPerPage = null)
{
AllObjects = new ObservableCollection<object>(allObjects);
if (entriesPerPage != null)
PageSize = (int)entriesPerPage;
SetCurrentPageItems();
}
#region Public Methods
public void GoToNextPage()
{
if (CurrentPageNumber != TotalPagesNumber)
{
CurrentPageNumber++;
SetCurrentPageItems();
}
}
public void GoToPreviousPage()
{
if (CurrentPageNumber > 1)
{
CurrentPageNumber--;
SetCurrentPageItems();
}
}
#endregion
#region Private Methods
public void SetCurrentPageItems()
{
int upperLimit = CurrentPageNumber * PageSize;
CurrentPageItems =
new ObservableCollection<object>(
AllObjects.Where(x => AllObjects.IndexOf(x) > upperLimit - (PageSize + 1) && AllObjects.IndexOf(x) < upperLimit));
dataGrid.ItemsSource = CurrentPageItems;
}
private void Reset()
{
CurrentPageNumber = 1;
SetCurrentPageItems();
}
#endregion
private void next_Click(object sender, RoutedEventArgs e)
{
if (CurrentPageNumber != TotalPagesNumber)
{
CurrentPageNumber++;
SetCurrentPageItems();
}
}
private void previous_Click(object sender, RoutedEventArgs e)
{
if (CurrentPageNumber > 1)
{
CurrentPageNumber--;
SetCurrentPageItems();
}
}
}
Main Window.xaml
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
List<Employee> emp = new List<Employee>();
for (int i = 0; i < 20; i++)
{
Employee e = new Employee();
e.ID = i;
e.Name = "Test " + i;
emp.Add(e);
}
DataGrid_UC d = new DataGrid_UC(emp, 5);
newContentControl.Content = d;
}
}

The dataGrid member is null because your second constructor is missing the InitializeComponent call, which (among other things) initializes the class members defined in XAML by x:Name.
So change the constructor like this:
public DataGrid_UC(IEnumerable<object> allObjects, int? entriesPerPage = null)
{
InitializeComponent();
AllObjects = new ObservableCollection<object>(allObjects);
...
}

Related

How to load data into a class and sort it

There is a LoadStudents method that writes objects with some fields to the Student class array. It is necessary to develop a method (I tried, called it Add) with the help of which it will be possible to carry out this procedure using three TextBoxes and the code for the button that will save this data.
public partial class Form1 : Form
{
public static int k=0;
Student[] mas = new Student[3];
public Form1()
{
InitializeComponent();
}
public delegate int CompareHealth(Student o1, Student o2);
public class Student
{
public string name = "";
public int days = 0;
public int hemoglobin = 0;
public Student() { }
public Student(string name, int days, int hemoglobin)
{
this.name = name;
this.days = days;
this.hemoglobin = hemoglobin;
}
public Student(Student s)
{
name = s.name;
days = s.days;
hemoglobin = s.hemoglobin;
}
public string add
{
set { name = value; }
get { return name; }
}
private static int CompareName(Student o1, Student o2)
{
return (string.Compare(o1.name, o2.name));
}
private static int CompareDays(Student o1, Student o2)
{
if (o1.days > o2.days) return (1);
else if (o1.days < o2.days) return (-1);
else return (0);
}
private static int CompareHemoglobin(Student o1, Student o2)
{
if (o1.hemoglobin > o2.hemoglobin) return (1);
else if (o1.hemoglobin < o2.hemoglobin) return (-1);
else return (0);
}
public static CompareHealth SortByName { get { return (new CompareHealth(CompareName)); } }
public static CompareHealth SortByDays { get { return (new CompareHealth(CompareDays)); } }
public static CompareHealth SortByHemoglobin { get { return (new CompareHealth(CompareHemoglobin)); } }
}
class Students
{
private int items = 0; const int n = 10;
private Student[] students = new Student[n];
public Student this[int num]
{
get { return (students[num - 1]); }
set { (students[num - 1]) = value; }
}
public void Vivod(ListBox h)
{
for (int i = 0; i < items; i++)
{
h.Items.Add(students[i].name + " " + students[i].days + " " + students[i].hemoglobin + " ");
}
}
public void LoadStudents()
{
Student p = new Student("А", 13, 68);
students[items++] = p;
Student w = new Student("Б", 18, 67);
students[items++] = w;
Student e = new Student("В", 5, 75);
students[items++] = e;
}
public void Add(TextBox t1, TextBox t2, TextBox t3)
{
if (k < 3)
{
Student load = new Student();
students[items++] = load;
k++;
}
}
public void SortStudent(CompareHealth compare)
{
Student temp = new Student();
for (int i = 1; i < items; i++)
for (int j = items - 1; j >= i; j--)
if (compare(students[j], students[j - 1]) == -1)
{ temp = students[j - 1]; students[j - 1] = students[j]; students[j] = temp; }
}
}
private void button2_Click(object sender, EventArgs e)
{
listBox1.Items.Clear();
Students students = new Students();
students.SortStudent(Student.SortByName);
students.Vivod(listBox1);
}
private void button1_Click(object sender, EventArgs e)
{
Students students = new Students();
students.Add(textBox1, textBox2, textBox3);
}
The problem is that one button contains the Add method and another (sorting) again, you need to specify a reference to the object students and, as I understand it, the array is reset. How to write code for buttons right?
I've had a go at rewriting your classes so that they are a bit more idiomatic. Let me know if there's anything in here that you need some explanation for.
public partial class Form1 : Form
{
private Students _students = new Students();
public Form1()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
_students.Sort(Students.SortByName);
this.Vivod(listBox1);
}
private void button1_Click(object sender, EventArgs e)
{
_students.Add(new Student(textBox1.Text, int.Parse(textBox2.Text), int.Parse(textBox3.Text)));
}
private void Vivod(ListBox listBox)
{
listBox.Items.Clear();
listBox.Items.AddRange(_students.ToStrings());
}
}
public class Students
{
private int _items = 0;
private const int __n = 10;
private Student[] students = new Student[__n];
public Student this[int num]
{
get => students[num - 1];
set { (students[num - 1]) = value; }
}
public string[] ToStrings() => Enumerable.Range(0, _items).Select(i => students[i].ToString() + " ").ToArray();
public void LoadStudents()
{
this.Add(new Student("А", 13, 68));
this.Add(new Student("Б", 18, 67));
this.Add(new Student("В", 5, 75));
}
public void Add(Student load)
{
if (_items < __n)
{
students[_items++] = load;
}
}
public void Sort(IComparer<Student> comparer)
{
Array.Sort(students, comparer);
}
private class SortByNameComparer : IComparer<Student>
{
public int Compare(Student o1, Student o2) => string.Compare(o1.Name, o2.Name);
}
private class SortByDaysComparer : IComparer<Student>
{
public int Compare(Student o1, Student o2) => o1.Days > o2.Days ? 1 : (o1.Days < o2.Days ? -1 : 0);
}
private class SortByHemoglobinComparer : IComparer<Student>
{
public int Compare(Student o1, Student o2) => o1.Hemoglobin > o2.Hemoglobin ? 1 : (o1.Hemoglobin < o2.Hemoglobin ? -1 : 0);
}
public static IComparer<Student> SortByName => new SortByNameComparer();
public static IComparer<Student> SortByDays => new SortByDaysComparer();
public static IComparer<Student> SortByHemoglobin => new SortByHemoglobinComparer();
}
public class Student
{
public string Name { get; set; } = "";
public int Days { get; set; } = 0;
public int Hemoglobin { get; set; } = 0;
public Student() { }
public Student(string name, int days, int hemoglobin)
{
this.Name = name;
this.Days = days;
this.Hemoglobin = hemoglobin;
}
public Student(Student s) : this(s.Name, s.Days, s.Hemoglobin) { }
public override string ToString() => $"{this.Name} {this.Days} {this.Hemoglobin}";
}
Ideally I'd make Student inherit from List<Student> to get the built-in list operations. Alternatively I'd use List<Student> instead of Student[] inside Students. But this should be a good start.

MVVM BeginInvoke doesn't work in my reference

I created a reference to load big data into a datagrid with a dapper extension. I have a Behavior that detects when the scroll is then down load the following data using this RelayCommand:
XAML in Datagrid Properties :
Behavior:ScrollViewerMonitor.AtEndCommand="{Binding LoadCommand}"
My Behavior (Detect when scroll is down) :
public class ScrollViewerMonitor
{
public static DependencyProperty AtEndCommandProperty
= DependencyProperty.RegisterAttached(
"AtEndCommand", typeof(ICommand),
typeof(ScrollViewerMonitor),
new PropertyMetadata(OnAtEndCommandChanged));
public static ICommand GetAtEndCommand(DependencyObject obj)
{
return (ICommand)obj.GetValue(AtEndCommandProperty);
}
public static void SetAtEndCommand(DependencyObject obj, ICommand value)
{
obj.SetValue(AtEndCommandProperty, value);
}
public static void OnAtEndCommandChanged(
DependencyObject d, DependencyPropertyChangedEventArgs e)
{
FrameworkElement element = (FrameworkElement)d;
if (element != null)
{
element.Loaded -= element_Loaded;
element.Loaded += element_Loaded;
}
}
static void element_Loaded(object sender, RoutedEventArgs e)
{
FrameworkElement element = (FrameworkElement)sender;
element.Loaded -= element_Loaded;
ScrollViewer scrollViewer = FindChildOfType<ScrollViewer>(element);
if (scrollViewer == null)
{
// throw new InvalidOperationException("ScrollViewer not found.");
return;
}
var dpd = DependencyPropertyDescriptor.FromProperty(ScrollViewer.VerticalOffsetProperty, typeof(ScrollViewer));
dpd.AddValueChanged(scrollViewer, delegate (object o, EventArgs args)
{
bool atBottom = scrollViewer.VerticalOffset
>= scrollViewer.ScrollableHeight;
if (atBottom)
{
var atEnd = GetAtEndCommand(element);
if (atEnd != null)
{
atEnd.Execute(null);
}
}
});
}
static T FindChildOfType<T>(DependencyObject root) where T : class
{
var queue = new Queue<DependencyObject>();
queue.Enqueue(root);
while (queue.Count > 0)
{
DependencyObject current = queue.Dequeue();
for (int i = VisualTreeHelper.GetChildrenCount(current) - 1; 0 <= i; i--)
{
var child = VisualTreeHelper.GetChild(current, i);
var typedChild = child as T;
if (typedChild != null)
{
return typedChild;
}
queue.Enqueue(child);
}
}
return null;
}
}
My ViewModel with LoadCommand :
//Init mmy ObservableCollection for DataGrid
var myObservableCollection = new ObservableCollection<Mouvement_Brouillard>();
//Init my Object
//Parameters(NumberPerPage,Conditions,OrderBy,Connection)
var myReference = new Paged2<Mouvement_Brouillard>(150, "", "Swmo_Id", new ConnectionProvider());
//Load First Datas
myReference.AddDatas(myObservableCollection);
//Call LoadCommand when Scroll is down
LoadCommand = new RelayCommand<object>(myReference.LoadCommand(myObservableCollection));
And my reference Paged2 (AddData in ObservableCollection and execute LoadCommand:
public class Paged2<T>
{
private T Value { get; set; }
public int NumberPage { get; set; }
public int RowsPerPage { get; set; }
public string Conditions { get; set; }
public string OrderBy { get; set; }
public ConnectionProvider Cnn { get; set; }
public static bool Busy;
public Paged2(int _RowsPerPage, string _Conditions, string _OrdeBy, ConnectionProvider _Cnn)
{
this.RowsPerPage = _RowsPerPage;
this.Conditions = _Conditions;
this.OrderBy = _OrdeBy;
this.NumberPage = 1;
this.Cnn = _Cnn;
}
public async void AddDatas(ObservableCollection<T> myList)
{
IEnumerable<T> myNewBlocList;
//DAL
using (var myCnn = this.Cnn.GetOpenConnection())
{
myNewBlocList = await myCnn.GetListPagedAsync<T>(this.NumberPage, this.RowsPerPage, this.Conditions, this.OrderBy);
}
NumberPage++;
foreach (var Item in myNewBlocList)
myList.Add(Item);
}
public Action<object> LoadCommand(Ref<ObservableCollection<T>> myList)
{
return new Action<object>(
obj =>
{
if (Busy)
return;
Busy = true;
System.Threading.ThreadPool.QueueUserWorkItem(
delegate
{
Application.Current.Dispatcher.BeginInvoke(new Action(
delegate
{
AddDatas(myList);
Busy = false;
}));
});
});
}
public class Ref<T>
{
public Ref() { }
public Ref(T value) { Value = value; }
public T Value { get; set; }
public override string ToString()
{
T value = Value;
return value == null ? "" : value.ToString();
}
public static implicit operator T(Ref<T> r) { return r.Value; }
public static implicit operator Ref<T>(T value) { return new Ref<T>(value); }
}
}
Everything works but since I outsource (place in another file ) method LoadCommand the next part of the code no longer works :
public Action<object> LoadCommand(Ref<ObservableCollection<T>> myList)
{
return new Action<object>(
obj =>
{
if (Busy)
return;
Busy = true;
System.Threading.ThreadPool.QueueUserWorkItem(
delegate
{
Application.Current.Dispatcher.BeginInvoke(new Action(
delegate
{
AddDatas(myList);
Busy = false;
}));
});
});
}

How to mock protected members with multiple interfaces

How to mock this class in nUnit Tests?
public class OpenDataQuery: PagedQuery, IOpenDataQuery
{
private static Dictionary<string, SortItem> m_sortModes;
protected override Dictionary<string, SortItem> SortModes
{
get
{
if (m_sortModes == null)
{
m_sortModes = new Dictionary<string, SortItem>();
AddSortMode(m_sortModes, new SortItem(ObjectExtensions.GetNameFromExpression<OpenDataCategoriesModel, string>(m => m.Name), "Наименование ↑", true) { IsDefault = true });
AddSortMode(m_sortModes, new SortItem(ObjectExtensions.GetNameFromExpression<OpenDataCategoriesModel, string>(m => m.Name), "Наименование ↓"));
}
return m_sortModes;
}
}
public IEnumerable<OpenDataCategoriesModel> OpenDataCategories { get; set; }
public string OpenDataTags { get; set; }
}
and
public abstract class PagedQuery : IPagedQuery
{
private const int DEFAULT_PAGE = 1;
private const int DEFAULT_COUNT = 5;
private int? m_page;
private int? m_count;
private int? m_total;
private string m_sort;
public int? Page
{
get
{
if (m_page == null || m_page <= 0)
{
return DEFAULT_PAGE;
}
return m_page;
}
set { m_page = value; }
}
public int? Count
{
get
{
if (m_count == null || m_count <= 0)
{
return DEFAULT_COUNT;
}
return m_count;
}
set { m_count = value; }
}
public int? Total
{
get
{
if (m_total == null || m_total <= 0)
{
return 0;
}
return m_total;
}
set { m_total = value; }
}
public string SearchQuery { get; set; }
protected virtual Dictionary<string, SortItem> SortModes
{
get { return null; }
}
public string Sort
{
get
{
var sortMode = GetSortMode(m_sort);
if (sortMode == null)
{
var defaultSort = (from i in SortModes where i.Value.IsDefault select i).FirstOrDefault();
if (!string.IsNullOrWhiteSpace(defaultSort.Key))
{
return defaultSort.Key;
}
return (from i in SortModes select i.Key).First();
}
return m_sort;
}
set
{
m_sort = value;
}
}
protected void AddSortMode(Dictionary<string, SortItem> sortModes, SortItem sortItem)
{
sortModes.Add(
String.Format(
"{0}{1}",
sortItem.FieldName.ToLower(),
sortItem.Asc ? "asc" : "desc"
),
sortItem
);
}
private SortItem GetSortMode(string sort)
{
if (SortModes == null || string.IsNullOrWhiteSpace(sort) ||
!SortModes.ContainsKey(sort.ToLower()))
{
return null;
}
return SortModes[sort.ToLower()];
}
public IOrderBy GetOrderBy()
{
var item = GetCurrentSortItem();
if (item == null)
{
return null;
}
if (item.Asc)
{
return new OrderBy(item.FieldName);
}
return new OrderByDesc(item.FieldName);
}
public SortItem GetCurrentSortItem()
{
return GetSortMode(Sort);
}
public Dictionary<string, SortItem> GetSortItems()
{
return SortModes;
}
}
and
public interface IOpenDataQuery : IPagedQuery
{
string OpenDataTags { get; set; }
}
I have some service method, that used openDataQuery class in parameters and in unit test i am trying mock this class, but this doesn't work:
public partial class OpenDataQueryRepository : Mock<OpenDataQuery>
{
public OpenDataQueryRepository(MockBehavior mockBehavior = MockBehavior.Strict)
: base(mockBehavior)
{
var opendataQuery = new Mock<IOpenDataQuery>();
var pagedQuery = opendataQuery.As<IPagedQuery>();
this.Setup(p=>p.GetOpenDataCategoriesMain(pagedQuery.Object,outttl)).Returns(OpenDataCategories);
}
}
I know that i should use Moq.Protected() for protected methods, but i don't know how use it correctly in this case. Please help me.
UPDATE:
I am testing this controller:
public class ODOpenDataController : ODBaseController
{
private readonly IOpenDataProvider m_openDataProvider;
public ODOpenDataController(IOpenDataProvider openDataProvider)
{
m_openDataProvider = openDataProvider;
}
public ActionResult Index(OpenDataQuery query)
{
int total;
query.OpenDataCategories = m_openDataProvider.GetOpenDataCategoriesMain(query, out total)
query.Total = total;
return View(query);
}
}
Test:
[Test]
public void Index_Test()
{
var opendataController = new ODOpenDataController(new OpenDataRepository().Object);
var result = opendataController.Index(new OpenDataQuery()) as ViewResult;
var model = result.Model as OpenDataQuery;
Assert.IsTrue(model.OpenDataCategories.Count() == 1);
}

showing form by select from list invalid cast exception

I want to add two lists to the box. It doesn't have a problem with adding items to the listbox, but a problem occurs when I try to click on one of the items and show a related form with details filled in to allow users to make amendments. Obviously the form didn't show, but instead an error occurs, no matter if I was try to open the form "delivery" or "pickup". The problem still occurs on one line
Error:
An unhandled exception of type 'System.InvalidCastException' occurred
in coursework2.exe
Additional information: Unable to cast object of type 'System.String'
to type 'coursework2.Pickup'.
namespace coursework2
{
public partial class MainForm : Form
{
private DeliveryForm deliveryform = new DeliveryForm();
private List<Visit> requests = new List<Visit>();
private Visit theVisit = new Visit();
private PickupForm pickupform = new PickupForm();
public void requestVisit(Visit newVisit)
{
requests.Add(newVisit);
}
public MainForm()
{
InitializeComponent();
}
private void btnNpickup_Click(object sender, EventArgs e)
{
pickupform.pickup = new Pickup();
pickupform.ShowDialog();
if (pickupform.pickup != null)
{
Pickup newPu = pickupform.pickup;
theVisit.addPick(newPu);
List<String> listOfPic = theVisit.listofPicks();
listboxVisits.Items.AddRange(listOfPic.ToArray());
}
updateList();
//this will upload details from pickup form to the list
}
private void groupBox2_Enter(object sender, EventArgs e)
{
}
private void MainForm_Load(object sender, EventArgs e)
{
}
private void btnNdelivery_Click(object sender, EventArgs e)
{
deliveryform.delivery = new Delivery();
deliveryform.ShowDialog();
if (deliveryform.delivery != null)
{
Delivery newDe = deliveryform.delivery;
theVisit.addDeliver(newDe);
List<String> listOfDel = theVisit.listofDeliver();
listboxVisits.Items.AddRange(listOfDel.ToArray());
}
updateList();
//this will upload detail of the delivery to the list
}
private void btnVall_Click(object sender, EventArgs e)
{
}
private void updateList()
{
listboxVisits.Items.Clear();
List<String> listofVis = theVisit.LisitVisits();
listboxVisits.Items.AddRange(listofVis.ToArray());
}
private void listboxVisits_SelectedIndexChanged(object sender, EventArgs e)
{
listboxVisits.FormattingEnabled = false;
int index = listboxVisits.SelectedIndex;
if (listboxVisits.SelectedItems.Count>0)
{
object object1 = listboxVisits.SelectedItems[0];
if (object1 is Delivery)
{
Delivery deliver = (Delivery)object1;
deliveryform.delivery = deliver;
deliveryform.ShowDialog();
}
else
{
Pickup pick = (Pickup)object1;// this is where error occur
pickupform.pickup = pick;
pickupform.ShowDialog();
}
}
this is the pickup class
public class Pickup
{
private string pickupname;
private string pickupaddress;
private Visit collects;
private Delivery sends;
private DateTime pdatetime;
private string dname;
private string daddress;
private DateTime dtime;
public string PickupName
{
get { return pickupname; }
set { pickupname = value; }
}
public string PickupAddress
{
get { return pickupaddress; }
set { pickupaddress = value; }
}
public string Dname
{
get { return dname; }
set { dname = value; }
}
public string Daddress
{
get { return daddress; }
set {daddress = value; }
}
public DateTime Pdatetime
{
get { return pdatetime; }
set { pdatetime = value; }
}
public DateTime Dtime
{
get { return dtime; }
set { dtime = value; }
}
public override string ToString()
{
return pickupname + " " + pickupaddress + " " + pdatetime.ToString()+" "+dname+" "+daddress+" "+dtime.ToString()+" Pickup ";
}
}
this is the visit class
public class Visit : Customer
{
private Customer requester;
private DateTime datetime;
private Delivery reciever;
private Pickup collect;
public DateTime DateTime
{
get { return datetime; }
set { datetime = value; }
}
private List<Pickup> picks = new List<Pickup>();
private List<Visit> visits = new List<Visit>();
private List<Delivery> deliver = new List<Delivery>();
public void addDeliver(Delivery de)
{
//adding new Delivery ToString the visit
deliver.Add(de);
}
public List<String> listofDeliver()
{
List<string> listofDeliver = new List<string>();
foreach (Delivery de in deliver)
{
String deAsString = de.ToString();
listofDeliver.Add(deAsString);
}
return listofDeliver;
}
public Delivery getDeliver(int index)
{
int count = 0;
foreach (Delivery de in deliver)
{
if (index == count)
return de;
count++;
}
return null;
}
public void addPick(Pickup pu)
{
picks.Add(pu);
}
public List<String> listofPicks()
{
List<string> listofPicks = new List<string>();
foreach (Pickup pu in picks)
{
String puAsString = pu.ToString();
listofPicks.Add(puAsString);
}
return listofPicks;
}
public Pickup getPicks(int index)
{
int count = 0;
foreach (Pickup pu in picks)
{
if (index == count)
return pu;
count++;
}
return null;
}
public List<String> LisitVisits()
{
List<String> visits = new List<string>();
visits.AddRange(listofDeliver());
visits.AddRange(listofPicks());
return visits;
}
public Visit getVisits(int index)
{
int count = 0;
foreach (Visit vis in visits)
{
if (index == count)
return vis;
count++;
}
return null;
}
public string VisitDetails()
{
return collect.PickupName + " " + collect.PickupAddress + " Pickup " + reciever.DeliveryName + " " + reciever.DeliveryAddress + " Delivery";
}
}

In Datagridview Paging not getting exact number of rows shown

I am using this code for paging ,using this i am getting all records in datagridview ,i have set _PateSize = 10;why i am not getting only 10 rows in datagridview,and on click of next button next 10 rows,how do i make this code working ,where i am going wrong
public partial class ShowEngClgList : Form
{
private int _CurrentPage = 1;
private int _PateSize = 10;
public int PageSize
{
get
{
return _PateSize;
}
set
{
_PateSize = value;
}
}
private DataTable _DataSource;
public DataTable DataSource
{
get
{
return _DataSource;
}
set
{
_DataSource = value;
}
}
private int _Width;
public int ControlWidth
{
get
{
if (_Width == 0)
return dataGridView1.Width;
else
return _Width;
}
set
{
_Width = value;
dataGridView1.Width = _Width;
}
}
private int _Height;
public int ControlHeight
{
get
{
if (_Height == 0)
return dataGridView1.Height;
else
return _Height;
}
set
{
_Height = value;
dataGridView1.Height = _Height;
}
}
private string _FirstButtonText = string.Empty;
public string FirstButtonText
{
get
{
if (_FirstButtonText == string.Empty)
return btnFirst.Text;
else
return _FirstButtonText;
}
set
{
_FirstButtonText = value;
btnFirst.Text = _FirstButtonText;
}
}
private string _LastButtonText = string.Empty;
public string LastButtonText
{
get
{
if (_LastButtonText == string.Empty)
return btnLast.Text;
else
return _LastButtonText;
}
set
{
_LastButtonText = value;
btnLast.Text = _LastButtonText;
}
}
private string _PreviousButtonText = string.Empty;
public string PreviousButtonText
{
get
{
if (_PreviousButtonText == string.Empty)
return btnPrevious.Text;
else
return _PreviousButtonText;
}
set
{
_PreviousButtonText = value;
btnPrevious.Text = _PreviousButtonText;
}
}
private string _NextButtonText = string.Empty;
public string NextButtonText
{
get
{
if (_NextButtonText == string.Empty)
return btnNext.Text;
else
return _NextButtonText;
}
set
{
_NextButtonText = value;
btnNext.Text = _NextButtonText;
}
}
public void DataBind(DataTable dataTable)
{
DataSource = dataTable;
dataGridView1.DataSource = ShowData(1);
}
private DataTable ShowData(int pageNumber)
{
DataTable dt = new DataTable();
int startIndex = PageSize * (pageNumber - 1);
var result = DataSource.AsEnumerable().Where((s, k) => (k >= startIndex && k < (startIndex + PageSize)));
foreach (DataColumn colunm in DataSource.Columns)
{
dt.Columns.Add(colunm.ColumnName);
}
foreach (var item in result)
{
dt.ImportRow(item);
}
txtPaging.Text = string.Format("Page {0} Of {1} Pages", pageNumber, (DataSource.Rows.Count / PageSize) + 1);
return dt;
}
public OleDbConnection acccon = null;
public OleDbDataAdapter da = null;
public DataTable dt = null;
public ShowEngClgList()
{
InitializeComponent();
try
{
acccon = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=db1.mdb");
acccon.Open();
}
catch (Exception err)
{
}
string sql = "Select EngClgName,EngClgAddress,EngClgEntranceType From EngColeges";
da = new OleDbDataAdapter(sql, acccon);
dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
}
private void btnFirst_Click(object sender, EventArgs e)
{
if (_CurrentPage == 1)
{
MessageBox.Show("You are already on First Page.");
}
else
{
_CurrentPage = 1;
dataGridView1.DataSource = ShowData(_CurrentPage);
}
}
private void btnPrevious_Click(object sender, EventArgs e)
{
if (_CurrentPage == 1)
{
MessageBox.Show("You are already on First page, you can not go to previous of First page.");
}
else
{
_CurrentPage -= 1;
dataGridView1.DataSource = ShowData(_CurrentPage);
}
}
private void btnNext_Click(object sender, EventArgs e)
{
int lastPage = (DataSource.Rows.Count / PageSize) + 1;
if (_CurrentPage == lastPage)
{
MessageBox.Show("You are already on Last page, you can not go to next page of Last page.");
}
else
{
_CurrentPage += 1;
dataGridView1.DataSource = ShowData(_CurrentPage);
}
}
private void btnLast_Click(object sender, EventArgs e)
{
int previousPage = _CurrentPage;
_CurrentPage = (DataSource.Rows.Count / PageSize) + 1;
if (previousPage == _CurrentPage)
{
MessageBox.Show("You are already on Last Page.");
}
else
{
dataGridView1.DataSource = ShowData(_CurrentPage);
}
}
}
thanks in advance for any help

Categories

Resources