473,566 Members | 2,763 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

SqlDataReader accessed only by field ordinals?

I notice that using the SqlDataReader requires the use of ordinal field
references rather than by name.
For example,

do while (myDataReader.R ead())
Console.Write(m yDataReader.Get Int32(0).ToStri ng() + Chr(9))
Console.Write(m yDataReader.Get String(2) + " " +
myDataReader.Ge tString(1) + Chr(9))
Console.Write(m yDataReader.Get String(3) + Chr(9))
if (myDataReader.I sDBNull(4)) then
Console.Write(" N/A" + Chr(10))
else
Console.Write(m yDataReader.Get Int32(4).ToStri ng() + Chr(10))
end if
loop

Is there a way for me to read data from SQL by field name (ie: column name)
rather than by ordinal? It is much easier to program this way and also
handles situations where fields have been inserted or otherwise changed
position in a table.

Thanks in advance,

Tom

Nov 21 '05 #1
5 2209
It works fine with field names. You just need to do a cast (CType for VB) to
the correct type, since you get Object back.

Tom Dacon
Dacon Software Consulting

"Tom Edelbrok" <an*******@anon ymous.com> wrote in message
news:EDY6e.2547 6$vt1.11985@edt nps90...
I notice that using the SqlDataReader requires the use of ordinal field
references rather than by name.
For example,

do while (myDataReader.R ead())
Console.Write(m yDataReader.Get Int32(0).ToStri ng() + Chr(9))
Console.Write(m yDataReader.Get String(2) + " " +
myDataReader.Ge tString(1) + Chr(9))
Console.Write(m yDataReader.Get String(3) + Chr(9))
if (myDataReader.I sDBNull(4)) then
Console.Write(" N/A" + Chr(10))
else
Console.Write(m yDataReader.Get Int32(4).ToStri ng() + Chr(10))
end if
loop

Is there a way for me to read data from SQL by field name (ie: column name) rather than by ordinal? It is much easier to program this way and also
handles situations where fields have been inserted or otherwise changed
position in a table.

Thanks in advance,

Tom

Nov 21 '05 #2
Tom,
It works fine with field names. You just need to do a cast (CType for VB)
to
the correct type, since you get Object back.


Casting in VBNet is DirectCast, CType is converting

Cor

Nov 21 '05 #3
Tom,

In addition to the other Tom the link too the item from the reader

http://msdn.microsoft.com/library/de...sitemtopic.asp

\\\
Dim arrImage() As Byte = DirectCast(rdr. Item("Photo"), Byte())
///

I hope this helps,

Cor


Nov 21 '05 #4
Tom,

