C# Equivalent of SqlDataReader.Item

I'm new to C#, moving over from VB...

Is there an equivalent to VB's SqlDataReader.Item   Here's what I'm trying to do:

SqlCommand cmdSelectedRecord = new SqlCommand(SQLStmt,conn);
SqlDataReader SelectedRecord = cmdSelectedRecord.ExecuteReader();
txtLastName.Text = SelectedRecord.Item("lname");
txtFirstName.Text = SelectedRecord.Item("fname");
SelectedRecord.Close();

Obviously I have defined my SQLStmt and conn as the connection.  "lname" and "fname" are tables in the database that I am querying.  The build error I get is:

System.Data.SqlClient.SqlDataReader' does not contain a definition for 'Item'.

Thanks,

Jeff



Answer this question

C# Equivalent of SqlDataReader.Item

  • JonCole - MSFT

    try

    txtLastName.Text = selectedRecord["lname"].ToString();

    or

    txtLastName.Text = (String)selectedRecord["lname"];

    selectedRecord["lname"] can be explicitly cast to String.



  • Andreas Botsikas

    OK, that makes sense.  I changed it and now I get this build error:

    Cannot implicitly convert type 'object' to 'string'. An explicit conversion exists (are you missing a cast )

    I understand what is meant by "Cannot implicitly convert type 'object' to 'string'.", but what does "An explicit conversion exists (are you missing a cast )" mean   I tried

    txtLastName.Text = selectedRecord.ToString["lname"];

    but that didn't work.

    IIRC, this could be an implicit conversion in VB.

    Thanks,

    Jeff

  • Zwack

    Awesome!  Thanks for the help!

    Jeff

  • Dave Hunt

    In C# SqlDataReader.Item is the default indexer for the class.  So you can reference the object itself as an indexed property.

    e.g.,

    SqlDataReader selectedRecord = cmd.ExecuteReader();
    selectedRecord.Read();
    txtLastName.Text = selectedRecord["lname"];
    txtFirstName.Text = selectedRecord["fname"];
    selectedRecord.Close();
    ...

    should do the trick.


  • C# Equivalent of SqlDataReader.Item