I am retrieving data from db and displaying in Label. but the problem is that this cannot retrieve db tabel first row data. Its print Second row data. If i given the db first row c_code then it is given the Error "There is no row at position 2" Kindly please solve my problem.
Thanks you
private void Get_Purchasing_Amount()
{
try
{
string get_P_Amount = "";
double var_P_Amount = 0;
int var_C_Code = 0;
string query = "select c_code as 'code' from `db_vegetable`.`tbl_payment_master`";
DataTable dt_C_Code = method_Class.method_Class.FetchRecords(query);
if (dt_C_Code.Rows.Count > 0)
{
for (int i = 0; i <= dt_C_Code.Rows.Count; i++)
{
var_C_Code = Convert.ToInt32(dt_C_Code.Rows[i]["code"]);
if (var_C_Code.Equals(Convert.ToInt32(txt_Customer_Code.Text)))
{
if (check_All.Checked.Equals(true))
{
get_P_Amount = "SELECT IFNULL(`purchasing`,0) AS 'purchasing' FROM `db_vegetable`.`tbl_payment_master` WHERE `c_code` = " + txt_Customer_Code.Text + "";
}
else
{
string dt_Query = "select `id` as 'id' from `db_vegetable`.`tbl_order_details`";
DataTable dt_C_O = method_Class.method_Class.FetchRecords(dt_Query);
if (dt_C_O.Rows.Count > 0)
get_P_Amount = "SELECT IFNULL(SUM(t_price),0) as 'purchasing' FROM `db_vegetable`.`tbl_order_details` WHERE `c_code` = " + txt_Customer_Code.Text + " AND (`date` BETWEEN '" + txt_From_Date.Text + "' AND '" + txt_To_Date.Text + "')";
else
lbl_Purchasing_Amount.Text = "0";
}
DataTable dt = method_Class.method_Class.FetchRecords(get_P_Amount);
var_P_Amount = Convert.ToDouble(dt.Rows[0]["purchasing"]);
lbl_Purchasing_Amount.Text = var_P_Amount.ToString();
}
else
{
lbl_Purchasing_Amount.Text = "0";
}
}
}
else
{
lbl_Purchasing_Amount.Text = "0";
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I believe this is probably the issue:
for (int i = 0; i <= dt_C_Code.Rows.Count; ; i++) {...}
Please consider substituting foreach (DataRow row in dt_C_Code.Rows) { ...}
If it's important which row should logically come "first", then please consider using an order by clause in your SQL statement.
Now problem is solve the problem is that break key word.
private void Get_Purchasing_Amount()
{
try
{
string get_P_Amount = "";
double var_P_Amount = 0;
//int var_C_Code = 0;
string query = "select c_code as 'code' from `db_vegetable`.`tbl_payment_master`";
DataTable dt_C_Code = method_Class.method_Class.FetchRecords(query);
if (dt_C_Code.Rows.Count > 0)
{
for (int i = 0; i <= dt_C_Code.Rows.Count; i++)//these line generate error please check this
{
//var_C_Code = Convert.ToInt32(dt_C_Code.Rows[i]["code"]);
if (Convert.ToInt32(dt_C_Code.Rows[i]["code"]).Equals(Convert.ToInt32(txt_Customer_Code.Text)))
{
if (check_All.Checked.Equals(true))
{
get_P_Amount = "SELECT IFNULL(`purchasing`,0) AS 'purchasing' FROM `db_vegetable`.`tbl_payment_master` WHERE `c_code` = " + txt_Customer_Code.Text + "";
}
else
{
string dt_Query = "select `id` as 'id' from `db_vegetable`.`tbl_order_details`";
DataTable dt_C_O = method_Class.method_Class.FetchRecords(dt_Query);
if (dt_C_O.Rows.Count > 0)
get_P_Amount = "SELECT IFNULL(SUM(t_price),0) as 'purchasing' FROM `db_vegetable`.`tbl_order_details` WHERE `c_code` = " + txt_Customer_Code.Text + " AND (`date` BETWEEN '" + txt_From_Date.Text + "' AND '" + txt_To_Date.Text + "')";
else
lbl_Purchasing_Amount.Text = "0";
}
DataTable dt = method_Class.method_Class.FetchRecords(get_P_Amount);
var_P_Amount = Convert.ToDouble(dt.Rows[0]["purchasing"]);
lbl_Purchasing_Amount.Text = var_P_Amount.ToString();
break;
}
else
{
lbl_Purchasing_Amount.Text = "0";
}
}
}
else
{
lbl_Purchasing_Amount.Text = "0";
}
}
catch (Exception)
{
}
}
In my program which has datagridview for insert,update or delete Purchase Order and it behave like as a shopping cart.This datagridview consist of BookName,ISBNNo,Order quantity,unit price and total.When I insert this datagridview data to database,each row insert with unique id PO_Cart_No(pk) which has identity value.
And also other background textbox details which are Po_No,supplier_Id and Grand total details insert into separate table which called PO table.And also this two tables link with foreign key PO_No.My question is when I add new row to existing row to update database,that new row didn't insert and other row data has updated.
Where is the problem.This is my code for you,
public void UpdatePurchseOrderTable(int PO_No,int Supplier_ID, string Date, string RequiredDate, double GrandTotal)
{
DynamicConnection con = new DynamicConnection();
con.mysqlconnection();
string query = "UPDATE TBL_PO "
+ " SET Supplier_ID = #Supplier_ID,Date = #Date,"
+ "RequiredDate = #RequiredDate,GrandTotal=#GrandTotal"
+ " WHERE PO_No = #PO_No";
con.sqlquery(query);
con.cmd.Parameters.Add(new SqlParameter("#PO_No", SqlDbType.Int));
con.cmd.Parameters["#PO_No"].Value = PO_No;
con.cmd.Parameters.Add(new SqlParameter("#Supplier_ID", SqlDbType.Int));
con.cmd.Parameters["#Supplier_ID"].Value = Supplier_ID;
con.cmd.Parameters.Add(new SqlParameter("#Date", SqlDbType.Date));
con.cmd.Parameters["#Date"].Value = Date;
con.cmd.Parameters.Add(new SqlParameter("#RequiredDate", SqlDbType.Date));
con.cmd.Parameters["#RequiredDate"].Value = RequiredDate;
con.cmd.Parameters.Add(new SqlParameter("#GrandTotal", SqlDbType.Money));
con.cmd.Parameters["#GrandTotal"].Value = GrandTotal;
con.nonquery();
}
public void UpdatePOCartTable(int PO_No,string ISBN_No,int OrderQuantity, double UnitPrice, double Total)
{
DynamicConnection con = new DynamicConnection();
con.mysqlconnection();
string query = "UPDATE TBL_PO_Cart"
+ " SET ISBN_No = #ISBN_No, OrderQuantity= #OrderQuantity,"
+ "UnitPrice= #UnitPrice,Total=#Total"
+ " WHERE PO_No = #PO_No";
con.sqlquery(query);
con.cmd.Parameters.Add(new SqlParameter("#PO_No", SqlDbType.Int));
con.cmd.Parameters["#PO_No"].Value = PO_No;
con.cmd.Parameters.Add(new SqlParameter("#ISBN_No", SqlDbType.NVarChar));
con.cmd.Parameters["#ISBN_No"].Value = ISBN_No;
con.cmd.Parameters.Add(new SqlParameter("#OrderQuantity", SqlDbType.NVarChar));
con.cmd.Parameters["#OrderQuantity"].Value = OrderQuantity;
con.cmd.Parameters.Add(new SqlParameter("#UnitPrice", SqlDbType.Money));
con.cmd.Parameters["#UnitPrice"].Value = Math.Round(UnitPrice,2,MidpointRounding.AwayFromZero);
con.cmd.Parameters.Add(new SqlParameter("#Total", SqlDbType.Money));
con.cmd.Parameters["#Total"].Value = Math.Round(Total,2,MidpointRounding.AwayFromZero);
con.nonquery();
}
and PO form data as follows
private void btnedit_Click(object sender, EventArgs e)
{
DynamicConnection con = new DynamicConnection();
try
{
if (txtPONo.Text != "" || cmbsupID.Text != "" || date1.Text != "" || requireddate.Text != "" || txtgrandTotal.Text != "")
{
PurchaseOrder PO = new PurchaseOrder();
if (cmbsupID.Text.Contains('-'))
{
string str = cmbsupID.Text;
int index = str.IndexOf('-');
if (index > 0)
{
int value = int.Parse(str.Substring(0, index));
PO.UpdatePurchseOrderTable(Convert.ToInt32(txtPONo.Text), value, date1.Text, requireddate.Text, Convert.ToDouble(txtgrandTotal.Text));
}
}
else
{
int value2 = Convert.ToInt32(cmbsupID.Text);
PO.UpdatePurchseOrderTable(Convert.ToInt32(txtPONo.Text), value2, date1.Text, requireddate.Text, Convert.ToDouble(txtgrandTotal.Text));
}
for (int i = 0; i < dataGridView1.Rows.Count-1; i++)
{
int PONO = Convert.ToInt32(txtPONo.Text);
string column1 = Convert.ToString(dataGridView1.Rows[i].Cells[1].Value);
int column2 = Convert.ToInt32(dataGridView1.Rows[i].Cells[2].Value);
double column3= Convert.ToDouble(dataGridView1.Rows[i].Cells[3].Value);
double column4 = Convert.ToDouble(dataGridView1.Rows[i].Cells[4].Value);
PO.UpdatePOCartTable(PONO,column1,column2,column3,column4);
}
}
else
{
MessageBox.Show("Please Provide Details!");
}
dataGridView1.Rows.Clear();
ClearData();
retviewPO_No();
MessageBox.Show("Record Updated Successfully");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I'm having problem setting the vertical scroll position. I have followed this similar question and I get the expected result for CellDoubleClick Event. But for KeyDown Event, where the user will press Enter key, it resets the vertical scroll position at the top
These are my CellDouble Click and KeyDown events.
private void dataGridSrch_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
addToSell();
}
}
private void dataGridSrch_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
addToSell();
}
This is my addToSell function, this function will call after that will update the DataGridView.
public void addToSell()
{
if (dataGridSrch.SelectedRows.Count > 0)
{
DataRow row = (dataGridSrch.SelectedRows[0].DataBoundItem as DataRowView).Row;
if (Convert.ToInt32(row["Stock"].ToString()) > 0)
{
string sellProd = row["Brand"].ToString() + " " + row["Part No."].ToString();
int sellQty = Convert.ToInt32(numSell.Value);
string sellUnit = row["Unit"].ToString();
double sellPrice = double.Parse(row["Price"].ToString()) * sellQty;
double sPrice = double.Parse(row["Price"].ToString());
dataGridSales.Rows.Add(sellProd, sellQty, sellUnit, sellPrice, sPrice, row["Part No."].ToString(), row["Stock"].ToString());
int count = 0;
double total = 0;
for (int i = 0; i < dataGridSales.Rows.Count; i++)
{
total += Convert.ToDouble(dataGridSales.Rows[i].Cells[3].Value);
count += Convert.ToInt32(dataGridSales.Rows[i].Cells[1].Value);
}
lblTotAmt.Text = "Total Amount: " + total.ToString("C2");
lblTotItem.Text = "Total Items: " + count;
amount = total;
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(#"UPDATE [dbo].[products]
SET Stock = Stock - '" + sellQty + "' WHERE [Part No.] = '" + row["Part No."] + "'", conn))
{
cmd.ExecuteNonQuery();
}
conn.Close();
}
>>>>>>>>>>>>>>>>after(); //THIS IS WHERE AFTER FUNCTION IS CALLED
}
else
{
MessageBox.Show("You dont have any stock for the selected item, please restock immediately.", "Please restock", MessageBoxButtons.OK);
}
}
if (dataGridSales.Rows.Count > 0)
{
cmbMOP.Enabled = true;
}
}
And this is my after function.
public void after()
{
string item = cmbItem.Text;
string brand = cmbBrand.Text;
string part = txtPart.Text;
string manu = cmbMan.Text;
string car = cmbCar.Text;
string year = cmbYr.Text;
conn.Open();
{
int index = dataGridSrch.SelectedRows[0].Index;
>>>>>>>>>>>>int scrollPos = dataGridSrch.FirstDisplayedScrollingRowIndex; //GET THE SCROLL POSITION
string sel = #"SELECT * FROM[dbo].[products] WHERE 1=1";
using (SqlCommand cmd = new SqlCommand())
{
if (!string.IsNullOrEmpty(item))
{
sel += " AND Item = #Item";
cmd.Parameters.Add("#Item", SqlDbType.VarChar).Value = item;
}
if (!string.IsNullOrEmpty(brand))
{
sel += " AND Brand = #Brand";
cmd.Parameters.Add("#Brand", SqlDbType.VarChar).Value = brand;
}
if (!string.IsNullOrEmpty(part))
{
sel += " AND [Part No.] = #Part";
cmd.Parameters.Add("#Part", SqlDbType.VarChar).Value = part;
}
if (!string.IsNullOrEmpty(manu))
{
sel += " AND Manufacturer = #Manufacturer";
cmd.Parameters.Add("#Manufacturer", SqlDbType.VarChar).Value = manu;
}
if (!string.IsNullOrEmpty(car))
{
sel += " AND Car = #Car";
cmd.Parameters.Add("#Car", SqlDbType.VarChar).Value = car;
}
if (!string.IsNullOrEmpty(year))
{
sel += " AND Year = #Year";
cmd.Parameters.Add("#Year", SqlDbType.VarChar).Value = year;
}
cmd.CommandText = sel;
cmd.Connection = conn;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
DataView dv = dt.DefaultView;
sda.Fill(dt);
dataGridSrch.DataSource = dt;
dv.Sort = "Item, Brand, Manufacturer, Car, Year, Price ASC ";
dataGridSrch.Columns["Price"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
dataGridSrch.Columns["Price"].DefaultCellStyle.Format = "C2";
dataGridSrch.Columns["Stock"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
dataGridSrch.Rows[index].Selected = true;
>>>>>>>>>>>>>>>>>>>>dataGridSrch.FirstDisplayedScrollingRowIndex = scrollPos; //AFTER UPDATE SET THE SCROLL POSITION
typeof(DataGridView).InvokeMember("DoubleBuffered", BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.SetProperty, null,
dataGridSrch, new object[] { true });
}
}
}
conn.Close();
}
I have also change my KeyDown Event to this
private void dataGridSrch_KeyDown(object sender, KeyEventArgs e)
{
int index = dataGridSrch.SelectedRows[0].Index;
int scrollPos = dataGridSrch.FirstDisplayedScrollingRowIndex;
if (e.KeyCode == Keys.Enter)
{
addToSell();
dataGridSrch.Rows[index].Selected = true;
dataGridSrch.FirstDisplayedScrollingRowIndex = scrollPos;
}
}
But still it resets the scroll position.
I have this code
*start time is another DateTime.now
*timeSinceStart is an array of timeSpan
*i believe that the for loop is for me to be able to create and store many values for the timespan and update the listview items(see link below for the photo of the form)
*f.ToString() is default 60(its an integer)
*the MH column in the picture is counting upwards, for ex. 1 2 3 4 5 6 etc etc
private void timer2_Tick(object sender, EventArgs e)
{
for (int w = 0; w < listView1.Items.Count; w++)
{
timeSinceStart[w] = DateTime.Now - startTime[w];
listView1.Items[w].SubItems[6].Text = (timeSinceStart[w].TotalSeconds.ToString());
if (f.ToString() == listView1.Items[w].SubItems[6].Text)
{
MessageBox.Show("dedede");
}
else
{
label3.Text = timeSinceStart[w].TotalSeconds.ToString();
}
}
I really cant make the message box pop up and also, the timespan value has decimal values, does it have a connection why the if condition doesn't trigger?
I have tried converting timespan to datetime and use datetime and timespan in the if else condition, it also doesnt seem to work.
here is the picture as i was saying:
edit*
I have another form that let the user to input an integer and a combobox that contains "Hour" of "Minute".
this is the code it contains:
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text == "")
{
MessageBox.Show("Please Indicate How Many Minutes/Hours.");
}
else
{
string desu = textBox1.Text;
int temp = 0;
if (int.TryParse(desu, out temp))
{
if (comboBox1.Text == "Hours")
{
//hours to seconds
time = temp * 3600;
eta = desu + " Hours";
sot = temp;
this.Close();
}
else if (comboBox1.Text == "Minutes")
{
//minutes to seconds
time = temp * 60;
eta = desu + " Minutes";
sot = temp;
this.Close();
}
}
else
{
MessageBox.Show("Please enter a valid integer");
}
}
}
And then i pass the value of "time" into the form mentioned above
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
ETA_Input frm = new ETA_Input(this);
frm.ShowDialog();
if (frm.time != 0)
{
string name = dataGridView1.CurrentRow.Cells[0].Value.ToString();
int deku = Int32.Parse(name);
string constring = "server=localhost;database=dbhorizon;uid=root;password=1234";
string Query = "update tblUserIdd set User_Available = 'Ongoing' where User_ID='" + deku + "' ";
MySqlConnection conDatabase = new MySqlConnection(constring);
MySqlCommand cmdDatabase = new MySqlCommand(Query, conDatabase);
MySqlDataReader myReader;
conDatabase.Open();
myReader = cmdDatabase.ExecuteReader();
string id = dataGridView1.CurrentRow.Cells[0].Value.ToString();
string naem = dataGridView1.CurrentRow.Cells[1].Value.ToString();
string field = dataGridView1.CurrentRow.Cells[2].Value.ToString();
f = frm.time;
if (stdex == 0)
{
startTime[stdex] = DateTime.Now;
stdex++;
}
else if (stdex >= 1)
{
startTime[stdex] = DateTime.Now;
stdex++;
}
secondss = string.Format("{0:t}", DateTime.Now);
string[] row = { id, naem, field, secondss, frm.eta,custb, f.ToString() };
var listViewItem = new ListViewItem(row);
listView1.Items.Add(listViewItem);
dgvref();
}
}
here.
I want to show 10 records per page in a datagridview on a window form and user must click next button to show next 10 records. Is it there some property in DataGridview or do i need to create a custom control.
What i need to do to achieve this.
Here's a simple working example, where a
BindingNavigator GUI control uses a
BindingSource object to
identify page breaks, by setting its DataSource to a custom subclass of IListSource.
(Thanks to this answer for
the key idea.) When the user clicks the "next page" button, the BindingNavigator fires bindingSource1_CurrentChanged and your code can fetch the desired records. Instructions:
Create a Windows Forms application
Drag onto the form a BindingNavigator, a DataGridView, and a BindingSource
Replace Form1.cs with the following code:
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace PagedDataGridView
{
public partial class Form1 : Form
{
private const int totalRecords = 43;
private const int pageSize = 10;
public Form1()
{
InitializeComponent();
dataGridView1.Columns.Add(new DataGridViewTextBoxColumn { DataPropertyName = "Index" });
bindingNavigator1.BindingSource = bindingSource1;
bindingSource1.CurrentChanged += new System.EventHandler(bindingSource1_CurrentChanged);
bindingSource1.DataSource = new PageOffsetList();
}
private void bindingSource1_CurrentChanged(object sender, EventArgs e)
{
// The desired page has changed, so fetch the page of records using the "Current" offset
int offset = (int)bindingSource1.Current;
var records = new List<Record>();
for (int i = offset; i < offset + pageSize && i < totalRecords; i++)
records.Add(new Record { Index = i });
dataGridView1.DataSource = records;
}
class Record
{
public int Index { get; set; }
}
class PageOffsetList : System.ComponentModel.IListSource
{
public bool ContainsListCollection { get; protected set; }
public System.Collections.IList GetList()
{
// Return a list of page offsets based on "totalRecords" and "pageSize"
var pageOffsets = new List<int>();
for (int offset = 0; offset < totalRecords; offset += pageSize)
pageOffsets.Add(offset);
return pageOffsets;
}
}
}
}
Here is my solution : It took me almost a year to find it and proud of this one
public class SuperGrid : DataGridView
{
public int PageSize
{
get
{
return _pageSize;
}
set
{
_pageSize = value;
}
}
public int _pageSize = 10;
BindingSource bs = new BindingSource();
BindingList<DataTable> tables = new BindingList<DataTable>();
public void SetPagedDataSource(DataTable dataTable, BindingNavigator bnav)
{
DataTable dt = null;
int counter = 1;
foreach (DataRow dr in dataTable.Rows)
{
if (counter == 1)
{
dt = dataTable.Clone();
tables.Add(dt);
}
dt.Rows.Add(dr.ItemArray);
if (PageSize < ++counter )
{
counter = 1;
}
}
bnav.BindingSource = bs;
bs.DataSource = tables;
bs.PositionChanged += bs_PositionChanged;
bs_PositionChanged(bs, EventArgs.Empty);
}
void bs_PositionChanged(object sender, EventArgs e)
{
this.DataSource = tables[bs.Position];
}
}
How to use it? Add above code to your project, drag the Supergrid and a bindingnavigator control to your win form .
superGrid1.PageSize = 5;
DataTable dt = DataProvider.ExecuteDt("select * from test order by col");
superGrid1.SetPagedDataSource(dt, bindingNavigator1);
And you get a paged Datagridview with data binding without much hastle/
Implement Paging DataGridView in Windows Forms (WinForms) Application using C# and VB.Net, this is another solution :
https://www.aspsnippets.com/Articles/Implement-Paging-DataGridView-in-Windows-Forms-WinForms-Application-using-C-and-VBNet.aspx
In this article It will be explained how to implement Paging DataGridView in Windows Forms (WinForms) Application using C# and VB.Net.
DataGridView control in Windows Forms (WinForms) Application does not have paging capabilities and hence Custom Paging using Stored Procedure needs to be implemented.
The Stored Procedure accepts PageIndex and PageSize as input parameters in order to fetch the records for the desired page index. In order to populate the Pager in front end, the total number of records in the table is needed which is fetched using the RecordCount Output parameter.
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
CREATE PROCEDURE [dbo].[GetCustomersPageWise]
#PageIndex INT = 1
,#PageSize INT = 10
,#RecordCount INT OUTPUT
AS
BEGIN
SET NOCOUNT ON;
SELECT ROW_NUMBER() OVER
(
ORDER BY [CustomerID] ASC
)AS RowNumber
,[CustomerID]
,[ContactName]
,[Country]
INTO #Results
FROM [Customers]
SELECT #RecordCount = COUNT(*)
FROM #Results
SELECT [CustomerID]
,[ContactName]
,[Country]
FROM #Results
WHERE RowNumber BETWEEN(#PageIndex -1) * #PageSize + 1 AND(((#PageIndex -1) * #PageSize + 1) + #PageSize) - 1
DROP TABLE #Results
END
Initially the value of the PageSize is set to 5 and the PageIndex is set as 1. The value of the RecordCount Output parameter and PageIndex are passed to the PopulatePager method (discussed later).
C#
//Set the Page Size.
int PageSize = 5;
private void Form1_Load(object sender, EventArgs e)
{
this.BindGrid(1);
}
private void BindGrid(int pageIndex)
{
string constring = #"Data Source=.\SQL2005;Initial Catalog=Northwind;Integrated Security=true";
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("GetCustomersPageWise", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#PageIndex", pageIndex);
cmd.Parameters.AddWithValue("#PageSize", PageSize);
cmd.Parameters.Add("#RecordCount", SqlDbType.Int, 4);
cmd.Parameters["#RecordCount"].Direction = ParameterDirection.Output;
con.Open();
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
dataGridView1.DataSource = dt;
con.Close();
int recordCount = Convert.ToInt32(cmd.Parameters["#RecordCount"].Value);
this.PopulatePager(recordCount, pageIndex);
}
}
}
Each dynamic Button is assigned a click event handler, when the Button is clicked the value of its Name is passed as PageIndex parameter to the BindGrid function, which populates the DataGridView with the new set of records.
C#
private void PopulatePager(int recordCount, int currentPage)
{
List<Page> pages = new List<Page>();
int startIndex, endIndex;
int pagerSpan = 5;
//Calculate the Start and End Index of pages to be displayed.
double dblPageCount = (double)((decimal)recordCount / Convert.ToDecimal(PageSize));
int pageCount = (int)Math.Ceiling(dblPageCount);
startIndex = currentPage > 1 && currentPage + pagerSpan - 1 < pagerSpan ? currentPage : 1;
endIndex = pageCount > pagerSpan ? pagerSpan : pageCount;
if (currentPage > pagerSpan % 2)
{
if (currentPage == 2)
{
endIndex = 5;
}
else
{
endIndex = currentPage + 2;
}
}
else
{
endIndex = (pagerSpan - currentPage) + 1;
}
if (endIndex - (pagerSpan - 1) > startIndex)
{
startIndex = endIndex - (pagerSpan - 1);
}
if (endIndex > pageCount)
{
endIndex = pageCount;
startIndex = ((endIndex - pagerSpan) + 1) > 0 ? (endIndex - pagerSpan) + 1 : 1;
}
//Add the First Page Button.
if (currentPage > 1)
{
pages.Add(new Page { Text = "First", Value = "1" });
}
//Add the Previous Button.
if (currentPage > 1)
{
pages.Add(new Page { Text = "<<", Value = (currentPage - 1).ToString() });
}
for (int i = startIndex; i <= endIndex; i++)
{
pages.Add(new Page { Text = i.ToString(), Value = i.ToString(), Selected = i == currentPage });
}
//Add the Next Button.
if (currentPage < pageCount)
{
pages.Add(new Page { Text = ">>", Value = (currentPage + 1).ToString() });
}
//Add the Last Button.
if (currentPage != pageCount)
{
pages.Add(new Page { Text = "Last", Value = pageCount.ToString() });
}
//Clear existing Pager Buttons.
pnlPager.Controls.Clear();
//Loop and add Buttons for Pager.
int count = 0;
foreach (Page page in pages)
{
Button btnPage = new Button();
btnPage.Location = new System.Drawing.Point(38 * count, 5);
btnPage.Size = new System.Drawing.Size(35, 20);
btnPage.Name = page.Value;
btnPage.Text = page.Text;
btnPage.Enabled = !page.Selected;
btnPage.Click += new System.EventHandler(this.Page_Click);
pnlPager.Controls.Add(btnPage);
count++;
}
}
private void Page_Click(object sender, EventArgs e)
{
Button btnPager = (sender as Button);
this.BindGrid(int.Parse(btnPager.Name));
}
public class Page
{
public string Text { get; set; }
public string Value { get; set; }
public bool Selected { get; set; }
}
Another Approach for this problem:
public class PagedGrid : DataGridView
{
Paging pg;
SQLQuery s;
public void SetPagedDataSource( SQLQuery s, BindingNavigator bnav)
{
this.s = s;
int count = DataProvider.ExecuteCount(s.CountQuery);
pg = new Paging(count, 5);
bnav.BindingSource = pg.BindingSource;
pg.BindingSource.PositionChanged += new EventHandler(bs_PositionChanged);
//first page
string q = s.GetPagingQuery(pg.GetStartRowNum(1), pg.GetEndRowNum(1), true);
DataTable dt = DataProvider.ExecuteDt(q);
DataSource = dt;
}
void bs_PositionChanged(object sender, EventArgs e)
{
int pos = ((BindingSource)sender).Position + 1;
string q = s.GetPagingQuery(pg.GetStartRowNum(pos), pg.GetEndRowNum(pos), false);
DataTable dt = DataProvider.ExecuteDt(q);
DataSource = dt;
}
public void UpdateData()
{
DataTable dt = (DataTable)DataSource;
using (SqlConnection con = new SqlConnection(DataProvider.conStr))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(s.CompleteQuery, con);
SqlCommandBuilder cb = new SqlCommandBuilder(da);
da.UpdateCommand = cb.GetUpdateCommand();
da.InsertCommand = cb.GetInsertCommand();
da.DeleteCommand = cb.GetDeleteCommand();
da.Update(dt);
}
MessageBox.Show("The changes are committed to database!");
}
}
/// <summary>
/// Gives functionality of next page , etc for paging.
/// </summary>
public class Paging
{
public int _totalSize = 0;
private int _pageSize = 0;
public int TotalSize
{
get
{
return _totalSize;
}
set
{
if (value <= 0)
{
throw new ArgumentException();
}
_totalSize = value;
}
}
public int PageSize
{
get
{
return _pageSize;
}
set
{
if (value <= 0)
{
throw new ArgumentException();
}
_pageSize = value;
}
}
public Paging(int totalSize, int pageSize)
{
this.TotalSize = totalSize;
this.PageSize = pageSize;
}
public int GetStartRowNum(int PageNum)
{
if (PageNum < 1)
{
throw new Exception("Page number starts at 1");
}
if (PageNum > GetPageCount())
{
throw new Exception("Page number starts at " + GetPageCount().ToString());
}
return 1 + ((PageNum - 1) * _pageSize);
}
public int GetEndRowNum(int PageNum)
{
if (PageNum < 1)
{
throw new Exception("Page number starts at 1");
}
if (PageNum > GetPageCount())
{
throw new Exception("Page number starts at " + GetPageCount().ToString());
}
return _pageSize + ((PageNum - 1) * _pageSize);
}
public int GetPageCount()
{
return (int)Math.Ceiling(TotalSize / (decimal)PageSize);
}
public bool IsFirstPage(int PageNum)
{
if (PageNum == 1)
{
return true;
}
return false;
}
public bool IsLastPage(int PageNum)
{
if (PageNum == GetPageCount())
{
return true;
}
return false;
}
private int _currentPage = 1;
public int CurrentPage
{
get
{
return _currentPage;
}
set
{
_currentPage = value;
}
}
public int NextPage
{
get
{
if (CurrentPage + 1 <= GetPageCount())
{
_currentPage = _currentPage + 1;
}
return _currentPage;
}
}
public int PreviousPage
{
get
{
if (_currentPage - 1 >= 1)
{
_currentPage = _currentPage - 1;
}
return _currentPage;
}
}
private BindingSource _bindingSource = null;
public BindingSource BindingSource
{
get
{
if (_bindingSource == null)
{
_bindingSource = new BindingSource();
List<int> test = new List<int>();
for (int i = 0; i < GetPageCount(); i++)
{
test.Add(i);
}
_bindingSource.DataSource = test;
}
return _bindingSource;
}
}
}
/// <summary>
/// Query Helper of Paging
/// </summary>
public class SQLQuery
{
private string IDColumn = "";
private string WherePart = " 1=1 ";
private string FromPart = "";
private string SelectPart = "";
public SQLQuery(string SelectPart, string FromPart, string WherePart, string IDColumn)
{
this.IDColumn = IDColumn;
this.WherePart = WherePart;
this.FromPart = FromPart;
this.SelectPart = SelectPart;
}
public string CompleteQuery
{
get
{
if (WherePart.Trim().Length > 0)
{
return string.Format("Select {0} from {1} where {2} ", SelectPart, FromPart, WherePart);
}
else
{
return string.Format("Select {0} from {1} ", SelectPart, FromPart);
}
}
}
public string CountQuery
{
get
{
if (WherePart.Trim().Length > 0)
{
return string.Format("Select count(*) from {0} where {1} ", FromPart, WherePart);
}
else
{
return string.Format("Select count(*) from {0} ", FromPart);
}
}
}
public string GetPagingQuery(int fromrow, int torow, bool isSerial)
{
fromrow--;
if (isSerial)
{
return string.Format("{0} where {1} >= {2} and {1} <= {3}", CompleteQuery, IDColumn, fromrow, torow);
}
else
{
string select1 = "";
string select2 = "";
if (WherePart.Trim().Length > 0)
{
select1 = string.Format("Select top {3} {0} from {1} where {2} ", SelectPart, FromPart, WherePart, torow.ToString());
select2 = string.Format("Select top {3} {0} from {1} where {2} ", SelectPart, FromPart, WherePart, fromrow.ToString());
}
else
{
select1 = string.Format("Select top {2} {0} from {1} ", SelectPart, FromPart, torow.ToString());
select2 = string.Format("Select top {2} {0} from {1} ", SelectPart, FromPart, fromrow.ToString());
}
if (fromrow <= 1)
{
return select1;
}
else
{
return string.Format("{0} except {1} ", select1, select2);
}
}
}
}
using it:
private void Form1_Load(object sender, EventArgs e)
{
SQLQuery s = new SQLQuery("*", "table", "", "id");
pagedGrid1.SetPagedDataSource(s, bindingNavigator1);
}
Note: The DataPrivier class is not included here , it is a simple class that returns datatable from any source.
Try this,
this code is for OleDb, but also works for SqlServer connections.
The dt (DataTable) object is filled with selected page rows, assuming that page starts with 1 (not 0)
public DataTable getData(string sql, int pgNo, int totalRows)
{
DataTable dt = null;
using (OleDbConnection conn = new OleDbConnection(connStr))
{
try
{
DataSet ds;
conn.Open();
ds = new DataSet();
OleDbDataAdapter adapter = new OleDbDataAdapter(sql, conn);
adapter.Fill(ds, (pgNo-1)*totalRows, totalRows, "Table");
conn.Close();
dt = ds.Tables[0];
}
catch (Exception ex)
{if (conn != null) conn.Dispose();}
return dt;
}
My answer is 10years late and I can't begin to explain why. But I think what is important is that I have something to offer. :D
I love to solve problems in the simplest way possible and by far this is the simplest way I use. If there are any issues with it, am glad to fix it.
using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Drawing;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
SqlDataAdapter pagingAdapter;
DataSet pagingDS;
int scrollVal; // This defines how many more data sets there are to load
int rowsPerPage = 10; // This defines the total number of rows to show
public Form1()
{
InitializeComponent();
scrollVal = 0;
}
private void BtnShowresults_Click(object sender, EventArgs e)
{
string connectionString = "Data Source=.;Initial Catalog=pubs;Integrated Security=True";
string sql = "SELECT * FROM Authors";
SqlConnection connection = new SqlConnection(connectionString);
pagingAdapter = new SqlDataAdapter(sql, connection);
pagingDS = new DataSet();
connection.Open();
//This part will get the total number of records from the query
pagingAdapter.Fill(dataSetProjects);
DataTable dataTable = pagingDS.Tables[0];
int rowCount = Convert.ToInt32(dataTable.Rows.Count);
this.btnShowresults.Tag = rowCount; // We set it to the button tag
pagingAdapter.Fill(pagingDS, scrollVal, rowsPerPage, "Authors_table");
connection.Close();
dataGridView1.DataSource = pagingDS;
dataGridView1.DataMember = "Authors_table";
}
private void btnPrevious_Click(object sender, EventArgs e)
{
if (scrollVal < = 0)
{
scrollVal = 0;
} else
{
scrollVal -= rowsPerPage;
}
pagingDS.Clear();
pagingAdapter.Fill(pagingDS, scrollVal, rowsPerPage, "authors_table");
}
private void BtnNext_Click(object sender, EventArgs e)
{
Button btnShowresults = (Button)pnSearch.Controls["btnShowresults"];
int resCount = Convert.ToInt32(btnShowresults.Tag);
if (scrollVal <= resCount)
{
scrollVal = rowsPerPage;
} else
{
scrollVal = rowsPerPage;
}
pagingDS.Clear();
pagingAdapter.Fill(pagingDS, scrollVal, rowsPerPage, "authors_table");
}
}
}
This code is found on http://csharp.net-informations.com/datagridview/csharp-datagridview-paging.htm. It had a few bugs I needed to fix. Consider this a cleaned up version.
Paging emulation with RadGridView for WinForms is possible, especially if we take full advantage of LINQ. This approach also gives us another advantage - client performance. The data processing (filtering, sorting and paging) is obviously done by the SQL server, which is fully optimized for such things, rather than the application. The client only processes and shows one page at a time, rather than all million records. Here I do not use RadGridView’s Virtual Mode - this is a topic for a more advanced blog post.
this link my help you :paging-with-radgridview
https://www.telerik.com/blogs/emulating-paging-with-radgridview-for-winforms-and-linq-with-1-million-records
and the code is:
private void BindGrid()
{
this.radGridView1.GridElement.BeginUpdate();
IQueryable queryable = new DataClasses1DataContext().MyTables.AsQueryable();
if (!String.IsNullOrEmpty(where))
{
queryable = queryable.Where(where);
}
if (!String.IsNullOrEmpty(orderBy))
{
queryable = queryable.OrderBy(orderBy);
}
radGridView1.DataSource = queryable.Skip(currentPageIndex * pageSize).Take(pageSize);
this.radGridView1.GridElement.EndUpdate(true);
EnableDisablePager();
}
I did manual paging on my datagridview. I hope this helps
private void btnBack_Click(object sender, EventArgs e)
{
int a = int.Parse(lblmin.Text);
int b = int.Parse(lblmax.Text);
int c = a - 100;
int d = b - 100;
if (lblmin.Text != "1")
{
String name = "Main";
String constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
"C:\\BBISDatabase\\Data.xlsx" +
";Extended Properties='Excel 8.0;HDR=YES;';";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand oconn = new OleDbCommand("Select * From [" + name + "$] where IDs between " + c.ToString() + " and " + d.ToString() + "", con);
con.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
DataTable data = new DataTable();
sda.Fill(data);
dgMain.DataSource = data;
lblcount.Text = c.ToString();
lblmax.Text = d.ToString();
}
else
{
btnBack.Visible = false;
}
}
private void btnNext_Click(object sender, EventArgs e)
{
int a = int.Parse(lblmin.Text);
int b = int.Parse(lblmax.Text);
int c = b + 1;
int d = b + 100;
String name = "Main";
String constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
"C:\\BBISDatabase\\Data.xlsx" +
";Extended Properties='Excel 8.0;HDR=YES;';";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand oconn = new OleDbCommand("Select * From [" + name + "$] where IDs between "+c.ToString()+" and "+d.ToString()+"", con);
con.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
DataTable data = new DataTable();
sda.Fill(data);
dgMain.DataSource = data;
lblmin.Text = c.ToString();
lblmax.Text = d.ToString();
btnBack.Visible = true;
}
and i put this code on form_load():
lblmin.Text = "1";