Looking at your problem, I got this idea for an often asked question for
filling a datable while using a progressbar
\\\Needs a progressbar, a button and a datagrid
Private Sub Button1_Click(B yVal sender As System.Object, _
ByVal e As System.EventArg s) Handles Button1.Click
Dim conn As New SqlClient.SqlCo nnection("Serve r=MyServer;" & _
"DataBase=North wind; Integrated Security=SSPI")
Dim cmd As New SqlClient.SqlCo mmand("Select Count(*) from
Employees", conn)
conn.Open()
ProgressBar1.Ma ximum = DirectCast(cmd. ExecuteScalar, Integer)
ProgressBar1.St ep = 1
ProgressBar1.Mi nimum = 0
cmd.CommandText = "SELECT * FROM Employees"
Dim rdr As SqlClient.SqlDa taReader = cmd.ExecuteRead er()
Dim dt As DataTable
While rdr.Read
If dt Is Nothing Then
dt = New DataTable
Dim dtschema As DataTable
dtschema = rdr.GetSchemaTa ble
For Each drschema As DataRow In dtschema.Rows
dt.Columns.Add( drschema("Colum nName").ToStrin g, _
Type.GetType(dr schema("DataTyp e").ToString ))
Next
End If
ProgressBar1.Pe rformStep()
Dim dr As DataRow = dt.NewRow
Dim tempObject(dt.C olumns.Count - 1) As Object
rdr.GetValues(t empObject) 'did not go in one time
dr.ItemArray = tempObject
dt.Rows.Add(dr)
Threading.Threa d.Sleep(500) 'only for showing
End While
DataGrid1.DataS ource = dt
rdr.Close()
conn.Dispose()
End Sub
///
Maybe it gives you as well some ideas?

Cor

"Tom Edelbrok" <an*******@anon ymous.com> schreef in bericht
news:EDY6e.2547 6$vt1.11985@edt nps90...
I notice that using the SqlDataReader requires the use of ordinal field
references rather than by name.
For example,

do while (myDataReader.R ead())
Console.Write(m yDataReader.Get Int32(0).ToStri ng() + Chr(9))
Console.Write(m yDataReader.Get String(2) + " " +
myDataReader.Ge tString(1) + Chr(9))
Console.Write(m yDataReader.Get String(3) + Chr(9))
if (myDataReader.I sDBNull(4)) then
Console.Write(" N/A" + Chr(10))
else
Console.Write(m yDataReader.Get Int32(4).ToStri ng() + Chr(10))
end if
loop

Is there a way for me to read data from SQL by field name (ie: column
name) rather than by ordinal? It is much easier to program this way and
also handles situations where fields have been inserted or otherwise
changed position in a table.

Thanks in advance,

Tom

Nov 21 '05 #5
Tom,
| Is there a way for me to read data from SQL by field name (ie: column
name)
| rather than by ordinal?
What I do is get the ordinals just before the loop using the
DataReader.GetO rdinalfunction.

Something like:

myDataReader = myCommand.Execu teReader(...)

Dim fieldId As Integer = myDataReader.Ge tOrdinal("Id")
Dim fieldLastName As Integer = myDataReader.Ge tOrdinal("LastN ame")
Dim fieldFirstName As Integer = myDataReader.Ge tOrdinal("First Name")
Dim fieldAddress As Integer = myDataReader.Ge tOrdinal("Addre ss")
Dim fieldAmount As Integer = myDataReader.Ge tOrdinal("Amoun t")

Do While (myDataReader.R ead())
Console.Write(m yDataReader.Get Int32(fieldId). ToString() +
Chr(9))
Console.Write(m yDataReader.Get String(fieldFir stName) + " " +
myDataReader.Ge tString(fieldLa stName) + Chr(9))
Console.Write(m yDataReader.Get String(fieldAdd ress) + Chr(9))
If (myDataReader.I sDBNull(fieldAm ount)) Then
Console.Write(" N/A" + Chr(10))
Else
Console.Write(m yDataReader.Get Int32(fieldAmou nt).ToString()
+ Chr(10))
End If
Loop

| It is much easier to program this way and also
| handles situations where fields have been inserted or otherwise changed
| position in a table.

When not using GetOrdinal as above, I've seen people use either constants or
Enums instead of integer literals to represent the ordinal positions...

Hope this helps
Jay
"Tom Edelbrok" <an*******@anon ymous.com> wrote in message
news:EDY6e.2547 6$vt1.11985@edt nps90...
|I notice that using the SqlDataReader requires the use of ordinal field
| references rather than by name.
| For example,
|
| do while (myDataReader.R ead())
| Console.Write(m yDataReader.Get Int32(0).ToStri ng() + Chr(9))
| Console.Write(m yDataReader.Get String(2) + " " +
| myDataReader.Ge tString(1) + Chr(9))
| Console.Write(m yDataReader.Get String(3) + Chr(9))
| if (myDataReader.I sDBNull(4)) then
| Console.Write(" N/A" + Chr(10))
| else
| Console.Write(m yDataReader.Get Int32(4).ToStri ng() + Chr(10))
| end if
| loop
|
| Is there a way for me to read data from SQL by field name (ie: column
name)
| rather than by ordinal? It is much easier to program this way and also
| handles situations where fields have been inserted or otherwise changed
| position in a table.
|
| Thanks in advance,
|
| Tom
|
|
|
Nov 21 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
6169
by: SC | last post by:
Hi, After a SqlDataReader.ExecuteReader method has returned, how can I get the field names of every column that were returned? It has to be possible, right? I looked through the different methods and properties but I couldn't find anything. Maybe I missed it!
5
12120
by: Wing | last post by:
Hi all, I execute a stored procedure in my C# code, assign the result to the SqlDataReader object and display it with datagrid. the question I like to ask, is possible to edit the datagrid output (eg. delete a row in the datagrid) and update the change in the corresponding table in the database? thanks for your time.
2
1625
by: Matt | last post by:
I just want to get the value of field UserName and Password in SqlDataReader object dr. But it yeields run-time error "Invalid attempt to read when no data is present" on line dr("UserName") and dr("Password") any ideas?? Dim sql As String = "select * from where UserName = '" & TextBox1.Text & "'" _ & "AND Password = '" & TextBox2.Text...
5
6579
by: Woody Splawn | last post by:
I have some code that looks like this: Dim SSN, LName, FName, M As String mySqlConnection = New SqlConnection(myConnectionString) Dim sql_Command As New SqlCommand( _ "Select SSN, LName, FName, M from Students WHERE (SSN = " + " '" + ProposedValue + "')", _ mySqlConnection) Try mySqlConnection.Open()
7
1705
by: Web learner | last post by:
I am trying to create a method GetDataFor(string column) becaues I have to repeat the same statements for several columns but I get an error as follows: The name 'dr' does not exist in the current context It seems the dr -the instance of sqlDataReader - is not becoming available to the method. How to make it available? This seems trivial and...
3
3246
by: dchristjohn | last post by:
I am currently developing a small windows application using Visual Basic via Visual Studio 2005. My database resides on a SQL 2000 server. I have a table with three fields: id (int, Not Null) lname (varchar(30), Not Null) fname (varchar(30), Not Null) I have one record in the table as follows:
12
7238
by: 2b|!2b==? | last post by:
I want to export my C++ classes in a DLL, using ordinal # - rather than by name. Will anyone care to enumerate through the steps required to do this? I am already failiar with exporting classes and symbols (both C++ and C) from a DLL. In the case of C functions, i also know how to export them by ordinal # - my main problem revolves around...
3
1841
by: Dom | last post by:
Still teaching myself about SQLDataReader and associated classes. I have to say, the new HELP screens from MS are just about useless!! Let's assume I have just read some records from a table into the SQLDataReader object, r. 1. Am I right to assume that accessing the fields as r is a little faster than r? 2. The elements of r are...
0
7584
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8108
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7644
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7951
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
5213
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3643
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3626
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2083
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
925
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.