Solved

How to load datagrid with only consecutive records

Posted on 2007-04-09
19
301 Views
Last Modified: 2010-04-15
Hi everyone!
I have a ASP.NET website using C# in the code behind.  I am using Access as a datasource.  I am working with live data that is constantly changing.  I am loading a grid with results from my query.  I need to change my query or rather the way I am loading my datagrid so that only consecutive records load.  If there is a break in the consecutive Entry_Order numbers of the record, I don't want anything beyond that point to load into my datagrid.

For example, this is my query result:

ID    Thread    MSEL      Entry_Order
1         1           A. 1               1
2         1           A. 2               2
4         1           A.5                4
5         1           B.1                5

Since there is a break between Entry_Order 2 and 4, I only want to display  records 1 and 2, not record 4 or 5.  Can someone show me how to display only consecutive records?

I am currently using this to load my grid:
+++++++++++++
ds = new DataSet();
OleDbDataAdapter da = new OleDbDataAdapter(strSQL,con);
try
{
    count=da.Fill(ds);
    if(!bIsError)
    {
        if(count!=0)
       {
      DataGrid1.DataSource=ds;
      DataGrid1.DataBind();
       }
       else
      SendUserAMessage("There are no tasks for you at this time.  Please recheck your tasks at a later time.");
        if(con.State.ToString() == "Open")
        {      con.Close();        }
   }
}

Thanks.  ptslv
0
Comment
Question by:ptslv
19 Comments
 
LVL 12

Expert Comment

by:craskin
ID: 18876631
i'm not that great with C, so hopefully you can get at what i'm saying in VB.

