Search Results

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

Page 3/28 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Use Extension Methods to find first and last day of the month

    - by Tim Hibbard
    A lot of reports work on data from last month.  It is a nice touch to have these dates pre-populated for your users.  Using extension methods, the code can look cleaner too. Extension Methods: public static class DateHelper { public static DateTime FirstOfTheMonth(this DateTime dt) { return new DateTime(dt.Year, dt.Month, 1); }   public static DateTime LastOfTheMonth(this DateTime dt) { return dt.FirstOfTheMonth().AddMonths(1).AddDays(-1); } } Consuming Code: void Prepopulate() { startDateBox.CurrentlySelectedDate = DateTime.Now.AddMonths(-1).FirstOfTheMonth(); endDateBox.CurrentlySelectedDate = DateTime.Now.AddMonths(-1).LastOfTheMonth(); }

    Read the article

  • What is the worst C#/.NET gotcha?

    - by MusiGenesis
    This question is similar to this one, but focused on C# and .NET. I was recently working with a DateTime object, and wrote something like this: DateTime dt = DateTime.Now; dt.AddDays(1); return dt; // still today's date! WTF? The intellisense documentation for AddDays says it adds a day to the date, which it doesn't - it actually returns a date with a day added to it, so you have to write it like: DateTime dt = DateTime.Now; dt = dt.AddDays(1); return dt; // tomorrow's date This one has bitten me a number of times before, so I thought it would be useful to catalog the worst C# gotchas.

    Read the article

  • how to add column in SQL Query that incl. LEFT OUTER JOIN

    - by radbyx
    I have this Query: SELECT p.ProductName, dt.MaxTimeStamp, p.Responsible FROM Product p LEFT JOIN (SELECT ProductID, MAX(TimeStamp) AS MaxTimeStamp FROM StateLog WHERE State = 0 GROUP BY ProductID, Status) dt ON p.ProductID = dt.ProductID ORDER BY p.ProductName; It works like it should, but now I need to SELECT "State" out too. The tricky part is, that I only want the lastest "TimeStamp" where "State" was false. But now I also need the "State" for the lastest "TimeStamp". I tried this: SELECT p.ProductName, dt.State, dt.MaxTimeStamp, p.Responsible FROM Product p LEFT JOIN (SELECT ProductID, MAX(TimeStamp) AS MaxTimeStamp, State FROM StateLog WHERE State = 0 GROUP BY ProductID, Status) dt ON p.ProductID =dt.ProductID ORDER BY p.ProductName; But it didn't work, because it gave me the "State" for the lastest "TimeStamp". So I hope there is some clever heads out there that can help me. I'm guessing that this is either very simple or very hard to solve.

    Read the article

  • C# DataTable to Json?

    - by AliRiza Adiyahsi
    I want to get DataTable as Json Format to show it on a chart. public JsonResult GetDataTable() { DataTable dt = new DataTable(); dt.Columns.Add("Jan"); dt.Columns.Add("Feb"); dt.Columns.Add("Mar"); dt.Columns.Add("Apr"); for (int i = 0; i < 10; i++) { dt.Rows.Add(i * 5, i * 10, i * 15, i * 11); } // JsonDataTable = dt to Json return new JsonResult { Data = new { success = true, chartData = JsonDataTable }, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; } How Can I convert DataTable to Json? Thanks.

    Read the article

  • What is the worst gotcha in C# or .NET?

    - by MusiGenesis
    This question is similar to this one, but focused on C# and .NET. I was recently working with a DateTime object, and wrote something like this: DateTime dt = DateTime.Now; dt.AddDays(1); return dt; // still today's date! WTF? The intellisense documentation for AddDays says it adds a day to the date, which it doesn't - it actually returns a date with a day added to it, so you have to write it like: DateTime dt = DateTime.Now; dt = dt.AddDays(1); return dt; // tomorrow's date This one has bitten me a number of times before, so I thought it would be useful to catalog the worst C# gotchas.

    Read the article

  • Automatically triggering standard spaceship controls to stop its motion

    - by Garan
    I have been working on a 2D top-down space strategy/shooting game. Right now it is only in the prototyping stage (I have gotten basic movement) but now I am trying to write a function that will stop the ship based on it's velocity. This is being written in Lua, using the Love2D engine. My code is as follows (note- object.dx is the x-velocity, object.dy is the y-velocity, object.acc is the acceleration, and object.r is the rotation in radians): function stopMoving(object, dt) local targetr = math.atan2(object.dy, object.dx) if targetr == object.r + math.pi then local currentspeed = math.sqrt(object.dx*object.dx+object.dy*object.dy) if currentspeed ~= 0 then object.dx = object.dx + object.acc*dt*math.cos(object.r) object.dy = object.dy + object.acc*dt*math.sin(object.r) end else if (targetr - object.r) >= math.pi then object.r = object.r - object.turnspeed*dt else object.r = object.r + object.turnspeed*dt end end end It is implemented in the update function as: if love.keyboard.isDown("backspace") then stopMoving(player, dt) end The problem is that when I am holding down backspace, it spins the player clockwise (though I am trying to have it go the direction that would be the most efficient at getting to the angle it would have to be) and then it never starts to accelerate the player in the direction opposite to it's velocity. What should I change in this code to get that to work? EDIT : I'm not trying to just stop the player in place, I'm trying to get it to use it's normal commands to neutralize it's existing velocity. I also changed math.atan to math.atan2, apparently it's better. I noticed no difference when running it, though.

    Read the article

  • java.io.IOException: Server returned HTTP response code: 503 for URL: http://www.w3.org/TR/xhtml1/DT

    - by JBristow
    In the following code: private Document transformDoc(Source source) throws TransformerException, IOException { TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(new StreamSource(xsltResource.getInputStream())); JDOMResult result = new JDOMResult(); transformer.transform(source, result); return result.getDocument(); } I get this exception: java.io.IOException: Server returned HTTP response code: 503 for URL: http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd The XHTML I'm translating over via xsl is: <!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> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/> <title>Terms and Conditions</title> </head> <body> <div>Test Content</div> </body> </html> How do I stop the xalan transformer from phoning home?

    Read the article

  • Add new row to asp .net grid view using button

    - by SARAVAN
    Hi, I am working in ASP .net 2.0. I am a learner. I have a grid view which has a button in it. Please find the asp mark up below <form id="form1" runat="server"> <div> <asp:GridView ID="myGridView" runat="server"> <Columns> <asp:TemplateField> <ItemTemplate> <asp:Button CommandName="AddARowBelow" Text="Add A Row Below" runat="server" /> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> </div> </form> Please find the code behind below. using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Data; using System.Web.UI.WebControls; namespace GridViewDemo { public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { DataTable dt = new DataTable("myTable"); dt.Columns.Add("col1"); dt.Columns.Add("col2"); dt.Columns.Add("col3"); dt.Rows.Add(1, 2, 3); dt.Rows.Add(1, 2, 3); dt.Rows.Add(1, 2, 3); dt.Rows.Add(1, 2, 3); dt.Rows.Add(1, 2, 3); myGridView.DataSource = dt; myGridView.DataBind(); } protected void myGridView_RowCommand(object sender, GridViewCommandEventArgs e) { } } } I was thinking that when I click the command button, it would fire the mygridview_rowcommand() but instead it threw an error as follows: Invalid postback or callback argument. Event validation is enabled using in configuration or <%@ Page EnableEventValidation="true" % in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation. Can any one let me know on where I am going wrong?

    Read the article

  • using Generics in C# [closed]

    - by Uphaar Goyal
    I have started looking into using generics in C#. As an example what i have done is that I have an abstract class which implements generic methods. these generic methods take a sql query, a connection string and the Type T as parameters and then construct the data set, populate the object and return it back. This way each business object does not need to have a method to populate it with data or construct its data set. All we need to do is pass the type, the sql query and the connection string and these methods do the rest.I am providing the code sample here. I am just looking to discuss with people who might have a better solution to what i have done. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.Data.SqlClient; using MWTWorkUnitMgmtLib.Business; using System.Collections.ObjectModel; using System.Reflection; namespace MWTWorkUnitMgmtLib.TableGateway { public abstract class TableGateway { public TableGateway() { } protected abstract string GetConnection(); protected abstract string GetTableName(); public DataSet GetDataSetFromSql(string connectionString, string sql) { DataSet ds = null; using (SqlConnection connection = new SqlConnection(connectionString)) using (SqlCommand command = connection.CreateCommand()) { command.CommandText = sql; connection.Open(); using (ds = new DataSet()) using (SqlDataAdapter adapter = new SqlDataAdapter(command)) { adapter.Fill(ds); } } return ds; } public static bool ContainsColumnName(DataRow dr, string columnName) { return dr.Table.Columns.Contains(columnName); } public DataTable GetDataTable(string connString, string sql) { DataSet ds = GetDataSetFromSql(connString, sql); DataTable dt = null; if (ds != null) { if (ds.Tables.Count 0) { dt = ds.Tables[0]; } } return dt; } public T Construct(DataRow dr, T t) where T : class, new() { Type t1 = t.GetType(); PropertyInfo[] properties = t1.GetProperties(); foreach (PropertyInfo property in properties) { if (ContainsColumnName(dr, property.Name) && (dr[property.Name] != null)) property.SetValue(t, dr[property.Name], null); } return t; } public T GetByID(string connString, string sql, T t) where T : class, new() { DataTable dt = GetDataTable(connString, sql); DataRow dr = dt.Rows[0]; return Construct(dr, t); } public List GetAll(string connString, string sql, T t) where T : class, new() { List collection = new List(); DataTable dt = GetDataTable(connString, sql); foreach (DataRow dr in dt.Rows) collection.Add(Construct(dr, t)); return collection; } } }

    Read the article

  • Date and Time Support in SQL Server 2008

    - by Aamir Hasan
      Using the New Date and Time Data Types Normal 0 false false false EN-US X-NONE X-NONE /* Style Definitions */ table.MsoNormalTable {mso-style-name:"Table Normal"; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-priority:99; mso-style-qformat:yes; mso-style-parent:""; mso-padding-alt:0in 5.4pt 0in 5.4pt; mso-para-margin-top:0in; mso-para-margin-right:0in; mso-para-margin-bottom:10.0pt; mso-para-margin-left:0in; line-height:115%; mso-pagination:widow-orphan; font-size:11.0pt; font-family:"Calibri","sans-serif"; mso-ascii-font-family:Calibri; mso-ascii-theme-font:minor-latin; mso-hansi-font-family:Calibri; mso-hansi-theme-font:minor-latin; mso-bidi-font-family:"Times New Roman"; mso-bidi-theme-font:minor-bidi;} 1.       The new date and time data types in SQL Server 2008 offer increased range and precision and are ANSI SQL compatible. 2.       Separate date and time data types minimize storage space requirements for applications that need only date or time information. Moreover, the variable precision of the new time data type increases storage savings in exchange for reduced accuracy. 3.       The new data types are mostly compatible with the original date and time data types and use the same Transact-SQL functions. 4.       The datetimeoffset data type allows you to handle date and time information in global applications that use data that originates from different time zones. SELECT c.name, p.* FROM politics pJOIN country cON p.country = c.codeWHERE YEAR(Independence) < 1753ORDER BY IndependenceGO8.    Highlight the SELECT statement and click Execute ( ) to show the use of some of the date functions.T-SQLSELECT c.name AS [Country Name],        CONVERT(VARCHAR(12), p.Independence, 107) AS [Independence Date],       DATEDIFF(YEAR, p.Independence, GETDATE()) AS [Years Independent (appox)],       p.GovernmentFROM politics pJOIN country cON p.country = c.codeWHERE YEAR(Independence) < 1753ORDER BY IndependenceGO10.    Select the SET DATEFORMAT statement and click Execute ( ) to change the DATEFORMAT to day-month-year.T-SQLSET DATEFORMAT dmyGO11.    Select the DECLARE and SELECT statements and click Execute ( ) to show how the datetime and datetime2 data types interpret a date literal.T-SQLSET DATEFORMAT dmyDECLARE @dt datetime = '2008-12-05'DECLARE @dt2 datetime2 = '2008-12-05'SELECT MONTH(@dt) AS [Month-Datetime], DAY(@dt)     AS [Day-Datetime]SELECT MONTH(@dt2) AS [Month-Datetime2], DAY(@dt2)     AS [Day-Datetime2]GO12.    Highlight the DECLARE and SELECT statements and click Execute ( ) to use integer arithmetic on a datetime variable.T-SQLDECLARE @dt datetime = '2008-12-05'SELECT @dt + 1GO13.    Highlight the DECLARE and SELECT statements and click Execute ( ) to show how integer arithmetic is not allowed for datetime2 variables.T-SQLDECLARE @dt2 datetime = '2008-12-05'SELECT @dt2 + 1GO14.    Highlight the DECLARE and SELECT statements and click Execute ( ) to show how to use DATE functions to do simple arithmetic on datetime2 variables.T-SQLDECLARE @dt2 datetime2(7) = '2008-12-05'SELECT DATEADD(d, 1, @dt2)GO15.    Highlight the DECLARE and SELECT statements and click Execute ( ) to show how the GETDATE function can be used with both datetime and datetime2 data types.T-SQLDECLARE @dt datetime = GETDATE();DECLARE @dt2 datetime2(7) = GETDATE();SELECT @dt AS [GetDate-DateTime], @dt2 AS [GetDate-DateTime2]GO16.    Draw attention to the values returned for both columns and how they are equal.17.    Highlight the DECLARE and SELECT statements and click Execute ( ) to show how the SYSDATETIME function can be used with both datetime and datetime2 data types.T-SQLDECLARE @dt datetime = SYSDATETIME();DECLARE @dt2 datetime2(7) = SYSDATETIME();SELECT @dt AS [Sysdatetime-DateTime], @dt2     AS [Sysdatetime-DateTime2]GO18.    Draw attention to the values returned for both columns and how they are different.Programming Global Applications with DateTimeOffset 2.    If you have not previously created the SQLTrainingKitDB database while completing another demo in this training kit, highlight the CREATE DATABASE statement and click Execute ( ) to do so now.T-SQLCREATE DATABASE SQLTrainingKitDBGO3.    Select the USE and CREATE TABLE statements and click Execute ( ) to create table datetest in the SQLTrainingKitDB database.T-SQLUSE SQLTrainingKitDBGOCREATE TABLE datetest (  id integer IDENTITY PRIMARY KEY,  datetimecol datetimeoffset,  EnteredTZ varchar(40)); Reference:http://www.microsoft.com/downloads/details.aspx?FamilyID=E9C68E1B-1E0E-4299-B498-6AB3CA72A6D7&displaylang=en   

    Read the article

  • MS SQL SELECT stored procedure according to combobox.selectedvalue

    - by Jay
    Hello, In order to fill a datagridview according to the selectedvalue of a combobox I've tried creating a stored procedure. However, as I'm not 100% sure what I'm doing it, depending on the WHERE statement at the end of my stored procedure, either returns everything within the table or nothing at all. This is what's in my class: Public Function GetAankoopDetails(ByRef DisplayMember As String, ByRef ValueMember As String) As DataTable DisplayMember = "AankoopDetailsID" ValueMember = "AankoopDetailsID" If DS.Tables.Count > 0 Then DS.Tables.Remove(DT) End If DT = DAC.ExecuteDataTable(My.Resources.S_AankoopDetails, _Result, _ DAC.Parameter(Const_AankoopID, AankoopID), _ DAC.Parameter("@ReturnValue", 0)) DS.Tables.Add(DT) Return DT End Function Public Function GetAankoopDetails() As DataTable If DS.Tables.Count > 0 Then DS.Tables.Remove(DT) End If DT = DAC.ExecuteDataTable(My.Resources.S_AankoopDetails, _Result, _ DAC.Parameter(Const_AankoopID, AankoopID), _ DAC.Parameter("@ReturnValue", 0)) DS.Tables.Add(DT) Return DT End Function This is the function in the code behind the form I've written in order to fill the datagridview: Private Sub GridAankoopDetails_Fill() Try Me.Cursor = Cursors.WaitCursor dgvAankoopDetails.DataSource = Nothing _clsAankoopDetails.AankoopDetailsID = cboKeuze.SelectedValue dgvAankoopDetails.DataSource = _clsAankoopDetails.GetAankoopDetails Catch ex As Exception MessageBox.Show("An error occurred while trying to fill the data grid: " & ex.Message, "Oops!", MessageBoxButtons.OK) Finally Me.Cursor = Cursors.Default End Try End Sub And finally, this is my stored procedure: (do note that I'm not sure what I'm doing here) USE [Budget] GO /****** Object: StoredProcedure [dbo].[S_AankoopDetails] Script Date: 04/12/2010 03:10:52 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER PROCEDURE [dbo].[S_AankoopDetails] ( @AankoopID int, @ReturnValue int output ) AS declare @Value int set @Value =@@rowcount if @Value = 0 begin SELECT dbo.tblAankoopDetails.AankoopDetailsID, dbo.tblAankoopDetails.AankoopID, dbo.tblAankoopDetails.ArtikelID, dbo.tblAankoopDetails.Aantal, dbo.tblAankoopDetails.Prijs, dbo.tblAankoopDetails.Korting, dbo.tblAankoopDetails.SoortKorting, dbo.tblAankoopDetails.UitgavenDeelGroepID FROM dbo.tblAankoopDetails INNER JOIN dbo.tblAankoop ON dbo.tblAankoopDetails.AankoopID = dbo.tblAankoop.AankoopID INNER JOIN dbo.tblArtikel ON dbo.tblAankoopDetails.ArtikelID = dbo.tblArtikel.ArtikelID INNER JOIN dbo.tblUitgavenDeelGroep ON dbo.tblAankoopDetails.UitgavenDeelGroepID = dbo.tblUitgavenDeelGroep.UitgavenDeelGroepID WHERE dbo.tblAankoopDetails.Deleted = 0 and dbo.tblAankoopDetails.AankoopID = @AankoopID ORDER BY AankoopID if @@rowcount >0 begin set @ReturnValue=999 end else begin set @ReturnValue=997 end end if @Value >0 begin --Dit wil zeggen dat ik een gebruiker wil ingeven die reeds bestaat. (998) set @ReturnValue=998 end Does anyone know what I'm need to do to resolve this? Kind regards, Jay

    Read the article

  • Is there added overhead to looking up a column in a DataTable by name rather than by index?

    - by Ben McCormack
    In a DataTable object, is there added overhead to looking up a column value by name thisRow("ColumnA") rather than by the column index thisRow(0)? In which scenarios might this be an issue. I work on a team that has lots of experience writing VB6 code and I noticed that didn't do column lookups by name for DataTable objects or data grids. Even in .NET code, we use a set of integer constants to reference column names in these types of objects. I asked our team lead why this was so, and he mentioned that in VB6, there was a lot of overhead in looking up data by column name rather than by index. Is this still true for .NET? Example code (in VB.NET, but same applies to C#): Public Sub TestADOData() Dim dt As New DataTable 'Set up the columns in the DataTable ' dt.Columns.Add(New DataColumn("ID", GetType(Integer))) dt.Columns.Add(New DataColumn("Name", GetType(String))) dt.Columns.Add(New DataColumn("Description", GetType(String))) 'Add some data to the data table ' dt.Rows.Add(1, "Fred", "Pitcher") dt.Rows.Add(3, "Hank", "Center Field") 'Method 1: By Column Name ' For Each r As DataRow In dt.Rows Console.WriteLine( _ "{0,-2} {1,-10} {2,-30}", r("ID"), r("Name"), r("Description")) Next Console.WriteLine() 'Method 2: By Column Name ' For Each r As DataRow In dt.Rows Console.WriteLine("{0,-2} {1,-10} {2,-30}", r(0), r(1), r(2)) Next End Sub Is there an case where method 2 provides a performance advantage over method 1?

    Read the article

  • PHP Markdown Extra and Definition Lists

    - by Kirk Bentley
    I'm currently generating a definition list with PHP Markdown Extra with the following syntax: Term : Description : Description Two My Other Term : Description which generates the following HTML: <dl> <dt>Term</dt> <dd>Description</dd> <dd>Description Two</dd> <dt>My Other Term</dt> <dd>Description</dd> </dl> Does anyone know how I can get Markdown to create separate definition lists for each definition term and descriptions to create markup like this? <dl> <dt>Term</dt> <dd>Description</dd> <dd>Description Two</dd> </dl> <dl <dt>My Other Term</dt> <dd>Description</dd> </dl>

    Read the article

  • SQL Server SELECT stored procedure according to combobox.selectedvalue

    - by Jay
    In order to fill a datagridview according to the selectedvalue of a combobox I've tried creating a stored procedure. However, as I'm not 100% sure what I'm doing, depending on the WHERE statement at the end of my stored procedure, it either returns everything within the table or nothing at all. This is what's in my class: Public Function GetAankoopDetails(ByRef DisplayMember As String, ByRef ValueMember As String) As DataTable DisplayMember = "AankoopDetailsID" ValueMember = "AankoopDetailsID" If DS.Tables.Count > 0 Then DS.Tables.Remove(DT) End If DT = DAC.ExecuteDataTable(My.Resources.S_AankoopDetails, _Result, _ DAC.Parameter(Const_AankoopID, AankoopID), _ DAC.Parameter("@ReturnValue", 0)) DS.Tables.Add(DT) Return DT End Function Public Function GetAankoopDetails() As DataTable If DS.Tables.Count > 0 Then DS.Tables.Remove(DT) End If DT = DAC.ExecuteDataTable(My.Resources.S_AankoopDetails, _Result, _ DAC.Parameter(Const_AankoopID, AankoopID), _ DAC.Parameter("@ReturnValue", 0)) DS.Tables.Add(DT) Return DT End Function This is the function in the code behind the form I've written in order to fill the datagridview: Private Sub GridAankoopDetails_Fill() Try Me.Cursor = Cursors.WaitCursor dgvAankoopDetails.DataSource = Nothing _clsAankoopDetails.AankoopDetailsID = cboKeuze.SelectedValue dgvAankoopDetails.DataSource = _clsAankoopDetails.GetAankoopDetails Catch ex As Exception MessageBox.Show("An error occurred while trying to fill the data grid: " & ex.Message, "Oops!", MessageBoxButtons.OK) Finally Me.Cursor = Cursors.Default End Try End Sub And finally, this is my stored procedure: (do note that I'm not sure what I'm doing here) USE [Budget] GO /****** Object: StoredProcedure [dbo].[S_AankoopDetails] Script Date: 04/12/2010 03:10:52 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER PROCEDURE [dbo].[S_AankoopDetails] ( @AankoopID int, @ReturnValue int output ) AS declare @Value int set @Value =@@rowcount if @Value = 0 begin SELECT dbo.tblAankoopDetails.AankoopDetailsID, dbo.tblAankoopDetails.AankoopID, dbo.tblAankoopDetails.ArtikelID, dbo.tblAankoopDetails.Aantal, dbo.tblAankoopDetails.Prijs, dbo.tblAankoopDetails.Korting, dbo.tblAankoopDetails.SoortKorting, dbo.tblAankoopDetails.UitgavenDeelGroepID FROM dbo.tblAankoopDetails INNER JOIN dbo.tblAankoop ON dbo.tblAankoopDetails.AankoopID = dbo.tblAankoop.AankoopID INNER JOIN dbo.tblArtikel ON dbo.tblAankoopDetails.ArtikelID = dbo.tblArtikel.ArtikelID INNER JOIN dbo.tblUitgavenDeelGroep ON dbo.tblAankoopDetails.UitgavenDeelGroepID = dbo.tblUitgavenDeelGroep.UitgavenDeelGroepID WHERE dbo.tblAankoopDetails.Deleted = 0 and dbo.tblAankoopDetails.AankoopID = @AankoopID ORDER BY AankoopID if @@rowcount >0 begin set @ReturnValue=999 end else begin set @ReturnValue=997 end end if @Value >0 begin --Dit wil zeggen dat ik een gebruiker wil ingeven die reeds bestaat. (998) set @ReturnValue=998 end Does anyone know what I need to do to resolve this?

    Read the article

  • Nested Views-button aint clicking

    - by Deepika
    i have a view which has a datepicker and a button added to it. There is another view which adds the above view as subview. But the events like touchesBegan and button's action are not being clicked on the subview. Please help The code of the parent view is: iTagDatePicker *dt=[[iTagDatePicker alloc] initWithFrame:CGRectMake(0.0, 180.0, 320.0, 240.0)]; //dt.userInteractionEnabled=YES; //[dt becomeFirstResponder]; dt.backgroundColor=[UIColor clearColor]; [UIView beginAnimations:@"animation" context:nil]; [UIView setAnimationDuration:1.0]; CGPoint cntr; cntr.x=160.0; cntr.y=420.0; dt.center=cntr; [self.view addSubview:dt]; self.view.userInteractionEnabled=YES; CGPoint cntr1; cntr1.x=160.0; cntr1.y=158.0; dt.center=cntr1; [UIView commitAnimations]; [dt release]; and the code for the sub class is: - (id)initWithFrame:(CGRect)frame { if (self = [super initWithFrame:frame]) { dtPicker=[[UIDatePicker alloc] initWithFrame:CGRectMake(frame.origin.x, frame.origin.y, 320.0, 216.0)]; dtPicker.datePickerMode=UIDatePickerModeDate; dtPicker.date=[NSDate date]; [self addSubview:dtPicker]; btn=[[UIButton buttonWithType:UIButtonTypeDetailDisclosure]retain]; btn.frame=CGRectMake(110.0, 400.0, 100.0, 20.0); [btn setTitle:@"Done" forState:UIControlStateNormal]; btn.userInteractionEnabled=YES; [btn becomeFirstResponder]; [btn addTarget:self action:@selector(SelectedVal:) forControlEvents:UIControlEventTouchDown]; [self addSubview:btn]; } return self; } The button is not working

    Read the article

  • A better way of getting a data table with various column types into string array

    - by Vlad
    This should be an easy one, looks like I got myself too confused. I get a table from a database, data ranges from varchar to int to Null values. Cheap and dirty way of converting this into a tab-delimited file that I already have is this (shrunken to preserve space, ugliness is kept on par with original): da.Fill(dt) ' da - DataAdapter ' ' dt - DataTable ' Dim lColumns As Long = dt.Columns.Count Dim arrColumns(dt.Columns.Count) As String Dim arrData(dt.Columns.Count) As Object Dim j As Long = 0 Dim arrData(dt.Columns.Count) As Object For i = 0 To dt.Rows.Count - 1 arrData = dt.Rows(i).ItemArray() For j = 0 To arrData.GetUpperBound(0) - 1 arrColumns(j) = arrData(j).ToString Next wrtOutput.WriteLine(String.Join(strFieldDelimiter, arrColumns)) Array.Clear(arrColumns, 0, arrColumns.GetLength(0)) Array.Clear(arrData, 0, arrData.GetLength(0)) Next Not only this is ugly and inefficient, it is also getting on my nerves. Besides, I want, if possible, to avoid the infamous double-loop through the table. I would really appreciate a clean and safe way of rewriting this piece. I like the approach that is used here - especially that is trying to solve the same problem that I have, but it crashes on me when I apply it to my case directly.

    Read the article

  • Session variable gets updated automatically

    - by user1869914
    protected void btningAccept_Click(object sender, EventArgs e) { if(!(txtLOVCode.Text==" "||txtLOVvalue.Text==" ")) { rowid++; // DFDLOVlst.Visible=true; DataTable dt = createTemptable(); dt = (DataTable)Session["dfdtemptable"]; DataRow dr = dt.NewRow(); dr["prociLOV_Id"] = rowid; dr["prociLOV_Value"] = txtLOVvalue.Text; dr["prociLOV_Code"] = txtLOVCode.Text; Boolean isalreadyinLOVlst = false; foreach (DataRow chkrow in dt.Rows) { if (String.Equals(dr["prociLOV_Value"].ToString().Trim(), chkrow["prociLOV_Value"].ToString().Trim(),StringComparison.CurrentCultureIgnoreCase) && String.Equals(dr["prociLOV_Code"].ToString().Trim(), chkrow["prociLOV_Code"].ToString().Trim(), StringComparison.CurrentCultureIgnoreCase)) { isalreadyinLOVlst = true; break; } } if (isalreadyinLOVlst) { this.lblMessage.Text = "LOV value: " + dr["prociLOV_Value"].ToString() + ": " + dr["prociLOV_Code"].ToString() + " already exits"; } else { this.lblMessage.Text = " "; dt.Rows.Add(dr); DataTable addedLOV = createTemptable(); addedLOV = (DataTable)Session["addedLOV"]; addedLOV.ImportRow(dr); ; Session["addedLOV"] = addedLOV; } DFDLOVlst.DataSource = dt; DFDLOVlst.DataBind(); // dt.AcceptChanges(); Session["dfdtemptable"] = dt; txtLOVCode.Text = ""; txtLOVvalue.Text = ""; MDIngrdientsCode.Hide(); this.txtLOVvalue.ReadOnly = false; this.txtLOVCode.ReadOnly = false; } else this.lblMessage.Text="NO LOV VALUES ENTERED"; } Here the session varible Session["dfdtemptable"] and Session["addedLOV"] both gets updated twice and their row count becomes 2 for each session varible..But the row count sholud be 1 for each session varible.But the Session variable gets updated on the other Session varibles updation.. The Session["dfdtemptable"] gets updated when Session["addedLOV"] is assigned or updated..Can't figure out the problem..?

    Read the article

  • datagridviewcomboboxcolumn with datasource issue?

    - by Sarrrva
    i have some propblem in datagridviewcombobocolumn with custom datasource property in vb.net. when i add datasource it does not populate in datagridview combobox column it giving nothing.. any one please help me out from this problem... code comboboxcell: Public Overrides Sub InitializeEditingControl(ByVal rowIndex As Integer, ByVal initialFormattedValue As Object, ByVal dataGridViewCellStyle As DataGridViewCellStyle) ' Set the value of the editing control to the current cell value. MyBase.InitializeEditingControl(rowIndex, initialFormattedValue, dataGridViewCellStyle) Dim ctl As ComboEditingControl = CType(DataGridView.EditingControl, ComboEditingControl) ctl.DropDownStyle = ComboBoxStyle.DropDown ctl.AutoCompleteSource = AutoCompleteSource.ListItems ctl.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Suggest If (Me.DataGridView.Rows(rowIndex).Cells(0).Value <> Nothing) Then Dim GetValueFromRowToUseForBuildingCombo As String = Me.DataGridView.Rows(rowIndex).Cells(0).Value.ToString() ctl.Items.Clear() Dim dt As New DataTable() Try dt = TryCast(DirectCast(Me.DataGridView.Columns(ColumnIndex), ComboColumn).DataSource, DataTable) Catch ex As Exception MsgBox("error") End Try If (dt Is Nothing) Then ctl.Items.Add("") Else Dim thing As DataRow For Each thing In dt.Rows ctl.Items.Add(thing(0).ToString) Next End If If Me.Value Is Nothing Then ctl.SelectedIndex = -1 Else ctl.SelectedItem = Me.Value End If ctl.EditingControlDataGridView = Me.DataGridView End If End Sub from code: Dim widgets As New WidgetDataHandler Dim obj = widgets.GetAllWigetTypes() Dim dt As New DataTable Dim ListofmyObjects As New List(Of widget_types)(obj) Dim objList As New cObjectToTable(Of widget_types)(ListofmyObjects) dt = objList.GetTable() Dim obj1 For Each obj1 In obj blPersons.Add(obj1) Next Dim col1 As New DataGridViewTextBoxColumn col1.DisplayIndex = 0 col1.DataPropertyName = "Id" col1.HeaderText = "Id" dgvi00.Columns.Add(col1) Dim col2 As New ComboColumn col2.DisplayIndex = 1 col2.SortMode = DataGridViewColumnSortMode.Automatic col2.HeaderText = "Name" col2.DataPropertyName = "Name" col2.ToolTipText = "Select something from my combo" Dim dst As New DataSet 'Dim dt1 As New DataTable 'dt1.Columns.Add(col2.HeaderText) 'For Each thing In dt.Rows ' MsgBox(thing(1).ToString) ' dt1.Rows.Add(thing(1).ToString) 'Next dst.Tables.Add(dt) col2.DataSource = dst.Tables(0) col2.DisplayMember = "Name" Me.dgvi00.Columns.AddRange(col2) dgvi00.DataSource = blPersons.BindingSource 'setup the bindings for the binding navigator Dim bn As New _365_Media_Library.BindingNavigatorWithFilter bn.Dock = DockStyle.Bottom bn.GripStyle = ToolStripGripStyle.Hidden Me.Controls.Add(bn) bn.BindingSource = blPersons.BindingSource note : its working good in standalone application regards and thanks sarva

    Read the article

  • Runge-Kutta (RK4) integration for game physics

    - by Kai
    Gaffer on Games has a great article about using RK4 integration for better game physics. The implementation is straightforward but the math behind it confuses me. I understand derivatives and integrals on a conceptual level but I haven't manipulated equations in a long time. Here's the brunt of Gaffer's implementation: void integrate(State &state, float t, float dt) { Derivative a = evaluate(state, t, 0.0f, Derivative()); Derivative b = evaluate(state, t+dt*0.5f, dt*0.5f, a); Derivative c = evaluate(state, t+dt*0.5f, dt*0.5f, b); Derivative d = evaluate(state, t+dt, dt, c); const float dxdt = 1.0f/6.0f * (a.dx + 2.0f*(b.dx + c.dx) + d.dx); const float dvdt = 1.0f/6.0f * (a.dv + 2.0f*(b.dv + c.dv) + d.dv) state.x = state.x + dxdt * dt; state.v = state.v + dvdt * dt; } Can anybody explain in simple terms how RK4 works? Specifically, why are we averaging the derivatives at 0.0f, 0.5f, 0.5f, and 1.0f? How is averaging derivatives up to the 4th order different from doing a simple euler integration with a smaller timestep? After reading the accepted answer below, and several other articles, I have a grasp on how RK4 works. To answer my own questions: Can anybody explain in simple terms how RK4 works? RK4 takes advantage of the fact that we can get a much better approximation of a function if we use its higher-order derivatives rather than just the first or second derivative. That's why the Taylor series converges much faster than Euler approximations. (take a look at the animation on the right side of that page) Specifically, why are we averaging the derivatives at 0.0f, 0.5f, 0.5f, and 1.0f? The Runge-Kutta method is an approximation of a function that samples derivatives of several points within a timestep, unlike the Taylor series which only samples derivatives of a single point. After sampling these derivatives we need to know how to weigh each sample to get the closest approximation possible. An easy way to do this is to pick constants that coincide with the Taylor series, which is how the constants of a Runge-Kutta equation are determined. This article made it clearer for me: http://web.mit.edu/10.001/Web/Course%5FNotes/Differential%5FEquations%5FNotes/node5.html. Notice how (15) is the Taylor series expansion while (17) is the Runge-Kutta derivation. How is averaging derivatives up to the 4th order different from doing a simple euler integration with a smaller timestep? Mathematically it converges much faster than doing many Euler approximations. Of course, with enough Euler approximations we can gain equal accuracy to RK4, but the computational power needed doesn't justify using Euler.

    Read the article

  • Add columns to a datatable in c#?

    - by Pandiya Chendur
    I have a csv reader class that reads a .csv file and its values.... I have created datatable out of it... Consider my Datatable contains three header columns Name,EmailId,PhoneNo.... The values have been added successfully.... Now i want to add two columns IsDeleted,CreatedDate to this datatable... I have tried this but it doesn't seem to work, foreach (string strHeader in headers) { dt.Columns.Add(strHeader); } string[] data; while ((data = reader.GetCSVLine()) != null) { dt.Rows.Add(data); } dt.Columns.Add("IsDeleted", typeof(byte)); dt.Columns.Add(new DataColumn("CreatedDate", typeof(DateTime))); foreach (DataRow dr in dt.Rows) { dr["IsDeleted"] = Convert.ToByte(0); dr["CreatedDate"] = Convert.ToDateTime(System.DateTime.Now.ToString()); dt.Rows.Add(dr); } When i try to add isdeleted values an error saying This row already belongs to this table. ....

    Read the article

  • Most efficient sorting of calculation on DataTable column calculation

    - by byte
    Lets say you have a DataTable that has columns of "id", "cost", "qty": DataTable dt = new DataTable(); dt.Columns.Add("id", typeof(int)); dt.Columns.Add("cost", typeof(double)); dt.Columns.Add("qty", typeof(int)); And it's keyed on "id": dt.PrimaryKey = new DataColumn[1] { dt.Columns["id"] }; Now what we are interested in is the cost per quantity. So, in other words if you had a row of: id | cost | qty ---------------- 42 | 10.00 | 2 The cost per quantity is 5.00. My question then is, given the preceeding table, assume it's constructed with many thousands of rows, and you're interested in the top 3 cost per quantity rows. The information needed is the id, cost per quantity. You cannot use LINQ. In SQL it would be trivial; how BEST (most efficiently) would you accomplish it in C# without LINQ?

    Read the article

  • XHTML validating block level element as a link

    - by Matty F
    I need a way to make an entire DL element clickable with only one anchor tag, that validates as XHTML. As in: <a> <dl> <dt>Data term</dt> <dd>Data definition</dd> </dl> </a> This currently doesn't validate as XHTML as the anchor tag cannot contain the DL. The only way I can get it to validate is if I make two anchor tags and place them inside DT and DD. As in: <dl> <dt><a>Data term</a></dt> <dd><a>Data definition</a></dt> </dl> I'm trying to avoid this, as it would result in two href attributes requiring maintenance, introducing the possibility they could become out of sync. Suggestions?

    Read the article

  • Why differs floating-point precision in C# when separated by parantheses and when separated by state

    - by Andreas Larsen
    I am aware of how floating point precision works in the regular cases, but I stumbled on an odd situation in my C# code. Why aren't result1 and result2 the exact same floating point value here? const float A; // Arbitrary value const float B; // Arbitrary value float result1 = (A*B)*dt; float result2 = (A*B); result2 *= dt; From this page I figured float arithmetic was left-associative and that this means values are evaluated and calculated in a left-to-right manner. The full source code involves XNA's Quaternions. I don't think it's relevant what my constants are and what the VectorHelper.AddPitchRollYaw() does. The test passes just fine if I calculate the delta pitch/roll/yaw angles in the same manner, but as the code is below it does not pass: X Expected: 0.275153548f But was: 0.275153786f [TestFixture] internal class QuaternionPrecisionTest { [Test] public void Test() { JoystickInput input; input.Pitch = 0.312312432f; input.Roll = 0.512312432f; input.Yaw = 0.912312432f; const float dt = 0.017001f; float pitchRate = input.Pitch * PhysicsConstants.MaxPitchRate; float rollRate = input.Roll * PhysicsConstants.MaxRollRate; float yawRate = input.Yaw * PhysicsConstants.MaxYawRate; Quaternion orient1 = Quaternion.Identity; Quaternion orient2 = Quaternion.Identity; for (int i = 0; i < 10000; i++) { float deltaPitch = (input.Pitch * PhysicsConstants.MaxPitchRate) * dt; float deltaRoll = (input.Roll * PhysicsConstants.MaxRollRate) * dt; float deltaYaw = (input.Yaw * PhysicsConstants.MaxYawRate) * dt; // Add deltas of pitch, roll and yaw to the rotation matrix orient1 = VectorHelper.AddPitchRollYaw( orient1, deltaPitch, deltaRoll, deltaYaw); deltaPitch = pitchRate * dt; deltaRoll = rollRate * dt; deltaYaw = yawRate * dt; orient2 = VectorHelper.AddPitchRollYaw( orient2, deltaPitch, deltaRoll, deltaYaw); } Assert.AreEqual(orient1.X, orient2.X, "X"); Assert.AreEqual(orient1.Y, orient2.Y, "Y"); Assert.AreEqual(orient1.Z, orient2.Z, "Z"); Assert.AreEqual(orient1.W, orient2.W, "W"); } } Granted, the error is small and only presents itself after a large number of iterations, but it has caused me some great headackes.

    Read the article

  • How do I allow edit only a particular column in datagridview in windows application using C#

    - by cmrhema
    Hi, I want to enable only two columns in the DataGridview to be able to edit. The others should not be allowed to edit. Further I am not directly linking to datasource; I will be doing some thing like this way DataTable dt = new DataTable(); dt.Columns.Add("Email"); dt.Columns.Add("email1"); for (int i = 0; i < 5; i++) { DataRow dr = dt.NewRow(); dr["Email"] = i.ToString(); dr["email1"] = i.ToString() + "sdf"; dt.Rows.Add(dr); } BindingSource bs = new BindingSource(); bs.DataSource = dt; dataGridView1.DataSource = bs; So which property should I set, that will enable only one column say Email(in the above eg) to be editable. Thanks

    Read the article

  • DataTable Delete Row and AcceptChanges

    - by Pang
    DataTable DT num type name =================================== 001 A Peter 002 A Sam 003 B John public static void fun1(ref DataTable DT, String TargetType) { for (int i = 0; i < DT.Rows.Count; i++) { string type = DT.Rows[i]["type"]; if (type == TargetType) { /**Do Something**/ DT.Rows[i].Delete(); } } DT.AcceptChanges(); } My function get specific data rows in datatable according to the TargetType and use their info to do something. After the datarow is read (match the target type), it will be deleted. However, the row is deleted immediately after .Delete() execute, so the location of the next row (by i) is incorrect. For example, if TargetType is A. When i=0, the "Peter" row is deleted after .Delete executed. Then when i=1, I suppose it will locate the "Sam" row but it actually located "John" row because "Peter" row is deleted. Is there any problem in my codes?

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >