Pagination c# aspx help using listview - c#

protected void showproduct()
{
int pagecount = 0;
int currentpage = 0;
if (Request.QueryString["page"] != null)
{
currentpage = Int32.Parse(Request.QueryString["page"]);
}
Response.Write("</br>"+currentpage);
MySqlConnection dbcon = new MySqlConnection("Server=localhost; Database=ip; Uid=root; Password=root;");
MySqlCommand dbcmd = new MySqlCommand();
dbcon.Open();
dbcmd.Connection = dbcon;
for (int q = 0; q <= currentpage; q++)
{
if (currentpage >2 )
{
pagecount = q * 3;
}else if(currentpage==2){
pagecount = 3;
}
}
dbcmd.CommandText = "select * from product where id >" + pagecount + " order by id asc limit 3";
//dbcmd.CommandText = "select * from product limit "+ pagecount +",3";
MySqlDataAdapter adapter = new MySqlDataAdapter(dbcmd.CommandText, dbcon);
DataTable t = new DataTable();
adapter.Fill(t);
ListView1.DataSource = t;
ListView1.DataBind();
}
http://prntscr.com/d83mgh
In page 2 I can view
http://prntscr.com/d83msj
When clicked on page 3 nothing is shown
I have like 9 data in my source

I am assuming that the items in the db have continuous ids without holes.
Then you can calculate the first id to be shown using the index of the selected page and the number of items to be shown per page like this:
const int itemsPerPage = 3; // number of items per page to be shown
const int minId = 1; // id of first record in db
// page selected by user in ui
int selectedPage;
if (Request.QueryString["page"] != null) {
// first page has index 0 to simplify the calculation
selectedPage = Int32.Parse(Request.QueryString["page"]) - 1;
}
// id of first record to be shown
int minIdToBeShown = minId + itemsPerPage * selectedPage;
// fetch records including the first record to be shown on the page
dbcmd.CommandText = "select * from product where id >=" + minIdToBeShown
+ " order by id asc limit " + itemsPerPage;

Related

Blocking Collection shows Duplicate entries

