Hey, I am pretty new to ASP.NET, trying to run basic query to get latest entry ID from table (since this shit doesn't have auto increment [I didn't find any way to make it])
but when I run the code it just gives me error.
[code]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Configuration;
using System.Data.Sql;
namespace AITProjectX11413088
{
public class SQLHelpers
{
public int GetLatestID(String type)
{
String query = "SELECT Max(ides) FROM "+type;
String connStr = ConfigurationManager.ConnectionStrings["RevsConnectionString"].ConnectionString;
SqlConnection sqli = new SqlConnection(connStr);
sqli.Open();
SqlCommand cmd = new SqlCommand(query, sqli);
SqlDataReader dr = cmd.ExecuteReader();
String num = dr["ides"]+1.ToString();
return Int32.Parse(num);
}
}
}
[/code]
Any help?
Stuck with this for quite a while now.
Thanks.
Having changing table names is a bad idea.
Anyways, try using "[URL="http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar(v=vs.110).aspx"]ExecuteScalar[/URL]" instead of creating a DataReader.
[QUOTE=Nisd;43203997]Having changing table names is a bad idea.
Anyways, try using "[URL="http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar(v=vs.110).aspx"]ExecuteScalar[/URL]" instead of creating a DataReader.[/QUOTE]
Well I just don't want to create different functions if one can do the thing?
[editline]16th December 2013[/editline]
[code]
public int GetLatestID(String type)
{
String query = "SELECT MAX(Id) FROM "+type;
String connStr = ConfigurationManager.ConnectionStrings["RevsConnectionString"].ConnectionString;
SqlConnection sqli = new SqlConnection(connStr);
sqli.Open();
SqlCommand cmd = new SqlCommand(query, sqli);
String dr = cmd.ExecuteScalar().ToString();
var firstColumn = cmd.ExecuteScalar();
int id = 0;
if (firstColumn != null)
{
id = Convert.ToInt32(firstColumn.ToString());
}
return id;
}
[/code]
Now it gives me:Input string was not in a correct format.
[editline]16th December 2013[/editline]
Derp... I am an idiot, I missed and didn't add value to one of the fields...
Should remove
[QUOTE]
String dr = cmd.ExecuteScalar().ToString();
[/QUOTE]
Sorry, you need to Log In to post a reply to this thread.