after you fill your dataset (though you should just use a datatable to save memory, loop through the records and remove the extra rows

Dim i as Integer = 0

Do while i < myDataTable.Rows.Count -1
    If myDataTable.Rows(i).Item("Entry_Order") <> i+1 Then
             myDataTable.Rows(i).Remove
    Else
             i+= 1
    End If
Loop

something like that should work.
0
 
LVL 23

Expert Comment

by:Christopher Kile
ID: 18876749
Fill a data table instead of a data set, create another data table, copy the records you want from your original data table to the new data table, then attach that data table to your data set (or simply create a view on the new data table, then bind that view to the data grid).  That second suggestion would mean you have to implement the update/insert handlers yourself.

0
 
LVL 5

Expert Comment

by:kosturdur
ID: 18876770
          DataRow drow = siparisHareketDetayDataTable.Rows[0];
            int counter =(Convert.ToInt32(drow["Entry_Order"].ToString()))
            for (int i = 0; i < siparisHareketDetayDataTable.Rows.Count; i++)
            {
               counter++;
                DataRow drow = siparisHareketDetayDataTable.Rows[i];
                if (counter) == (Convert.ToInt32(drow["Entry_Order"].ToString()))
                {
                  //add to datagrid(fill a dataset then bind) or a listview
                  ListViewItem lvi = new ListViewItem(drow["ID   "].ToString());
                  lvi.SubItems.Add(drow["Thread    "].ToString());
                  lvi.SubItems.Add(drow["MSEL      "].ToString());
                  lvi.SubItems.Add(drow["Entry_Order"].ToString());
                  myListview.Items.Add(lvi);
                }
           }
or in sql look the link below
http://www.sqlteam.com/item.asp?ItemID=1491
HTH,
Kosturdur
0
 

Author Comment

by:ptslv
ID: 18876801
Thanks for the quick responses.  I will try them and see what works best for me.

ptslv
0
 
LVL 5

Expert Comment

by:kosturdur
ID: 18876804
In http://www.sqlteam.com/item.asp?ItemID=1491
if you get the row number, you can make select top xxx sql statement.
Kosturdur
0
 

Author Comment

by:ptslv
ID: 18877715
kosturdur-

I have tried your method, but it does not limit the list to only records with consecutive Entry_Order numbers.  Entire query results are showing.

I have tried setting up craskin's code but am getting errors;  Here's what I have:

da.Fill(ds,dataTableName);
DataTable myDataTable = ds.Tables[dataTableName];
DataRow drow = myDataTable.Rows[0];
 int i = 0;
while (i < myDataTable.Rows.Count -1)
{
    if( myDataTable.Rows.Item["Entry_Order"] != i+1)
    {
        myDataTable.Rows.Remove();  
    }
    else
        i+=1;
 }

myDataTable.Rows.Item["Entry_Order"]  throws the error: System.Data.DataRow Collection does not contain a definition for 'Item'

myDataTable.Rows.Remove();   throws an error - invalid arguments and cannot convert from  int to System.Data.DataRow

any suggestions?

ptslv
0
 
LVL 5

Expert Comment

by:kosturdur
ID: 18879032
if you don't want to see the non-consecutive don't add to the listview. Sorry but I couldn't understand what you really mean?
If your data is like;
1 2 4 5 you can only show 1-2
Could you write the code that you tried my solution?
------------
In craskin's code if you delete(remove) a row, I think you forgot to increase i.
Kosturdur
0
 

Author Comment

by:ptslv
ID: 18882214
Kosturdur-
This is what I have from your code, but the Listview stuff throws errors:  I think I have too much stuff here but I am trying to weed it out.  I had it working at one point to show all the rows but I broke it somewhere when I tried to remove the unwanted records:

string dataTableName = "UserTasks";
    DataTable myDataTable = ds.Tables[dataTableName];

    try
    {
       count=da.Fill(ds);  // trying something different - still good
//****************************************************************************
//new datatable stuff added 4/9/07

           DataRow drow = myDataTable.Rows[0];
            int counter =(Convert.ToInt32(drow["Entry_Order"].ToString()));
            for (int i = 0; i < myDataTable.Rows.Count; i++)
            {
               counter++;
                drow = myDataTable.Rows[i];
                if ((counter) == (Convert.ToInt32(drow["Entry_Order"].ToString())))
                {
                  //add to datagrid(fill a dataset then bind) or a listview
                  ListViewItem lvi = new ListViewItem(drow["ID"].ToString());
                  lvi.SubItems.Add(drow["Thread"].ToString());
                  lvi.SubItems.Add(drow["MSEL"].ToString());
                  lvi.SubItems.Add(drow["Entry_Order"].ToString());
                  myListview.Items.Add(lvi);
                }
           }


      if(!bIsError)
      {
          if(count!=0)
          {
                   DataGrid1.DataSource=ds;
                   DataGrid1.DataBind();
          }
          else
             SendUserAMessage("There are no tasks at this time.  Please recheck your tasks at a later time.");

          if(con.State.ToString() == "Open")
          {con.Close();}
      }
                      ......the erst of the try/catch
ptslv

0
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 
LVL 5

Expert Comment

by:kosturdur
ID: 18883897
hi ptslv,
--If your table is like that;
*********************Table crate SQL BEGINS******************************
/****** Object:  Table [dbo].[UserTasks]    Script Date: 04/10/2007 20:13:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[UserTasks](
      [ID] [int] IDENTITY(1,1) NOT NULL,
      [Thread] [int] NOT NULL,
      [MSEL] [nchar](10) COLLATE Turkish_CI_AS NOT NULL,
      [Entry_Order] [int] NOT NULL,
 CONSTRAINT [PK_UserTasks] PRIMARY KEY CLUSTERED
(
      [ID] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
*********************Table crate SQL ENDS*********************************
--And your data is like;
*********************Data BEGINS*********************************************
ID    Thread    MSEL      Entry_Order
1         1           A. 1               1
2         1           A. 2               2
4         1           A.5                4
5         1           B.1                5
*********************Data ENDS***********************************************
--The code below works;
--You must have a form with a button1 and datagridview1(do not set it's datasource just drop a datagridview) and a dataset2 of your table named UserTasks;
--On button1_Click event of button1 write this code.
************************CODE BEGINS*************************************
        private void button1_Click(object sender, EventArgs e)
        {
            DataSet2TableAdapters.UserTasksTableAdapter da = new WindowsApplication4.DataSet2TableAdapters.UserTasksTableAdapter();
            DataSet2.UserTasksDataTable dtUserTasks = new DataSet2.UserTasksDataTable();
            da.Fill(dtUserTasks);
            DataTable dt = dtUserTasks.Copy();
            DataRow drow = dt.Rows[0];
            int value = Convert.ToInt32(drow["Entry_Order"].ToString());
            bool consecutiveRecordFound = false;
            int i = 1;
            while (i < dt.Rows.Count)
            {
                drow = dt.Rows[i];
                if (Convert.ToInt32(drow["Entry_Order"].ToString()) != value + 1)
                {
                    if (consecutiveRecordFound)
                    {
                        dt.Rows[i].Delete();
                    }
                    else
                    {
                        value = Convert.ToInt32(drow["Entry_Order"].ToString());
                        dt.Rows[i-1].Delete();
                    }
                }
                else
                {
                    consecutiveRecordFound = true;
                    value = Convert.ToInt32(drow["Entry_Order"].ToString());
                }
                i++;
            }
            if (consecutiveRecordFound)
            {
                dataGridView1.DataSource = dt;
            }
            else
            {
           SendUserAMessage("There are no tasks at this time.  Please recheck your tasks at a later time.");
            }
        }
************************CODE ENDS*************************************

The error In craskin's code if you delete(remove) a row, the row still there with no data that means you forgot to increase i.
Kosturdur
0
 

Author Comment

by:ptslv
ID: 18884066
My table has more fields to it.  Those are the major fields I look for in my query.  I have them in an editable datagrid.  My customer has users who are assigned tasks, and only wants the users to see consecutive tasks.  For instance, if User1 has Entry_Orders 1,2,4,5, and User2 has Entry_Order 5, User1 can only view and do the first 2 tasks.  Then User 2 does his task.  Then User1 goes back in and sees his next 2 tasks and completes them.  That is the cycle.  There may be tasks in between which are assigned to a different user, and that task has to be completed before the next can be done.  

So the code I need has to be able to work with an editable datagrid.

Thanks.  ptslv
0
 

Author Comment

by:ptslv
ID: 18884105
By the way, this is an ASP.NET web application, not a Windows application.  Your code is throwing a bunch of errors!

ptslv
0
 

Author Comment

by:ptslv
ID: 18897138
Kosturdur-

I adjusted your code and ran it but only the first record loaded into the grid.  This is my code now:

OleDbConnection con = new OleDbConnection(strConnection2);
strSQL = "Select.....";
OleDbDataAdapter da2 = new OleDbDataAdapter(strSQL,con);
ds2 = new DataSet();
DataTable dtUserTasks = new DataTable();
da2.Fill(dtUserTasks);
DataTable dt = dtUserTasks.Copy();
DataRow drow = dt.Rows[0];
int value = Convert.ToInt32(drow["Entry_Order"].ToString());
bool consecutiveRecordFound = false;
int i = 1;
while (i < dt.Rows.Count)
    {
        drow = dt.Rows[i];
        if (Convert.ToInt32(drow["Entry_Order"].ToString()) != value + 1)
        {
       if (consecutiveRecordFound)
       {
                             dt.Rows[i].Delete();
       }
       else
       {
               value = Convert.ToInt32(drow["Entry_Order"].ToString());
               dt.Rows[i-1].Delete();
       }
            }
            else
            {
       consecutiveRecordFound = true;
       value = Convert.ToInt32(drow["Entry_Order"].ToString());
            }
              i++;
    }
    if (consecutiveRecordFound)
    {
            DataGrid1.DataSource = dt;
    }
    else
    {
            SendUserAMessage("There are no tasks at this time.  Please recheck your tasks at a later time.");
    }


ptslv      
0
 
LVL 5

Expert Comment

by:kosturdur
ID: 18907315
I tried my code and worked for windows application. The code looks ok so, maybe the data is wrong. And maybe the connections aren't ok. Why don't you use typed datasets in ASP.Net. Please looked the link below http://www.asp.net/learn/dataaccess/default.aspx?tabid=63 and find the "Creating a Data Access Layer" part http://www.asp.net/learn/dataaccess/tutorial01vb.aspx?tabid=63.
Neverthless, I want to try your code with typed dataset in ASP.Net.
Kosturdur

0
 
LVL 5

Accepted Solution

by:
kosturdur earned 500 total points
ID: 18907428
Ok I tried and it worked in ASP.NET also. I put a gridview. and add a dataset to the project by add new item. And by draging and droping the selected Usertasks MS SQL Server Table from Server Explorer to DataSet(called DataSet1). And On PageLoad I wrote this code;
    protected void Page_Load(object sender, EventArgs e)
    {
        DataSet1TableAdapters.UserTasksTableAdapter da = new DataSet1TableAdapters.UserTasksTableAdapter();
        DataSet1.UserTasksDataTable dtUserTasks = new DataSet1.UserTasksDataTable();
        da.Fill(dtUserTasks);
        DataTable dt = dtUserTasks.Copy();
        DataRow drow = dt.Rows[0];
        int value = Convert.ToInt32(drow["Entry_Order"].ToString());
        bool consecutiveRecordFound = false;
        int i = 1;
        while (i < dt.Rows.Count)
        {
            drow = dt.Rows[i];
            if (Convert.ToInt32(drow["Entry_Order"].ToString()) != value + 1)
            {
                if (consecutiveRecordFound)
                {
                    dt.Rows[i].Delete();
                }
                else
                {
                    value = Convert.ToInt32(drow["Entry_Order"].ToString());
                    dt.Rows[i-1].Delete();
                }
            }
            else
            {
                consecutiveRecordFound = true;
                value = Convert.ToInt32(drow["Entry_Order"].ToString());
            }
            i++;
        }
        if (consecutiveRecordFound)
        {
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
        else
        {
            //SendUserAMessage("There are no tasks at this time.  Please recheck your tasks at a later time.");
        }
    }

the result is;
ID Thread MSEL Entry_Order
1 1 MSEL1  1
2 2 MSEL2  2

Kosturdur
0
 

Author Comment

by:ptslv
ID: 18913760
I am still working on this - it was pushed to the back burner!  I will comment when I have a chance!  Thanks.

ptslv
0
 
LVL 5

Expert Comment

by:kosturdur
ID: 19332147
I think I gived the right answer for both windows and web application. I also tried the codes and both are working.  
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Error on link 14 38
app server have enough resources... 2 24
C#.NET and microsoft certification. 3 34
Convert html page to a php post email form automatically? 10 29
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
This tutorial demonstrates how to identify and create boundary or building outlines in Google Maps. In this example, I outline the boundaries of an enclosed skatepark within a community park.  Login to your Google Account, then  Google for "Google M…
The is a quite short video tutorial. In this video, I'm going to show you how to create self-host WordPress blog with free hosting service.

920 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now