I first retrieve Total number of rows in my table (say 100) and then divide them into chunks (say 25). Then I create a task (taskFetch) which fetches rows from MyTable in chunks into DataTable (each containing 25 records) using Parallel.Foreach() method. There's another nested Parallel,Foreach() which uses Partitioner.Create() which retrieves data from each DataTable and Adds it into Blocking Collection (sourceCollection). For testing purpose I output the result on console and it was fine.
But, as I tried to retrieve data from sourceCollection I found duplicate entries. In real I have over 1500,000 records in table. I dont exactly think that duplicate entries are Add-ed but the way I'm Take-ing is something I'm a bit doubtful about.
Code
public async Task BulkMigrationAsync(string clearPVK, string EncZPK)
{
BlockingCollection<MigrationObject> sourceCollection = new BlockingCollection<MigrationObject>();
List<Task> tasksGeneratedPinBlock = new List<Task>();
int rangeFrom = 1;
int recordsInSet = 25;
int rangeTo = 25;
int setsCount = 0;
Dictionary<int, Tuple<int, int>> chunks = new Dictionary<int, Tuple<int, int>>();
SqlConnection conn = new SqlConnection(_Database.ConnectionString);
SqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM MyTable); // Suppose If retrieves 100 rows
// getting total records from MyTable
using (conn)
{
conn.Open();
setsCount = Convert.ToInt32(cmd.ExecuteScalar()) / recordsInSet ; // then setsCount will be 4
conn.Close();
}
for (int i = 0; i < setsCount; i++)
{
chunks.Add(i, new Tuple<int, int>(rangeFrom, rangeTo));
rangeFrom = rangeTo + 1;
rangeTo = rangeTo + recordsInSet;
}
// Each chunk would contain 100000 records to be preocessed later
// chunks => {0, (1, 25)}
// {1, (26, 50)} // a chunk, chunk.Value.Item1 = 26 and chunk.Value.Item2 = 50
// {2, (51, 75)}
// {3, (76, 100)}
// fetching results in dataTable from DB in chunks and ADDING to sourceCollection
Task taskFetch = Task.Factory.StartNew(() =>
{
Parallel.ForEach(chunks, (chunk) =>
{
DataTable dt = new DataTable();
SqlConnection localConn = new SqlConnection(_Database.ConnectionString);
string command = #"SELECT * FROM ( SELECT RELATIONSHIP_NUM, CUST_ID, CODE, BLOCK_NEW, ROW_NUMBER() over (
order by RELATIONSHIP_NUM, CUST_ID) as RowNum FROM MyTable) SUB
WHERE SUB.RowNum BETWEEN chunk.Value.Item1 AND chunk.Value.Item2";
SqlDataAdapter da = new SqlDataAdapter(command, localConn);
try
{
using (da)
using (localConn)
{
da.Fill(dt);
}
}
finally
{
if (localConn.State != ConnectionState.Closed)
localConn.Close();
localConn.Dispose();
}
Parallel.ForEach(Partitioner.Create(0, dt.Rows.Count),
(range, state) =>
{
MigrationObject migSource = new MigrationObject();
for (int i = range.Item1; i < range.Item2; i++)
{
migSource.PAN = dt.Rows[i]["CUST_ID"].ToString();
migSource.PinOffset = dt.Rows[i]["CODE"].ToString();
migSource.PinBlockNew = dt.Rows[i]["BLOCK_NEW"].ToString();
migSource.RelationshipNum = dt.Rows[i]["RELATIONSHIP_NUM"].ToString();
Console.WriteLine(#"PAN " + migSource.PAN + " Rel " + migSource.RelationshipNum
+ " for ranges : " + range.Item1 + " TO " + range.Item2);
sourceCollection.TryAdd(migSource);
}
});
});
});
await taskFetch;
sourceCollection.CompleteAdding();
while (!sourceCollection.IsCompleted)
{
MigrationObject mig;
if (sourceCollection.TryTake(out mig)) // Seems to be the problem area because may be im not handling out
{
await Task.Delay(50);
Console.WriteLine(" Rel " + mig.RelationshipNum + " PAN " + mig.PAN);
}
}
}
My bad, Actually the problem area is :
Parallel.ForEach(Partitioner.Create(0, dt.Rows.Count),
(range, state) =>
{
MigrationObject migSource = new MigrationObject(); // creating the object outside For loop.
for (int i = range.Item1; i < range.Item2; i++)
{
migSource.PAN = dt.Rows[i]["CUST_ID"].ToString();
migSource.PinOffset = dt.Rows[i]["CODE"].ToString();
migSource.PinBlockNew = dt.Rows[i]["BLOCK_NEW"].ToString();
migSource.RelationshipNum = dt.Rows[i]["RELATIONSHIP_NUM"].ToString();
Console.WriteLine(#"PAN " + migSource.PAN + " Rel " + migSource.RelationshipNum
+ " for ranges : " + range.Item1 + " TO " + range.Item2);
sourceCollection.TryAdd(migSource);
}
});
instead I should have included ' MigrationObject migSource = new MigrationObject();' inside For loop :
Parallel.ForEach(Partitioner.Create(0, dt.Rows.Count),
(range, state) =>
{
for (int i = range.Item1; i < range.Item2; i++)
{
MigrationObject migSource = new MigrationObject();
migSource.PAN = dt.Rows[i]["CUST_ID"].ToString();
migSource.PinOffset = dt.Rows[i]["CODE"].ToString();
migSource.PinBlockNew = dt.Rows[i]["BLOCK_NEW"].ToString();
migSource.RelationshipNum = dt.Rows[i]["RELATIONSHIP_NUM"].ToString();
Console.WriteLine(#"PAN " + migSource.PAN + " Rel " + migSource.RelationshipNum
+ " for ranges : " + range.Item1 + " TO " + range.Item2);
sourceCollection.TryAdd(migSource);
}
});

How to you disable CheckBoxList value in the database of array a[]. in the code below

