Search code examples
c#sqloracle-databasetextbox

How to select Max Value from database in Textbox


i have simple table item and a text box textbox1 now i want to show max value in textbox i am using the command but code not work

item table: CREATE TABLE TableItem( ItemId NUMBER(10) NOT NULL, ItemName VARCHAR2(40) NOT NULL, UnitId NUMBER(10) NOT NULL, CategoryId NUMBER(10) NOT NULL, ItemStatus NUMBER(1) NOT NULL, SupplierId NUMBER(10)NOT NULL );

and item table insert data:

INSERT INTO TableItem(ITEMID,ITEMNAME,UNITID,CATEGORYID,ITEMSTATUS,SUPPLIERID)
VALUES(01,'Product-1',21,10,1,51);
INSERT INTO TableItem(ITEMID,ITEMNAME,UNITID,CATEGORYID,ITEMSTATUS,SUPPLIERID)
VALUES(02,'Product-2',22,11,1,52);
INSERT INTO TableItem(ITEMID,ITEMNAME,UNITID,CATEGORYID,ITEMSTATUS,SUPPLIERID)
VALUES(03,'Product-3',23,12,1,53);
INSERT INTO TableItem(ITEMID,ITEMNAME,UNITID,CATEGORYID,ITEMSTATUS,SUPPLIERID)
VALUES(04,'Product-4',24,14,1,53);
INSERT INTO TableItem(ITEMID,ITEMNAME,UNITID,CATEGORYID,ITEMSTATUS,SUPPLIERID)
VALUES(05,'Product-5',21,12,1,53);
INSERT INTO TableItem(ITEMID,ITEMNAME,UNITID,CATEGORYID,ITEMSTATUS,SUPPLIERID)
VALUES(06,'Product-5',23,12,1,52);

now i need max value of itemid

con.Open();
try
{
    OleDbCommand cmd4 = new OleDbCommand("SELECT MAX(ItemId)  FROM TableItem", con);

    textBoxInsert.Text = cmd4.ExecuteScalar().ToString();

}
finally
{


}

con.Close();

Solution

  • You need to create a data adapter, it will fetch your SQL in your database based on your connection. After that you will get a table as result, so you just need to add it to your DataTable and get the rows. There is more interesting implementations, but with this code you can see if it everything is working fine, I've implemented a MySQL version like this:

    DataTable _datatable = new DataTable();
    MySQLDataAdapter _adapter = new MySQLDataAdapter("SELECT * FROM TEST_TABLE", connection)
    _adapter.Fill(_datatable);
    
    myTextBox.Text = _datatable.Rows[0]["ID"].ToString();
    

    On your case, you just need to replace MySQLDataAdapter with OracleDataAdapter, from OracleClient

    Reference:

    https://msdn.microsoft.com/pt-br/library/system.data.oracleclient.oracledataadapter(v=vs.110).aspx