Click here to Skip to main content
15,892,059 members
Please Sign up or sign in to vote.
1.91/5 (4 votes)
See more:
I have tabe1 contains column3 which is NVARCHAR

I need to select the highest number in column3 and show it in a textbox
Posted
Comments
Gautham Prabhu K 7-Nov-15 10:57am    
If its a number why your storing it as NVARCHAR? and not as integer.
PIEBALDconsult 7-Nov-15 11:04am    
There are no numbers is a VARCHAR.
Maciej Los 9-Nov-15 14:05pm    
Number is a number and string is a string. String representation of number is not a number.

SQL Query:
select MAX(Column3) from table1

C#
DataTable table = new DataTable();
using (SqlConnection connection = new SqlConnection("ConnectionString"))
{
    using (SqlCommand cmd = new SqlCommand("select MAX(Column3) from table1", connection))
    {
        using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
        {
            adapter.Fill(table);
            textBox.Text = table.Rows[0].ToString();
        }
    }
}


http://www.w3schools.com/sql/sql_func_max.asp[^]
http://www.tutorialspoint.com/sql/sql-max-function.htm[^]

Using C# to connect to and query from a SQL database[^]
https://msdn.microsoft.com/en-us/library/fksx3b4f.aspx[^]

-KR
 
Share this answer
 
v2
Comments
Ahmed Zoeil 7-Nov-15 12:20pm    
it gives me an error :

Additional information: Fill: SelectCommand.Connection property has not been initialized.
Krunal Rohit 9-Nov-15 9:13am    
Answer is updated.

-KR
Rojalin Sahoo 9-Nov-15 7:24am    
Assign connection to command.
using (SqlCommand cmd = new SqlCommand("select MAX(Column3) from table1",connection))
Krunal Rohit 9-Nov-15 9:12am    
I knew I missed out something. :laugh:

-KR
SELECT MAX(COLUMN3) FROM TABLE1

IF THE COLUMN CONTAINS NUMBER THEN, IT WILL SHOW THE MAX NUMBER
 
Share this answer
 
SqlConnection con=new SqlConnection("//Connectionpath");
SqlCommand cmd=new SqlCommand();
SqlDataAdapter ada=new SqlDataAdapter();
DataTable dt=new Datatable();

cmd.Connection=con;
cmd.CommandText="SELECT MAX(COLUMN3) FROM TABLE1";
ada.SelectCommand=cmd;
ada.Fill(dt);

if(dt.Rows.Count>0)
{
textBox.Text = dt.Rows[0]["COLUMN3"].ToString();
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900