protected void Page_Load(object sender, EventArgs e)
{
SqlDataAdapter cmd = new SqlDataAdapter("select Theatre_size, Theatre_Cost from Theatre where Theatre_Name='" + Request.Cookies["tname"].Value + "'", con);
DataSet ds2 = new DataSet();
cmd.Fill(ds2);
CheckBoxList CbxList = new CheckBoxList();
if (ds2.Tables[0].Rows.Count > 0)
{
Label1.Text = "Ticket Cost RS " + ds2.Tables[0].Rows[0]["Theatre_Cost"].ToString() + "/";
x = Convert.ToInt32(ds2.Tables[0].Rows[0]["Theatre_size"].ToString());
for (int i = 1; i<=x; i++)
{
CbxList.DataSource = ds2;
CbxList.Items.Add(new ListItem(Convert.ToString(i)));
CbxList.ID = i.ToString();
CbxList.Text = i.ToString();
CbxList.RepeatDirection = RepeatDirection.Vertical;
CbxList.RepeatColumns = 10;
}
ph.Controls.Add(CbxList);
}
string u = "";
SqlDataAdapter da = new SqlDataAdapter("select SeatNo from Booking where Theatre_Name='" + Request.Cookies["tname"].Value + "' and ShowDate='" + Request.Cookies["bdate"].Value + "' and ShowTime='" + Request.Cookies["stime"].Value + "'", con);
DataSet ds = new DataSet();
da.Fill(ds);
x = Convert.ToInt32(ds2.Tables[0].Rows[0]["Theatre_size"].ToString());
int rcount = ds.Tables[0].Rows.Count;
if (rcount > 0)
{
rcount = rcount - 1;
while (rcount >= 0)
{
u = ds.Tables[0].Rows[rcount][0].ToString();
//string u = "32,55,1,4,8";
string[] a = u.Split(new char[] { ',' });
int y, z;
for (y = 0; y <= a.Length - 1; y++)
{
for (z = 1; z <= x; z++)
{
CheckBoxList lc = (CheckBoxList)ph.FindControl(z.ToString());
if (lc.Text == a[y])
{
lc.Enabled = false;
}
}
}
rcount = rcount - 1;
}
}
con.Close();
}
In this Code, after i have added CheckBoxList from i=1 to i=Theatre_size taken from SQL database. There is a Column in SQL with SeatNo(varhchar(60) takes values as 1,2,3 in table Booking
These values are stored in an array a[].
ph is the placeholder where checkBoxList is placed.
How will you disable the values of the CheckBoxList for array a[] of the SeatNo that are already saved in the database, while traversing through the values of the CheckBoxList placed in the PlaceHolder ph.
I tried the Below code but, it doesn't seem to work for disabling the CheckBoxList for a[].
string u = "";
SqlDataAdapter da = new SqlDataAdapter("select SeatNo from Booking where Theatre_Name='" + Request.Cookies["tname"].Value + "' and ShowDate='" + Request.Cookies["bdate"].Value + "' and ShowTime='" + Request.Cookies["stime"].Value + "'", con);
DataSet ds = new DataSet();
da.Fill(ds);
x = Convert.ToInt32(ds2.Tables[0].Rows[0]["Theatre_size"].ToString());
int rcount = ds.Tables[0].Rows.Count;
if (rcount > 0)
{
rcount = rcount - 1;
while (rcount >= 0)
{
u = ds.Tables[0].Rows[rcount][0].ToString();
//string u = "32,55,1,4,8";
string[] a = u.Split(new char[] { ',' });
Label2.Text = "hi";
int y, z;
for (y = 0; y <= a.Length - 1; y++)
{
for (z = 1; z <= x; z++)
{
CheckBoxList lc = (CheckBoxList)ph.FindControl(z.ToString());
if (lc.Text == a[y])
{
lc.Enabled = false;
}
}
//CheckBoxList1.Items[1].Enabled = false;
}
rcount = rcount - 1;
}
}
con.Close();
}

Execute array values in query c#

I'm busy with a task program and then I came on to a problem!
Here is my code:
int id = 1;
List<Button> _bListGroups = new List<Button>();
MySqlCommand mcCommandUserID = new MySqlCommand("SELECT * FROM pakket WHERE gebruikersid=#id", _msConnection);
mcCommandUserID.Parameters.AddWithValue("#id", id);
MySqlDataReader msReader = mcCommandUserID.ExecuteReader();
DataTable dtGetUserid = new DataTable();
dtGetUserid.Load(msReader);
string[] nummer = new string[10];
int i = 0;
foreach (DataRow row in dtGetUserid.Rows)
{
nummer[i] = row["groepsid"].ToString();
i++;
}
MySqlCommand msCommandGetGroup = new MySqlCommand("SELECT * FROM groep WHERE id=#id",_msConnection);
msCommandGetGroup.Parameters.AddWithValue("#id", nummer[i]);
MySqlDataReader msGetGroup = msCommandGetGroup.ExecuteReader();
DataTable dtGetGroup = new DataTable();
dtGetGroup.Load(msGetGroup);
int mtop = 10;
int mleft = 15;
int count = 1;
foreach (DataRow dr in dtGetGroup.Rows)
{
Button temp = new Button();
temp.Name = "bt" + dr["id"];
temp.Text = (string)dr["groepsnaam"];
temp.Width = 125;
temp.Height = 125;
temp.Left = mleft;
temp.Top = mtop;
mleft += 127;
if (count == 2)
{
mtop += 125;
mleft = 15;
count = 0;
}
count++;
_bListGroups.Add(temp);
}
return _bListGroups.ToArray();
When i give my array a specific number(like nummer[1]) i get one button back but if I use the variable i, it doesn't give me any buttons. I already tried to debug it but I couldn't solve it.
Note that you are increasing i in the end of every iteration. So in the end i is greater than the last assigned index by 1. Therefore you need i-1:
msCommandGetGroup.Parameters.AddWithValue("#id", nummer[i-1]);
Also you might want to have some prechecks here for edge cases, say when there is no rows in dtGetUserid.Rows.
You've failed to reset your counter.
the variable i is at this stage:
msCommandGetGroup.Parameters.AddWithValue("#id", nummer[i]);
set to an array index which you havent allocated with any values.

Display pictures with their name from database in winforms?

dataGridView1.DataSource = null;
using (SqlConnection myDatabaseConnection = new SqlConnection(myConnectionString.ConnectionString))
{
myDatabaseConnection.Open();
using (SqlCommand mySqlCommand = new SqlCommand("Select Name, Picture from Employee ", myDatabaseConnection))
{
DataSet ds = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(mySqlCommand);
adapter.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
}
}
Instead of using datagridview, How I can display the picture with their Name in the panel or other control from the database something like this format http://static.neatorama.com/images/2008-04/yearbook-project-robot-johnny.gif in win form?
For example I have 7 records in the database, the form will display 7 panels with picture and label. And when I click or select a panel it will dipslay more information such as Address, Contacts, Etc in a textBox. If the records in the database is too many to fit in the form there will be a vertical or horizontal scroll bar.
I suggest you to create the objects you need dynamically. You can use "Location" to position your object.
Example :
int cptx = 0;
int cpty = 0;
for(int i=0; i<ds.Tables[0].Rows.Count;i++)
{
PictureBox currentpic = new PictureBox();
Label currentlabel = new Label();
currentpic.Size = new Size(20,20);
currentlabel.Size = new Size(20,20);
currentpic.BorderStyle = BorderStyle.FixedSingle;
currentlabel.Text = "te";
if(cptx >= 4)
{
cptx = 0;
cpty ++;
}
currentpic.Location= new Point((cptx*25),(cpty*50));
currentlabel.Location = new Point((cptx*25),(cpty*50)+25);
This.Controls.Add(currentpic);
cptx ++;
}
This code should do this :
EDIT : I suggest you to take a look at the "User control", the user control allow you to create you own control. So, the picture and the label will be inside a single control. The advantage to use the user control is the control you will create will be totally reusable for your other windows and/or programs.
Form has only one panel (pnlGrid) and panel's AutoScroll property setted as true;
DataTable dtImage = new DataTable();
dtImage.Columns.Add("Path");
dtImage.Columns.Add("Name");
dtImage.Rows.Add(new object[] { "ImagePath", "ImageText" });
dtImage.Rows.Add(new object[] { "ImagePath", "ImageText" });
dtImage.Rows.Add(new object[] { "ImagePath", "ImageText" });
CreateImageGrid(dtImage);
and method;
private void CreateImageGrid(DataTable dtDataSource)
{
int colCount = 5;
int rowCount = 0;
int imgWidth = 100;
int imgHeight = 100;
int imgPadding = 10;
int lblPadding = 5;
int ind = -1;
PictureBox pic = null;
Label lbl = null;
if (dtDataSource.Rows.Count > colCount)
{
rowCount = Convert.ToInt32(dtDataSource.Rows.Count / colCount);
if (Convert.ToInt32(dtDataSource.Rows.Count % colCount) > 0)
{
rowCount++;
}
}
else
{
rowCount = 1;
}
for (int j = 0; j < rowCount; j++)
{
for (int i = 0; i < colCount && dtDataSource.Rows.Count > ((j * colCount) + i); i++)
{
ind = (j * colCount) + i;
pic = new PictureBox();
pic.Image = Image.FromFile(dtDataSource.Rows[ind]["Path"].ToString());
pnlGrid.Controls.Add(pic);
pic.Width = imgWidth;
pic.Height = imgHeight;
pic.Top = (j * (imgHeight + imgPadding)) + imgPadding;
pic.Left = (i * (imgWidth + imgPadding)) + imgPadding;
lbl = new Label();
lbl.Text = dtDataSource.Rows[ind]["Name"].ToString();
pnlGrid.Controls.Add(lbl);
lbl.Left = pic.Left;
lbl.Top = pic.Top + pic.Height + lblPadding;
}
}
}
Note: Text lengths may cause problems, you should define some rules.

