I have this SQL Table:
TABLE: Info
COLUMNS:| Name | Value
--------|----------|------------------
ROW: | Server | 255.255.255.255
ROW: | Host | 212.212.212.212
ROW: | User | Admin
I’m selecting this table like that: SELECT * FROM Info
Now after I got all in this table.
I want to get the value Where Name = 'Server' and put it into the Server variable.
What is the best method to do it in C#?
DataSet? DataReader? And how can I accomplish this?
If you didn’t understand what I need here is another good explanation thx to Tim:
I’m trying to get a specified column’s value based on the value in another column of the same row
Based on your latest comments, it appears that you want to get all the rows in the table, and then be able to select a given row based on the Name column.
A DataTable would be best if your program is going to need to access the different rows at different times – as long as the DataTable is in memory/cached, you can pull the value for any name at any time.
If you just need to do it once, a SqlDataReader would probably be faster, but its forward-only.
DataTable example:
Assuming you’ve already filled the DataTable (name info in the example), you can use the Select method:
DateReader example:
Based upon @Kobe’s code, simply check the Name each time you advance to the next record, and then pull the Value out:
There are some caveats to be aware of. First, the Select method of the DataTable returns an array of DataRow, so if more than one record has “Server” in the Name column, you’ll get multiple results. If that’s by design, that’s fine – just loop through the array of DataRows.
Second, if there are a lot of rows in the table, or there is the potential down the road, the reader may be slower depending on where the record of interest is in the table. And if you’re dealing with the possibility of multiple records in the table matching the Name criteria, it’s probably easier all around to just stick with a DataTable.