Warrior Forum - The #1 Digital Marketing Forum & Marketplace

Warrior Forum - The #1 Digital Marketing Forum & Marketplace (https://www.warriorforum.com/)
-   Programming (https://www.warriorforum.com/programming/)
-   -   C#(Windows Forms): How to get the MAX column value from a database table (SQL) (https://www.warriorforum.com/programming/721246-c-windows-forms-how-get-max-column-value-database-table-sql.html)

forme 4th December 2012 03:23 AM

C#(Windows Forms): How to get the MAX column value from a database table (SQL)
 
I have a table named invoicedetails in my database.
I have to get the max value of the invoiceNo column and display it after incremented that value by 1. I searched hours on the net and found several solutions. This is what I tried,

(no problem with the connection)
string connectionString = "path";
SqlConnection con;
con = new SqlConnection(connectionString);
con.Open();

SqlCommand cmd = new SqlCommand();
String query = "Select max(invoiceNo) from invoicedetails";
cmd.Connection = con;
cmd.CommandText = query;

int invNo = Convert.ToInt32(cmd.ExecuteScalar());
int newInv=invNo + 1;

textBoxInvoiceNo.Text = newInv.ToString();


I have put this code to the form load event. But the InvoiceNo text box displays nothing. And this
exception displays:-"Object cannot be cast fromDBNull to other types".
Where's the problem?

KirkMcD 4th December 2012 06:13 AM

Re: C#(Windows Forms): How to get the MAX column value from a database table (SQL)
 
Max(InvoiceNo) will be null if there are no values in the table.

forme 4th December 2012 06:39 AM

Re: C#(Windows Forms): How to get the MAX column value from a database table (SQL)
 
Well, there are few records in the table.

forme 4th December 2012 06:40 AM

Re: C#(Windows Forms): How to get the MAX column value from a database table (SQL)
 
Quote:

Originally Posted by KirkMcD (Post 7426813)
Max(InvoiceNo) will be null if there are no values in the table.

Well, there are few records in the table.

CreateSoft 4th December 2012 10:50 PM

Re: C#(Windows Forms): How to get the MAX column value from a database table (SQL)
 
From a quick glance, I don't see anything wrong, so I would suggest testing your query using a query analyzer and see if it really is returning data.

TrafficMystic 12th December 2012 03:45 AM

Re: C#(Windows Forms): How to get the MAX column value from a database table (SQL)
 
have you put an index and primary key on the table?

I suspect not.. add them and retry..


All times are GMT -6. The time now is 09:10 AM.