Note that there are some explanatory texts on larger screens.

plurals
  1. POStoring useful data from SQL Server stored procedure
    primarykey
    data
    text
    <p>I'm very new to c# and trying to muddle my way around things. I'm used to coding on an iSeries (RPG) so c# is a very different concept to me.</p> <p>I have a stored procedure which returns a row (or rows) of data depending on the matching rows.</p> <p>Imagine my table <em>users</em> holds the following columns:</p> <pre><code>UserId, CompanyId, FirstName, LastName, CompanyAdmin, AccountStatus, UserName. </code></pre> <p>I have a stored procedure which returns all of these columns where there is a matching Company ID (ie.. <code>Select * from users where CompanyId = 1</code>).</p> <p>I have created a class with matching fields as above and the appropriate get/set methods (ie. <code>public int UserId {get; set;}</code> etc).</p> <p>I've used a <code>SqlDataReader</code> and am attempting to load each field from my class with data from the reader, but I'm getting an error </p> <blockquote> <p>'reader["UserName"]' threw an exception of type </p> <p>'System.InvalidOperationException' object</p> <p>{System.InvalidOperationException}</p> </blockquote> <p>What am I missing? Ultimately I would like an object that has all of my fields defined that will match my result set from my SQL Server stored procedure.</p> <p>My code throwing the error looks like this..</p> <pre><code> public partial class Admin : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { DataSet ds = new DataSet("ot_Users"); using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString)) using (SqlCommand command = conn.CreateCommand()) { command.CommandText = "dbo.ot_User_GetByUserName"; command.CommandType = CommandType.StoredProcedure; command.Parameters.AddWithValue("@UserName", Environment.UserName); conn.Open(); SqlDataReader reader = command.ExecuteReader(); ot_Users user = new ot_Users(); while(reader.Read()) { user.CompanyId = (int) reader["CompanyId"]; user.UserId = (int) reader["UserId"]; user.FirstName = (String) reader["FirstName"]; user.LastName = (String) reader["LastName"]; user.CompanyAdmin = (bool) reader["CompanyAdmin"]; user.AccountStatus = (int) reader["AccountStatus"]; user.UserName = (String) reader["UserName"]; } reader.NextResult(); CompanyName.Text = user.FirstName.ToString(); } } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload