Link to home
Start Free TrialLog in
Avatar of Paul Kahl
Paul KahlFlag for United States of America

asked on

Creating class function to retrieve single-row database content

I have this function:
public static DataSet getPageContentByID(int tableContentID)
    {
        SqlConnection SQLConn = new SqlConnection(MarComConnectionString());

        SqlCommand sqlCmd = new SqlCommand("spx_FetchOrrtaxWebsiteContentText", SQLConn);
        sqlCmd.CommandType = CommandType.StoredProcedure;

        SqlDataAdapter sqlAdp = new SqlDataAdapter(sqlCmd);

        sqlCmd.Parameters.Add("@output_id", SqlDbType.Int);
        sqlCmd.Parameters["@output_id"].Value = tableContentID;

        DataSet dtsData = new DataSet();
       
        try
        {
            SQLConn.Open();
            sqlAdp.Fill(dtsData);
        }
        finally
        {
            SQLConn.Close();
        }

        return dtsData;
    }

As you can see, it returns a dataset. What I would like to do is instead just have it return 1 piece of data, as the table in question only has 1 column I'm interested in, 1 row at a time (the sproc called, in fact, only outputs 1 row)

this would be easy in VB, as I could set the function as a string, but since I'm required to do this in C#, I'm not sure what to do.
Avatar of CaldNT
CaldNT

Use:

dtsData.Tables[0].Rows[0]


This will return a System.Data.DataRow with the first row from the first table in your DataSet. If the DataSet has only one table with one row this will be all the data in it.

Good luck!
Or if you just want one column:

public static getPageContentByID(int tableContentID)
{
   ...

  return dtsData.Tables[0].Rosw[0][0].ToString();

}
ASKER CERTIFIED SOLUTION
Avatar of dstanley9
dstanley9

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Paul Kahl

ASKER

Final function:

public static string getPageContentByID(int tableContentID)
    {
        SqlConnection SQLConn = new SqlConnection(MarComConnectionString());

        SqlCommand sqlCmd = new SqlCommand("spx_FetchOrrtaxWebsiteContentText", SQLConn);
        sqlCmd.CommandType = CommandType.StoredProcedure;

        SqlDataAdapter sqlAdp = new SqlDataAdapter(sqlCmd);

        sqlCmd.Parameters.Add("@output_id", SqlDbType.Int);
        sqlCmd.Parameters["@output_id"].Value = tableContentID;

        DataSet dtsData = new DataSet();

        try
        {
            SQLConn.Open();
            sqlAdp.Fill(dtsData);
        }
        finally
        {
            SQLConn.Close();
        }

        return dtsData.Tables[0].Rows[0][0].ToString();
    }

I changed the function to a String base instead of a DataSet base, since that's the true goal of it, but otherwise used the code you suggested. It worked perfectly! Thank you!