Add only a percentage of rows to DataTable

So i'm making a program to Audit some of our workers randomly. And i'm trying to make a program to scan our Access DB and pull a percentage of orders. But i want to randomly select the orders, i dont want just the top 5% or something.
static DataTable RandomSelect(double errPercentage,string User)
{
OleDbConnection conn = new OleDbConnection(strAccessConn);
string query = "SELECT ControlNumber FROM Log WHERE User ='" + User + "' AND Log.EndStatus in ('Needs Review', 'Check Search', 'Vision Delivery', 'CA Review', '1TSI To Be Delivered');";
OleDbDataAdapter adapter = new OleDbDataAdapter(query, conn);
DataTable dt = new DataTable();
DataTable dtRandomRows = new DataTable();
try
{
adapter.Fill(dt);
//dtRandomRows = dt.Clone();
Random rDom = new Random();
int i = 0;
for (int ctr = 1; ctr <= dt.Rows.Count; ctr++)
{
i = rDom.Next(1, dt.Rows.Count);
//dtRandomRows.Rows.Add(dt.Rows[i]);
dtRandomRows.ImportRow(dt.Rows[i]);
}
dtRandomRows.AcceptChanges();
}
catch (OleDbException ex)
{
}
return dtRandomRows;
}
The code above works, but it randomly selects rows from the entire table of the ControlNumbers (orders) and puts them all into dtRandomRows. However, i just want this to select the 'errPercentage' or rows randomly...any thoughts?
Random rand = new Random();
// Mark every row as not selected yet.
int[] nonSelectedRows = new int[dt.Rows.Count];
for(int i = 0; i < dt.Rows.Count; i++)
nonSelectedRows[i] = 1;
int numSelected = 0;
int numLeft = dt.Rows.Count;
int targetNum = dt.Rows.Count * errPercentage;
while(numSelected < targetNum)
{
for (int row = 0; row < dt.Rows.Count; row++)
{
// Each record has a 1/numleft chance of getting selected.
boolean isSelected = rand.Next(numLeft) == 0;
// Check to make sure it hasn't already been selected.
if(isSelected && nonSelectedRows[row] > 0)
{
dtRandomRows.ImportRow(dt.Rows[row]);
nonSelectedRows[row] = -1; // Mark this row as selected.
numSelected++;
numLeft--;
}
// We've already found enough to match our targetNum.
if(numSelected >= targetNum)
break;
}
}

Categories