Search Results

Search found 676 results on 28 pages for 'dt'.

Page 17/28 | < Previous Page | 13 14 15 16 17 18 19 20 21 22 23 24  | Next Page >

  • SqlDataAdapter Update is not working in C# wih Sql Server

    - by Ahmed
    I am trying to save data from C# form to Sql server Northwind Orders database, I am only using CustomerID, OrderDate and ShippedDate for data entry. Following is the code to Form load and save button: private void Form1_Load(object sender, EventArgs e) { SetComb(); connectionString = ConfigurationManager.AppSettings["connectionString"]; sqlConnection = new SqlConnection(connectionString); String sqlSelect = "Select OrderID, CustomerID, OrderDate, ShippedDate from Orders"; sqlDataMaster = new SqlDataAdapter(sqlSelect, sqlConnection); sqlConnection.Open(); //=============================================================================== //--- Set up the INSERT Command //=============================================================================== sInsProcName = "prInsert_Order"; insertcommand = new SqlCommand(sInsProcName, sqlConnection); insertcommand.CommandType = CommandType.StoredProcedure; insertcommand.Parameters.Add(new SqlParameter("@nNewID", SqlDbType.Int, 0, ParameterDirection.Output, false, 0, 0, "OrderID", DataRowVersion.Default, null)); insertcommand.UpdatedRowSource = UpdateRowSource.OutputParameters; insertcommand.Parameters.Add(new SqlParameter("@sCustomerID", SqlDbType.NChar, 5,"CustomerID")); insertcommand.Parameters["@sCustomerID"].Value = cmbCust.SelectedValue; insertcommand.Parameters.Add(new SqlParameter("@dtOrderDate", SqlDbType.DateTime, 8,"OrderDate")); insertcommand.Parameters["@dtOrderDate"].Value = dtOrdDt.Text; insertcommand.Parameters.Add(new SqlParameter("@dtShipDate", SqlDbType.DateTime, 8,"ShippedDate")); insertcommand.Parameters["@dtShipDate"].Value = dtShipDt.Text; sqlDataMaster.InsertCommand = insertcommand; //=============================================================================== //--- Set up the UPDATE Command //=============================================================================== sUpdProcName = "prUpdate_Order"; updatecommand = new SqlCommand(sUpdProcName, sqlConnection); updatecommand.CommandType = CommandType.StoredProcedure; updatecommand.Parameters.Add(new SqlParameter("@nOrderID", SqlDbType.Int, 4, "OrderID")); updatecommand.Parameters.Add(new SqlParameter("@dtOrderDate", SqlDbType.DateTime, 8, "OrderDate")); updatecommand.Parameters.Add(new SqlParameter("@dtShipDate", SqlDbType.DateTime, 8, "ShippedDate")); sqlDataMaster.UpdateCommand = updatecommand; //=============================================================================== //--- Set up the DELETE Command //=============================================================================== sDelProcName = "prDelete_Order"; deletecommand = new SqlCommand(sDelProcName, sqlConnection); deletecommand.CommandType = CommandType.StoredProcedure; deletecommand.Parameters.Add(new SqlParameter("@nOrderID", SqlDbType.Int, 4, "OrderID")); sqlDataMaster.DeleteCommand = deletecommand; dt = new DataTable(); sqlDataMaster.FillSchema(dt, SchemaType.Source); ds = new DataSet(); ds.Tables.Add(dt); bs = new BindingSource(); bs.DataSource = ds.Tables[0]; } public void SetComb() { cmbCust.DataSource = dm.GetData("Select * from Customers order by CompanyName"); cmbCust.DisplayMember = "CompanyName"; cmbCust.ValueMember = "CustomerId"; cmbCust.Text = ""; } private void btnSave_Click(object sender, EventArgs e) { sqlDataMaster.Update((DataTable) bs.DataSource); } and Stored Procedures for Insert/Update/Delete set ANSI_NULLS ON set QUOTED_IDENTIFIER ON GO ALTER PROCEDURE [dbo].[prInsert_Order] -- ALTER PROCEDURE prInsert_Order @sCustomerID CHAR(5), @dtOrderDate DATETIME, @dtShipDate DATETIME, @nNewID INT OUTPUT AS SET NOCOUNT ON INSERT INTO Orders (CustomerID, OrderDate, ShippedDate) VALUES (@sCustomerID, @dtOrderDate, @dtShipDate) SELECT @nNewID = SCOPE_IDENTITY() set ANSI_NULLS ON set QUOTED_IDENTIFIER ON GO ALTER PROCEDURE [dbo].[prUpdate_Order] -- ALTER PROCEDURE prUpdate_Order @nOrderID INT, @dtOrderDate DATETIME, @dtShipDate DATETIME AS UPDATE Orders SET OrderDate = @dtOrderDate, ShippedDate = @dtShipDate WHERE OrderID = @nOrderID set ANSI_NULLS ON set QUOTED_IDENTIFIER ON GO ALTER PROCEDURE [dbo].[prDelete_Order] -- ALTER PROCEDURE prDelete_Order @nOrderID INT AS DELETE Orders WHERE OrderID = @nOrderID In the form CustomerID is selected via combobox which has Display property of CustomerName and Value property of CustomerID. But when clicking save button it shows no error, but it also don't save anything in Orders Table of Northwind....dm.GetData is the method of my Data Access Layer class to just get the info and populate CustomerID combobox. Any help with the code is highly appreciated... Thanks Ahmed

    Read the article

  • Finding the maximum value/date across columns

    - by AtulThakor
    While working on some code recently I discovered a neat little trick to find the maximum value across several columns….. So the starting point was finding the maximum date across several related tables and storing the maximum value against an aggregated record. Here's the sample setup code: USE TEMPDB IF OBJECT_ID('CUSTOMER') IS NOT NULL BEGIN DROP TABLE CUSTOMER END IF OBJECT_ID('ADDRESS') IS NOT NULL BEGIN DROP TABLE ADDRESS END IF OBJECT_ID('ORDERS') IS NOT NULL BEGIN DROP TABLE ORDERS END SELECT 1 AS CUSTOMERID, 'FREDDY KRUEGER' AS NAME, GETDATE() - 10 AS DATEUPDATED INTO CUSTOMER SELECT 100000 AS ADDRESSID, 1 AS CUSTOMERID, '1428 ELM STREET' AS ADDRESS, GETDATE() -5 AS DATEUPDATED INTO ADDRESS SELECT 123456 AS ORDERID, 1 AS CUSTOMERID, GETDATE() + 1 AS DATEUPDATED INTO ORDERS .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }   Now the code used a function to determine the maximum date, this performed poorly. After considering pivoting the data I opted for a case statement, this seemed reasonable until I discovered other areas which needed to determine the maximum date between 5 or more tables which didn't scale well. The final solution involved using the value clause within a sub query as followed. SELECT C.CUSTOMERID, A.ADDRESSID, (SELECT MAX(DT) FROM (Values(C.DATEUPDATED),(A.DATEUPDATED),(O.DATEUPDATED)) AS VALUE(DT)) FROM CUSTOMER C INNER JOIN ADDRESS A ON C.CUSTOMERID = A.CUSTOMERID INNER JOIN ORDERS O ON O.CUSTOMERID = C.CUSTOMERID .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } As you can see the solution scales well and can take advantage of many of the aggregate functions!

    Read the article

  • How to create array with unique sprites? in cocos2d iphone

    - by prakash s
    I write the code like this. This displays only one sprite (red colour bubble) with number of times and moving down, but actually I want to display different sprites (different colour bubble) every time and moving down. I also add no of .png images in resource folder of my project. Here I used only 3.png, but I need to display all *.png images (different colour bubbles) in my project but I don't know how to get this. Please help me Thank you. Here is the code: -(void)addTarget { CCSprite *target = [CCSprite spriteWithFile:@"3.png" rect:CGRectMake(0, 0, 256, 256)]; CGSize winSize = [[CCDirector sharedDirector] winSize]; int minY = target.contentSize.height/2; int maxY = winSize.height - target.contentSize.height/2; int rangeY = maxY - minY; int actualY = (arc4random() % rangeY) + minY; // Create the target slightly off-screen along the right edge, // and along a random position along the Y axis as calculated above target.position = ccp(winSize.width + (target.contentSize.width/2), actualY); [self addChild:target]; // Determine speed of the target int minDuration = 4.0; int maxDuration = 12.0; int rangeDuration = maxDuration - minDuration; int actualDuration = (arc4random() % rangeDuration) + minDuration; // Create the actions id actionMove = [CCMoveTo actionWithDuration:actualDuration position:ccp(-target.contentSize.width/2,actualY)]; id actionMoveDone = [CCCallFuncN actionWithTarget:self selector:@selector(spriteMoveFinished:)]; [target runAction:[CCSequence actions:actionMove, actionMoveDone, nil]]; // Add to targets array target.tag = 2; [_targets addObject:target]; } -(void)gameLogic:(ccTime)dt { [self addTarget]; } -(id) init { if( (self=[super initWithColor:ccc4(255,255,255,255)] )) { // Enable touch events self.isTouchEnabled = YES; // Initialize arrays _targets = [[NSMutableArray alloc] init]; _projectiles = [[NSMutableArray alloc] init]; // Get the dimensions of the window for calculation purposes CGSize winSize = [[CCDirector sharedDirector] winSize]; [self schedule:@selector(gameLogic:) interval:1.0]; [self schedule:@selector(update:)]; } return self; } - (void)update:(ccTime)dt { NSMutableArray *projectilesToDelete = [[NSMutableArray alloc] init]; for (CCSprite *projectile in _projectiles) { CGRect projectileRect = CGRectMake(projectile.position.x - (projectile.contentSize.width/2), projectile.position.y - (projectile.contentSize.height/2), projectile.contentSize.width, projectile.contentSize.height); NSMutableArray *targetsToDelete = [[NSMutableArray alloc] init]; for (CCSprite *target in _targets) { CGRect targetRect = CGRectMake(target.position.x - (target.contentSize.width/2), target.position.y - (target.contentSize.height/2), target.contentSize.width, target.contentSize.height); if (CGRectIntersectsRect(projectileRect, targetRect)) { [targetsToDelete addObject:target]; } } for (CCSprite *target in targetsToDelete) { [_targets removeObject:target]; [self removeChild:target cleanup:YES]; _projectilesDestroyed++; if (_projectilesDestroyed > 30) { //GameOverScene *gameOverScene = [GameOverScene node]; // [gameOverScene.layer.label setString:@"You Win!"]; // [[CCDirector sharedDirector] replaceScene:gameOverScene]; } } if (targetsToDelete.count > 0) { [projectilesToDelete addObject:projectile]; } [targetsToDelete release]; } for (CCSprite *projectile in projectilesToDelete) { [_projectiles removeObject:projectile]; [self removeChild:projectile cleanup:YES]; } [projectilesToDelete release]; }

    Read the article

  • Asynchrony in C# 5 (Part I)

    - by javarg
    I’ve been playing around with the new Async CTP preview available for download from Microsoft. It’s amazing how language trends are influencing the evolution of Microsoft’s developing platform. Much effort is being done at language level today than previous versions of .NET. In these post series I’ll review some major features contained in this release: Asynchronous functions TPL Dataflow Task based asynchronous Pattern Part I: Asynchronous Functions This is a mean of expressing asynchronous operations. This kind of functions must return void or Task/Task<> (functions returning void let us implement Fire & Forget asynchronous operations). The two new keywords introduced are async and await. async: marks a function as asynchronous, indicating that some part of its execution may take place some time later (after the method call has returned). Thus, all async functions must include some kind of asynchronous operations. This keyword on its own does not make a function asynchronous thought, its nature depends on its implementation. await: allows us to define operations inside a function that will be awaited for continuation (more on this later). Async function sample: Async/Await Sample async void ShowDateTimeAsync() {     while (true)     {         var client = new ServiceReference1.Service1Client();         var dt = await client.GetDateTimeTaskAsync();         Console.WriteLine("Current DateTime is: {0}", dt);         await TaskEx.Delay(1000);     } } The previous sample is a typical usage scenario for these new features. Suppose we query some external Web Service to get data (in this case the current DateTime) and we do so at regular intervals in order to refresh user’s UI. Note the async and await functions working together. The ShowDateTimeAsync method indicate its asynchronous nature to the caller using the keyword async (that it may complete after returning control to its caller). The await keyword indicates the flow control of the method will continue executing asynchronously after client.GetDateTimeTaskAsync returns. The latter is the most important thing to understand about the behavior of this method and how this actually works. The flow control of the method will be reconstructed after any asynchronous operation completes (specified with the keyword await). This reconstruction of flow control is the real magic behind the scene and it is done by C#/VB compilers. Note how we didn’t use any of the regular existing async patterns and we’ve defined the method very much like a synchronous one. Now, compare the following code snippet  in contrast to the previuous async/await: Traditional UI Async void ComplicatedShowDateTime() {     var client = new ServiceReference1.Service1Client();     client.GetDateTimeCompleted += (s, e) =>     {         Console.WriteLine("Current DateTime is: {0}", e.Result);         client.GetDateTimeAsync();     };     client.GetDateTimeAsync(); } The previous implementation is somehow similar to the first shown, but more complicated. Note how the while loop is implemented as a chained callback to the same method (client.GetDateTimeAsync) inside the event handler (please, do not do this in your own application, this is just an example).  How it works? Using an state workflow (or jump table actually), the compiler expands our code and create the necessary steps to execute it, resuming pending operations after any asynchronous one. The intention of the new Async/Await pattern is to let us think and code as we normally do when designing and algorithm. It also allows us to preserve the logical flow control of the program (without using any tricky coding patterns to accomplish this). The compiler will then create the necessary workflow to execute operations as the happen in time.

    Read the article

  • How to make a stack stable? Need help for an explicit resting contact scheme (2-dimensional)

    - by Register Sole
    Previously, I struggle with the sequential impulse-based method I developed. Thanks to jedediah referring me to this paper, I managed to rebuild the codes and implement the simultaneous impulse based method with Projected-Gauss-Seidel (PGS) iterative solver as described by Erin Catto (mentioned in the reference of the paper as [Catt05]). So here's how it currently is: The simulation handles 2-dimensional rotating convex polygons. Detection is using separating-axis test, with a SKIN, meaning closest points between two polygons is detected and determined if their distance is less than SKIN. To resolve collision, simultaneous impulse-based method is used. It is solved using iterative solver (PGS-solver) as in Erin Catto's paper. Error-correction is implemented using Baumgarte's stabilization (you can refer to either paper for this) using J V = beta/dt*overlap, J is the Jacobian for the constraints, V the matrix containing the velocities of the bodies, beta an error-correction parameter that is better be < 1, dt the time-step taken by the engine, and overlap, the overlap between the bodies (true overlap, so SKIN is ignored). However, it is still less stable than I expected :s I tried to stack hexagons (or squares, doesn't really matter), and even with only 4 to 5 of them, they would swing! Also note that I am not looking for a sleeping scheme. But I would settle if you have any explicit scheme to handle resting contacts. That said, I would be more than happy if you have a way of treating it generally (as continuous collision, instead of explicitly as a special state). Ideas I have tried: Using simultaneous position based error correction as described in the paper in section 5.3.2, turned out to be worse than the current scheme. If you want to know the parameters I used: Hexagons, side 50 (pixels) gravity 2400 (pixels/sec^2) time-step 1/60 (sec) beta 0.1 restitution 0 to 0.2 coeff. of friction 0.2 PGS iteration 10 initial separation 10 (pixels) mass 1 (unit is irrelevant for now, i modified velocity directly<-impulse method) inertia 1/1000 Thanks in advance! I really appreciate any help from you guys!! :) EDIT In response to Cholesky's comment about warm starting the solver and Baumgarte: Oh right, I forgot to mention! I do save the contact history and the impulse determined in this time step to be used as initial guess in the next time step. As for the Baumgarte, here's what actually happens in the code. Collision is detected when the bodies' closest distance is less than SKIN, meaning they are actually still separated. If at this moment, I used the PGS solver without Baumgarte, restitution of 0 alone would be able to stop the bodies, separated by a distance of ~SKIN, in mid-air! So this isn't right, I want to have the bodies touching each other. So I turn on the Baumgarte, where its role is actually to pull the bodies together! Weird I know, a scheme intended to push the body apart becomes useful for the reverse. Also, I found that if I increase the number of iteration to 100, stacks become much more stable, though the program becomes so slow. UPDATE Since the stack swings left and right, could it be something is wrong with my friction model? Current friction constraint: relative_tangential_velocity = 0

    Read the article

  • QT: trouble with qobject_cast

    - by weevilo
    I have derived QGraphicsItem and QGraphicsScene classes. I want the items to be able to call scene() and get a derviedGraphicsItem * instead of a QGraphicsItem *, so I reimplemented QGraphicsScene::itemAt to return a derived pointer. DerivedItem* DerivedScene::itemAt( const QPointF &position, const QTransform &dt ) const { return qobject_cast< DerivedItem * >( QGraphicsScene::itemAt(position, dt) ); } I get the following error (Qt 4.6, GCC 4.4.3 on Ubuntut 10.4) scene.cpp: In member function ‘DerivedItem* DerivedScene::itemAt(qreal, qreal, const QTransform&) const’: scene.cpp:28: error: no matching function for call to ‘qobject_cast(QGraphicsItem*)’ I then noticed QGraphicsItem doesn't inherit QObject, so I made my derived QGraphicsItem class have multiple inheritance from QObject and QGraphicsItem, and after adding the Q_OBJECT macro and rebuilding the project I get the same error. Am I going about this the wrong way? I know it's supposed to be bad design to try to cast a parent class as a child, but in this case it seems like what I want, since my derived item class has new functionality and its objects need a way to call that new functionality on items around themselves, and asking the items scene object with itemAt() seems like the best way - but I need itemAt() to return a pointer of the right type. I can get around this by having the derived items cast the QGraphicsItem * returned by QGraphicsScene::itemAt() using dynamic_cast, but I don't really understand why that works and not qobject_cast, or the benefits or disadvantages to using dynamic_cast vs. qobject_cast.

    Read the article

  • Deselect dates in Web Calendar c#

    - by yomismo
    Hello, I'm trying to select and de-select dates on a C# Web Calendar control. The problem I have is that I can select or deselect dates except when there is only a single date selected. Clicking on it does not trigger the selection changed event, so Ineed to do something on the dayrender event but I'm not sure what or how. Any ideas? TIA Code so far: public static List<DateTime> list = new List<DateTime>(); protected void Calendar1_DayRender(object sender, DayRenderEventArgs e) { if (e.Day.IsSelected == true) { list.Add(e.Day.Date); } Session["SelectedDates"] = list; } protected void Calendar1_SelectionChanged(object sender, EventArgs e) { DateTime selection = Calendar1.SelectedDate; if (Session["SelectedDates"] != null) { List<DateTime> newList = (List<DateTime>)Session["SelectedDates"]; foreach (DateTime dt in newList) { Calendar1.SelectedDates.Add(dt); } if (searchdate(selection, newList)) { Calendar1.SelectedDates.Remove(selection); } list.Clear(); } } public bool searchdate(DateTime date, List<DateTime> dates) { var query = from o in dates where o.Date == date select o; if (query.ToList().Count == 0) { return false; } else { return true; } }

    Read the article

  • Using OLEDB parameters in .NET when connecting to an AS400/DB2

    - by Jeff Stock
    I have been pulling my hair out trying to figure out what I can't get parameters to work in my query. I have the code written in VB.NET trying to do a query to an AS/400. I have IBM Access for Windows installed and I am able to get queries to work, just not with parameters. Any time I include a parameter in my query (ex. @MyParm) it doesn't work. It's like it doesn't replace the parameter with the value it should be. Here's my code: I get the following error: SQL0206: Column @MyParm not in specified tables Here's my code: Dim da As New OleDbDataAdapter Dim dt As New DataTable da.SelectCommand = New OleDbCommand da.SelectCommand.Connection = con da.SelectCommand.CommandText = "SELECT * FROM MyTable WHERE Col1 = @MyParm" With da.SelectCommand.Parameters .Add("@MyParm", OleDbType.Integer, 9) .Item("@MyParm").Value = 5 End With ' I get the error here of course da.Fill(dt) I can replace @MyParm with a literal of 5 and it works fine. What am I missing here? I do this with SQL Server all the time, but this is the first time I am attempting it on an AS400.

    Read the article

  • Difference between DataTable.Load() and DataTable = dataSet.Tables[];

    - by subbu
    Hi All , I have a doubt i use the following piece of code get data from a SQLlite data base and Load it into a data table "SQLiteConnection cnn = new SQLiteConnection("Data Source=" + path); cnn.Open(); SQLiteCommand mycommand = new SQLiteCommand(cnn); string sql = "select Company,Phone,Email,Address,City,State,Zip,Country,Fax,Web from RecordsTable"; mycommand.CommandText = sql; SQLiteDataReader reader = mycommand.ExecuteReader(); dt.Load(reader); reader.Close(); cnn.Close();" In some cases when I try to load it Gives me "Failed to enable constraints exception" But when I tried this below given piece of code for same table and same set of records it worked "SQLiteConnection ObjConnection = new SQLiteConnection("Data Source=" + path); SQLiteCommand ObjCommand = new SQLiteCommand("select Company,Phone,Email,Address,City,State,Zip,Country,Fax,Web from RecordsTable", ObjConnection); ObjCommand.CommandType = CommandType.Text; SQLiteDataAdapter ObjDataAdapter = new SQLiteDataAdapter(ObjCommand); DataSet dataSet = new DataSet(); ObjDataAdapter.Fill(dataSet, "RecordsTable"); dt = dataSet.Tables["RecordsTable"]; " Can any one tell me what is the difference between two

    Read the article

  • Reading text out of textbox in Radgrid

    - by Christophe
    I have a Radgrid with 2 Textboxes and 2 DatePickers. The idea is that I have a grid with a Property name, value, valid from and until. I'm filling the first Textbox myself, the user has to fill in the value, from and until. Filling in the propertynames: (In the pageload) foreach (String s in testProperties) { DataRow dr = dt.NewRow(); dr[0] = s; dr[1] = ""; dr[2] = ""; dr[3] = ""; dt.Rows.Add(dr); } When the user hit "Save" I have to read out all the data he filled in. (In the btnSave click) foreach (GridDataItem dataItem in RadGrid1.Items) { String[] str = new String[3]; str[0] = ((TextBox)dataItem["col2"].FindControl("TextBox2")).Text; str[1] = ((RadDatePicker)dataItem["col3"].FindControl("RadDatePicker1")).SelectedDate.ToString(); str[2] = ((RadDatePicker)dataItem["col4"].FindControl("RadDatePicker2")).SelectedDate.ToString(); properties.Add(((TextBox)dataItem["col1"].FindControl("TextBox1")).Text, str); } Now this is where I have the problem. When i read out the data all my 'str' have the value "" instead the data that the user fills in. Question is, how comes my values in the texboxes remain ""? Or is their a better way to read out the data?

    Read the article

  • C# inaccurate timer?

    - by Ivan
    Hi there, I'm developing an application and I need to get the current date from a server (it differs from the machine's date). I receive the date from the server and with a simple Split I create a new DateTime: globalVars.fec = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, int.Parse(infoHour[0]), int.Parse(infoHour[1]), int.Parse(infoHour[2])); globalVars is a class and fec is a public static variable so that I can access it anywhere in the application (bad coding I know...). Now I need to have a timer checking if that date is equal to some dates I have stored in a List and if it is equal I just call a function. List<DateTime> fechas = new List<DateTime>(); Before having to obtain the date from a server I was using computer's date, so to check if the dates matched I was using this: private void timerDatesMatch_Tick(object sender, EventArgs e) { DateTime tick = DateTime.Now; foreach (DateTime dt in fechas) { if (dt == tick) { //blahblah } } } Now I have the date from the server so DateTime.Now can't be used here. Instead I have created a new timer with Interval=1000 and on tick I'm adding 1 second to globalVars.fec using: globalVars.fec = globalVars.fec.AddSeconds(1); But the clock isn't accurate and every 30 mins the clock loses about 30 seconds. Is there another way of doing what I'm trying to do? I've thought about using threading.timer instead but I need to have access to other threads and non-static functions. Thanks in advance, Ivan

    Read the article

  • Problem converting a byte array into datatable.

    - by kranthi
    Hi, In my aspx page I have a HTML inputfile type which allows user to browse for a spreadsheet.Once the user choses the file to upload I want to read the content of the spreadsheet and store the content into mysql database table. I am using the following code to read the content of the uploaded file and convert it into a datatable in order into insert it into database table. if (filMyFile.PostedFile != null) { // Get a reference to PostedFile object HttpPostedFile myFile = filMyFile.PostedFile; // Get size of uploaded file int nFileLen = myFile.ContentLength; // make sure the size of the file is > 0 if (nFileLen > 0) { // Allocate a buffer for reading of the file byte[] myData = new byte[nFileLen]; // Read uploaded file from the Stream myFile.InputStream.Read(myData, 0, nFileLen); DataTable dt = new DataTable(); MemoryStream st = new MemoryStream(myData); st.Position = 0; System.Runtime.Serialization.IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); dt=(DataTable)formatter.Deserialize(st); } } But I am getting the following error when I am trying to deserialise the byte array into datatable. Binary stream '0' does not contain a valid BinaryHeader. Possible causes are invalid stream or object version change between serialization and deserialization. Could someone please tell me what am I doing wrong? I've also tried converting the bytearray into string ,then converting the string back to byte array and convert into datatable.That is also throwing the same error. Thanks.

    Read the article

  • C# unaccurate timer?

    - by Ivan
    Hi there, I'm developing an application and I need to get the current date from a server (it differs from the machine's date). I receive the date from the server and with a simple Split I create a new DateTime: globalVars.fec = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, int.Parse(infoHour[0]), int.Parse(infoHour[1]), int.Parse(infoHour[2])); globalVars is a class and fec is a public static variable so that I can access it anywhere in the application (bad coding I know...). Now I need to have a timer checking if that date is equal to some dates I have stored in a List and if it is equal I just call a function. List<DateTime> fechas = new List<DateTime>(); Before having to obtain the date from a server I was using computer's date, so to check if the dates matched I was using this: private void timerDatesMatch_Tick(object sender, EventArgs e) { DateTime tick = DateTime.Now; foreach (DateTime dt in fechas) { if (dt == tick) { //blahblah } } } Now I have the date from the server so DateTime.Now can't be used here. Instead I have created a new timer with Interval=1000 and on tick I'm adding 1 second to globalVars.fec using: globalVars.fec = globalVars.fec.AddSeconds(1); But the clock isn't accurate and every 30 mins the clock loses about 30 seconds. Is there another way of doing what I'm trying to do? I've thought about using threading.timer instead but I need to have access to other threads and non-static functions. Thanks in advance, Ivan

    Read the article

  • vant view dataset with microsoft report viewer

    - by Tan
    I have a dataset, the dataset is using a stored procedur to fetch data. i have filled the dataset and everythings is okej.When iam using the debug i can se that the dataset is not empty. but i cant view it with the microsoft report viewer. here is my code please help. private void frmPrint_Load(object sender, EventArgs e) { this.reportViewer1.RefreshReport(); reportViewer1.LocalReport.DataSources.Clear(); GetCauseMachineMatrixTableAdapter adapter = new GetCauseMachineMatrixTableAdapter(); QpNibrolDataSet dataset = new QpNibrolDataSet(); adapter.Fill(dataset.GetCauseMachineMatrix, this.start, this.end); DataTable DT = dataset.Tables[0]; ReportDataSource reportdatasource = new ReportDataSource(); reportdatasource.Name = "RDS_NAME"; reportdatasource.Value = DT; reportViewer1.LocalReport.DataSources.Add(reportdatasource); reportViewer1.LocalReport.Refresh(); reportViewer1.RefreshReport(); } the form is saying "The source of the report definition is not been specified" what im i doing wrong. Idont use a rdlc because when iam trying to view my dataset no columms name show because the Stored procedur i am using requires Parameters. please advice and help my thank you

    Read the article

  • SQL statement with datetimepicker

    - by David Archer
    This should hopefully be a simple one. When using a date time picker in a windows form, I want an SQL statement to be carried out, like so: string sql = "SELECT * FROM Jobs WHERE JobDate = '" + dtpJobDate.Text + "'"; Unfortunately, this doesn't actually provide any results because the JobDate field is stored as a DateTime value. I'd like to be able to search for all records that are on this date, no matter what the time stored may be, any help? New query: SqlDataAdapter da2 = new SqlDataAdapter(); SqlCommand cmd = new SqlCommand(); cmd.CommandText = "SELECT * FROM Jobs WHERE JobDate >= @p_StartDate AND JobDate < @p_EndDate"; cmd.Parameters.Add ("@p_StartDate", SqlDbType.DateTime).Value = dtpJobDate.Value.Date; cmd.Parameters.Add ("@p_EndDate", SqlDbType.DateTime).Value = dtpJobDate.Value.Date.AddDays(1); cmd.Connection = conn; da2.SelectCommand = cmd; da2.Fill(dt); dgvJobDiary.DataSource = dt; Huge thanks for all the help!

    Read the article

  • SQL Server PIVOT with multiple X-axis columns

    - by HeavenCore
    Take the following example data: Payroll Forname Surname Month Year Amount 0000001 James Bond 3 2011 144.00 0000001 James Bond 6 2012 672.00 0000001 James Bond 7 2012 240.00 0000001 James Bond 8 2012 1744.50 0000002 Elvis Presley 3 2011 1491.00 0000002 Elvis Presley 6 2012 189.00 0000002 Elvis Presley 7 2012 1816.50 0000002 Elvis Presley 8 2012 1383.00 How would i PIVOT this on the Year + Month (eg: 201210) but preserve Payroll, Forename & Surname as seperate columns, for example, the above would become: Payroll Forename Surname 201103 201206 201207 201208 0000001 James Bond 144.00 672.00 240.00 1744.50 0000002 Elvis Presley 1491.00 189.00 1816.50 1383.00 I'm assuming that because the Year + Month names can change then i will need to employ dynamic SQL + PIVOT - i had a go but couldnt even get the code to parse, nevermind run - any help would be most appreciated! Edit: What i have so far: INSERT INTO #tbl_RawDateBuffer ( PayrollNumber , Surname , Forename , [Month] , [Year] , AmountPayable ) SELECT PayrollNumber , Surname , Forename , [Month] , [Year] , AmountPayable FROM RawData WHERE [Max] > 1500 DECLARE @Columns AS NVARCHAR(MAX) DECLARE @StrSQL AS NVARCHAR(MAX) SET @Columns = STUFF((SELECT DISTINCT ',' + QUOTENAME(CONVERT(VARCHAR(4), c.[Year]) + RIGHT('00' + CONVERT(VARCHAR(2), c.[Month]), 2)) FROM #tbl_RawDateBuffer c FOR XML PATH('') , TYPE ).value('.', 'NVARCHAR(MAX)'), 1, 1, '') SET @StrSQL = 'SELECT PayrollNumber, ' + @Columns + ' from ( select PayrollNumber , CONVERT(VARCHAR(4), [Year]) + RIGHT(''00'' + CONVERT(VARCHAR(2), [Month]), 2) dt from #tbl_RawDateBuffer ) x pivot ( sum(AmountPayable) for dt in (' + @Columns + ') ) p ' EXECUTE(@StrSQL) DROP TABLE #tbl_RawDateBuffer

    Read the article

  • Static method , Abstract method , Interface method comparision ?

    - by programmerist
    When i choose these methods? i can not decide which one i must prefer or when will i use one of them?which one give best performance? First Type Usage public abstract class _AccessorForSQL { public virtual bool Save(string sp, ListDictionary ld, CommandType cmdType); public virtual bool Update(); public virtual bool Delete(); public virtual DataSet Select(); } class GenAccessor : _AccessorForSQL { DataSet ds; DataTable dt; public override bool Save(string sp, ListDictionary ld, CommandType cmdType) { } public override bool Update() { return true; } public override bool Delete() { return true; } public override DataSet Select() { DataSet dst = new DataSet(); return dst; } Second Type Usage Also i can write it below codes: public class GenAccessor { public Static bool Save() { } public Static bool Update() { } public Static bool Delete() { } } Third Type Usage Also i can write it below codes: public interface IAccessorForSQL { bool Delete(); bool Save(string sp, ListDictionary ld, CommandType cmdType); DataSet Select(); bool Update(); } public class _AccessorForSQL : IAccessorForSQL { private DataSet ds; private DataTable dt; public virtual bool Save(string sp, ListDictionary ld, CommandType cmdType) { } } } I can use first one below usage: GenAccessor gen = New GenAccessor(); gen.Save(); I can use second one below usage: GenAccessor.Save(); Which one do you prefer? When will i use them? which time i need override method ? which time i need static method?

    Read the article

  • How do you parse a paragraph of text into sentences? (perferrably in Ruby)

    - by henry74
    How do you take paragraph or large amount of text and break it into sentences (perferably using Ruby) taking into account cases such as Mr. and Dr. and U.S.A? (Assuming you just put the sentences into an array of arrays) UPDATE: One possible solution I thought of involves using a parts-of-speech tagger (POST) and a classifier to determine the end of a sentence: Getting data from Mr. Jones felt the warm sun on his face as he stepped out onto the balcony of his summer home in Italy. He was happy to be alive. CLASSIFIER Mr./PERSON Jones/PERSON felt/O the/O warm/O sun/O on/O his/O face/O as/O he/O stepped/O out/O onto/O the/O balcony/O of/O his/O summer/O home/O in/O Italy/LOCATION ./O He/O was/O happy/O to/O be/O alive/O ./O POST Mr./NNP Jones/NNP felt/VBD the/DT warm/JJ sun/NN on/IN his/PRP$ face/NN as/IN he/PRP stepped/VBD out/RP onto/IN the/DT balcony/NN of/IN his/PRP$ summer/NN home/NN in/IN Italy./NNP He/PRP was/VBD happy/JJ to/TO be/VB alive./IN Can we assume, since Italy is a location, the period is the valid end of the sentence? Since ending on "Mr." would have no other parts-of-speech, can we assume this is not a valid end-of-sentence period? Is this the best answer to the my question? Thoughts?

    Read the article

  • reCAPTCHA Ajax API + custom theme not working

    - by Felix
    I can't see where I'm going wrong. I've tried everything I could think of, reCAPTCHA is just not working with the Ajax API. Here's what my code looks like: <!-- this is in <head> --> <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script> <script type="text/javascript" src="http://api.recaptcha.net/js/recaptcha_ajax.js"></script> <script type="text/javascript"> $(document).ready(function() { Recaptcha.create("my key here", "recaptcha_widget", { "theme": "custom", "lang": "en", "callback": function() { console.log("callback"); } // this doesn't get called }); }); </script> <!-- ... this is in <body> --> <div id="recaptcha_widget" style="display: none"> <div id="recaptcha_image"></div> <div id="recaptcha_links"> <a href="javascript:Recaptcha.reload()">get another</a> &bull; <a class="recaptcha_only_if_image" href="javascript:Recaptcha.switch_type('audio')">switch to audio</a> <a class="recaptcha_only_if_audio" href="javascript:Recaptcha.switch_type('image')">switch to image</a> &bull; <a href="javascript:Recaptcha.showhelp()">help</a> </div> <dt>Type the words</dt> <dd><input type="text" id="recaptcha_response_field" name="recaptcha_response_field"></dd> </div>

    Read the article

  • Cannot install XML::LibXML module on Windows

    - by Deepak Konidena
    I am trying to use XPath to extract some HTML tags and data and for that I need to use XML::LibXML module. I tried installing it from CPAN shell but it doesn't install. I followed the instructions from CPAN site about the installation, that we need to install libxml2, iconv and zlib wrappers before installing XML::LibXML and it didn't work out. Also, if there is any other simpler module that gets my task done, please let me know. The task at hand: I am searching for a specific <dd> tag on a html page which is really big ( around 5000 - 10000) <dd> and <dt> tags. So, I am writing a script which matches the content within <dd> tag and fetches the content within the corresponding (next) <dt> tag. I wish i could i have been a little more clearer. Any help is greatly appreciated.

    Read the article

  • Error Message, "The Controls collection cannot be modified because the control contains code blocks"

    - by Gogster
    I'm receiving this error on a page that previously worked fine, in fact the only change I've made to the page recently was to add another asp:TextBox and asp:RequiredFieldValidator control. The page already had numerous ASP.NET controls on it, so I cannot see why these extra controls would make a difference, anyway I shall post the code below and hopefully you can see what the error is: <%@ Control Language="C#" AutoEventWireup="true" CodeFile="MeetingGenerator.ascx.cs" Inherits="usercontrols_MeetingGenerator" %> <%@ Register TagPrefix="cc1" Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" %> <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager> <div style="width:498px;height:425px;background-color:#033b2a;text-align:center;padding-top:20px;"> <asp:Label ID="lblDone" CssClass="done" runat="server"></asp:Label> <asp:Panel id="pnlAddReport" runat="server"> <div> <img src="../images/banners/add-meeting.png" alt="Add Report" /> </div> <p> <asp:ValidationSummary ID="ValidationSummary" CssClass="validationsummary" runat="server" /> <asp:TextBox ID="txtTitle" BorderStyle="None" CssClass="watermark" Width="250px" Height="22px" runat="server"></asp:TextBox> <cc1:TextBoxWatermarkExtender ID="TextBoxWatermarkExtender1" TargetControlID="txtTitle" WatermarkCssClass="watermark" WatermarkText=" Meeting title" runat="server"></cc1:TextBoxWatermarkExtender> <asp:RequiredFieldValidator ID="rfvTitle" ControlToValidate="txtTitle" Text="" ErrorMessage="Please enter the title" Display="None" InitialValue="" runat="server"></asp:RequiredFieldValidator> <asp:RequiredFieldValidator ID="rfvTitle1" ControlToValidate="txtTitle" Text="" ErrorMessage="Please enter the title" Display="None" InitialValue=" Meeting title" runat="server"></asp:RequiredFieldValidator> </p> <p> <asp:TextBox ID="txtDate" BorderStyle="None" CssClass="watermark" Width="250px" Height="22px" runat="server"></asp:TextBox> <cc1:CalendarExtender ID="ceDate" TargetControlID="txtDate" Format="dd/MM/yyyy" runat="server"> </cc1:CalendarExtender> <cc1:TextBoxWatermarkExtender ID="TextBoxWatermarkExtender2" TargetControlID="txtDate" WatermarkCssClass="watermark" WatermarkText=" Meeting Date" runat="server"></cc1:TextBoxWatermarkExtender> <asp:RequiredFieldValidator ID="rfvDate" ControlToValidate="txtDate" Text="" ErrorMessage="Please select the meeting date" Display="None" InitialValue="" runat="server"></asp:RequiredFieldValidator> <asp:RequiredFieldValidator ID="rfvDate1" ControlToValidate="txtDate" Text="" ErrorMessage="Please select the meeting date" Display="None" InitialValue=" Meeting Date" runat="server"></asp:RequiredFieldValidator> </p> <p> <asp:TextBox ID="txtMeetingTime" BorderStyle="None" Width="250px" Height="22px" MaxLength="5" runat="server"></asp:TextBox> <cc1:TextBoxWatermarkExtender ID="tweMeetingTime" TargetControlID="txtMeetingTime" WatermarkCssClass="watermark" WatermarkText=" Time (HH:MM)" runat="server"></cc1:TextBoxWatermarkExtender> <asp:RequiredFieldValidator ID="RequiredFieldValidator1" ControlToValidate="txtMeetingTime" Text="" ErrorMessage="Please enter the meeting time" Display="None" InitialValue="" runat="server"></asp:RequiredFieldValidator> <asp:RequiredFieldValidator ID="RequiredFieldValidator11" ControlToValidate="txtMeetingTime" Text="" ErrorMessage="Please enter the meeting time" Display="None" InitialValue=" Time (HH:MM)" runat="server"></asp:RequiredFieldValidator> </p> <p> <asp:TextBox ID="txtLocation" BorderStyle="None" CssClass="watermark" Width="250px" Height="22px" runat="server"></asp:TextBox> <cc1:TextBoxWatermarkExtender ID="TextBoxWatermarkExtender3" TargetControlID="txtLocation" WatermarkCssClass="watermark" WatermarkText=" Location" runat="server"></cc1:TextBoxWatermarkExtender> <asp:RequiredFieldValidator ID="rfvLocation" ControlToValidate="txtLocation" Text="" ErrorMessage="Please enter the location" Display="None" InitialValue="" runat="server"></asp:RequiredFieldValidator> <asp:RequiredFieldValidator ID="rfvLocation1" ControlToValidate="txtLocation" Text="" ErrorMessage="Please enter the location" Display="None" InitialValue=" Location" runat="server"></asp:RequiredFieldValidator> </p> <p> <asp:ImageButton ID="btnAddMeeting" ImageUrl="/images/buttons/addmeeting-btn.gif" runat="server" OnClick="btnAddMeeting_Click" /> </p> <p> </p> </asp:Panel> </div> <%@ Master Language="C#" MasterPageFile="/masterpages/Master.master" AutoEventWireup="true" %> <asp:content ContentPlaceHolderId="additionalhead" runat="server"> </asp:content> <asp:content ContentPlaceHolderId="additionalbody" runat="server"> <umbraco:Macro Alias="AddMeeting" runat="server"></umbraco:Macro> </asp:content> <asp:content ContentPlaceHolderId="bodyContent" runat="server"> </asp:content> <%@ Master Language="C#" AutoEventWireup="true" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title><umbraco:Item field="title" runat="server"></umbraco:Item></title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script> <script type="text/javascript" src="/js/jQueryString-2.0.2-Min.js"></script> <link rel="stylesheet" type="text/css" href="/css/Styles.css" /> <link rel="stylesheet" type="text/css" href="/css/Layout.css" /> <link rel="stylesheet" type="text/css" href="/css/Forms.css" /> <script type="text/javascript" language="javascript"> $(document).ready(function () { $('#uploadAgenda').hide(); $('#uploadMinutes').hide(); $('#<%=txtSearchEAA.ClientID%>').val('Search EAA'); var st = $.getQueryString({ ID:"search" }); if (st != '') { $('#<%=txtSearchEAA.ClientID%>').val(st); }; $('#<%=txtSearchEAA.ClientID%>').click(function() { $('#<%=txtSearchEAA.ClientID%>').val(''); }); }); </script> <script type="text/C#" runat="server"> protected void btnSearch_Click(object sender, EventArgs e) { Response.Redirect("/members/search-results?search=" + txtSearchEAA.Text); } </script> <asp:ContentPlaceHolder id="additionalhead" runat="server"></asp:ContentPlaceHolder> <umbraco:Item field="AdditionalHead" runat="server"></umbraco:Item> </head> <body style="background-color:#e5e5e5;"> <script runat="server"> protected void btnLogout_Click(object sender, EventArgs e) { FormsAuthentication.SignOut(); Response.Redirect("/login"); } </script> <form id="form1" runat="server"> <asp:ContentPlaceHolder id="additionalbody" runat="server"></asp:ContentPlaceHolder> <div class="wrapper"> <div class="content"> <div class="banner"> <div class="bannerSearchSpacer"> <a href="/home"><h1><span>EAA</span></h1></a> </div> <div class="aboutEAA"> &nbsp; </div> <div class="bannerSearchAligns"> <div class="searchbox"> <asp:TextBox ID="txtSearchEAA" CssClass="watermark" Width="155px" runat="server"></asp:TextBox> </div> <div class="searchButton"> <asp:ImageButton ID="imbSearch" ImageUrl="/images/buttons/go.gif" OnClick="btnSearch_Click" runat="server" /> </div> <div style="clear:both;"></div> </div> <div class="loginBox"> <dl> <dt>Hello</dt> <dd><umbraco:Macro Alias="MemberName" runat="server"></umbraco:Macro></dd> <dt>Arena</dt> <dd><umbraco:Macro Alias="MemberArena" runat="server"></umbraco:Macro></dd> </dl> <div><asp:ImageButton ID="btnLogout" ImageUrl="/images/buttons/logout.gif" runat="server" OnClick="btnLogout_Click" /></div> </div> <div style="clear:both;"></div> </div> <div id="contentarea"> <div class="menuLeft"> <div class="menuPlaceholder"> <umbraco:Macro Alias="DynamicMenu" runat="server"></umbraco:Macro> </div> </div> <div class="mainBody"> <asp:ContentPlaceHolder id="bodyContent" runat="server"></asp:ContentPlaceHolder> </div> <div style="clear:both;"></div> </div> </div> </div> </form> <umbraco:Macro Alias="MemberAnalytics" runat="server"></umbraco:Macro> </body> </html>

    Read the article

  • How to read a database record with a DataReader and add it to a DataTable

    - by Olga
    Hello I have some data in a Oracle database table(around 4 million records) which i want to transform and store in a MSSQL database using ADO.NET. So far i used (for much smaller tables) a DataAdapter to read the data out of the Oracle DataBase and add the DataTable to a DataSet for further processing. When i tried this with my huge table, there was a outofmemory exception thrown. ( I assume this is because i cannot load the whole table into my memory) :) Now i am looking for a good way to perform this extract/transfer/load, without storing the whole table in the memory. I would like to use a DataReader and read the single dataRecords in a DataTable. If there are about 100k rows in it, I would like to process them and clear the DataTable afterwards(to have free memory again). Now i would like to know how to add a single datarecord as a row to a dataTable with ado.net and how to completly clear the dataTable out of memory: My code so far: Dim dt As New DataTable Dim count As Int32 count = 0 ' reads data records from oracle database table' While rdr.Read() 'read n records and add them to a dataTable' While count < 10000 dt.Rows.Add(????) count = count + 1 End While 'transform data in the dataTable, and insert it to the destination' ' flush the dataTable after insertion' count = 0 End While Thank you very much for your response!

    Read the article

  • Sorting GridView Formed With Data Set

    - by nani
    Following Code is for Sorting GridView Formed With DataSet Source: http://www.highoncoding.com/Articles/176_Sorting_GridView_Manually_.aspx But it is not displaying any output. There is no problem in sql connection. I am unable to trace the error, please help me. Thank You. public partial class _Default : System.Web.UI.Page { private const string ASCENDING = " ASC"; private const string DESCENDING = " DESC"; private DataSet GetData() { SqlConnection cnn = new SqlConnection("Server=localhost;Database=Northwind;Trusted_Connection=True;"); SqlDataAdapter da = new SqlDataAdapter("SELECT TOP 5 firstname,lastname,hiredate FROM EMPLOYEES", cnn); DataSet ds = new DataSet(); da.Fill(ds); return ds; } public SortDirection GridViewSortDirection { get { if (ViewState["sortDirection"] == null) ViewState["sortDirection"] = SortDirection.Ascending; return (SortDirection)ViewState["sortDirection"]; } set { ViewState["sortDirection"] = value; } } protected void GridView1_Sorting(object sender, GridViewSortEventArgs e) { string sortExpression = e.SortExpression; if (GridViewSortDirection == SortDirection.Ascending) { GridViewSortDirection = SortDirection.Descending; SortGridView(sortExpression, DESCENDING); } else { GridViewSortDirection = SortDirection.Ascending; SortGridView(sortExpression, ASCENDING); } } private void SortGridView(string sortExpression, string direction) { // You can cache the DataTable for improving performance DataTable dt = GetData().Tables[0]; DataView dv = new DataView(dt); dv.Sort = sortExpression + direction; GridView1.DataSource = dv; GridView1.DataBind(); } } aspx page asp:GridView ID="GridView1" runat="server" AllowSorting="True" OnSorting="GridView1_Sorting" /asp:GridView

    Read the article

  • Getting minimum - Min() - for DateTime column in a DataTable using LINQ to DataSets?

    - by Jay Stevens
    I need to get the minimum DateTime value of a column in a DataTable. The DataTable is generated dynamically from a CSV file, therefore I don't know the name of that column until runtime. Here is code I've got that doesn't work... private DateTime GetStartDateFromCSV(string inputFile, string date_attr) { EnumerableRowCollection<DataRow> table = CsvStreamReader.GetDataTableFromCSV(inputFile, "input", true).AsEnumerable(); DateTime dt = table.Select(record => record.Field<DateTime>(date_attr)).Min(); return dt; } The variable table is broken out just for clarity. I basically need to find the minimum value as a DateTime for one of the columns (to be chosen at runtime and represented by date_attr). I have tried several solutions from SO (most deal with known columns and/or non-DateTime fields). What I've got throws an error at runtime telling me that it can't do the DateTime conversion (that seems to be a problem with Linq?) I've confirmed that the data for the column name that is in the string date_attr is a date value.

    Read the article

  • Get Last Friday of Month in Java

    - by Nick Klauer
    I am working on a project where the requirement is to have a date calculated as being the last Friday of a given month. I think I have a solution that only uses standard Java, but I was wondering if anyone knew of anything more concise or efficient. Below is what I tested with for this year: for (int month = 0; month < 13; month++) { GregorianCalendar d = new GregorianCalendar(); d.set(d.MONTH, month); System.out.println("Last Week of Month in " + d.getDisplayName(d.MONTH, Calendar.LONG, Locale.ENGLISH) + ": " + d.getLeastMaximum(d.WEEK_OF_MONTH)); d.set(d.DAY_OF_WEEK, d.FRIDAY); d.set(d.WEEK_OF_MONTH, d.getActualMaximum(d.WEEK_OF_MONTH)); while (d.get(d.MONTH) > month || d.get(d.MONTH) < month) { d.add(d.WEEK_OF_MONTH, -1); } Date dt = d.getTime(); System.out.println("Last Friday of Last Week in " + d.getDisplayName(d.MONTH, Calendar.LONG, Locale.ENGLISH) + ": " + dt.toString()); }

    Read the article

< Previous Page | 13 14 15 16 17 18 19 20 21 22 23 24  | Next Page >