I have the following scenario which I’ve been using to return a single row from a SQL database. After I’ve returned the data I’m simply using it to populate fields on my web form.
Example database class:
public class DBAccess
{
public DataTable ReturnContactInfo(int userID)
{
// executes a stored procedure, populates a datatable, then returns it
}
}
Example using the class to populate a theoretical customer name field:
protected void Page_Load(object sender, EventArgs e)
{
if(!isPostBack)
{
DBAccess db = new DBAccess();
DataTable dt = db.ReturnContactInfo(1);
if (dt.Rows.Count > 0)
{
customerName.Text = Convert.ToString(dt.Rows[0]["customerName"]);
}
}
}
Is there a better or more efficient way of doing this (“this” being returning a single data row to pull data from)? This approach certainly works, but it’s a bit cumbersome to have to type dt.Rows[0][string] when I’m always and only going to be working with the row at index 0. Please keep in mind that I’d like to be able to keep all the data layer stuff extracted to a single class. Which (from what I understand) means I cannot use a SqlDataReader because it has to be closed when finished so I can’t return it from my data layer class.
Define a class with the members you want as properties. Then populate and return that object. You can make this simple using tools like “dapper”:
Then:
Now: