views:

1247

answers:

3

I have a database column I simply need to check to see if a value is there.

        DataTable dt = masterDataSet.Tables["Settings"];
        DataColumn SETTINGS = dt.Columns["DEFAULTSETTINGS"];

I just need to iterate over the values in this column to see if a value exists. Help

+1  A: 

You iterate the rows, not the column

DataColumn SETTINGS = dt.Columns["DEFAULTSETTINGS"];
foreach(DataRow row in dt.Select())
{
    object columnValue = row[SETTINGS];
    // Do something with columnValue
}
Pierre-Alain Vigeant
+1  A: 

You can use linq in .net 3.5:


DataColumn col = dt.Columns["DEFAULTSETTINGS"];
object value = //expected value
bool valueExists = dt.AsEnumerable().Any(row => row.Field<object>(col).Equals(value));

EDIT: It seems from the comments you're trying to see if the 'DEFAULTSETTINGS' column contains the string 'default'. The Field extension method simply casts the object in the datarow at that column into the given type, so you can change the type parameter rather than use ToString(). So for your example you can probably use this:


DataColumn col = dt.Columns["DEFAULTSETTINGS"];
bool valueExists = dt.AsEnumerable().Any(row => "default".Equals(row.Field<string>(col), StringComparison.OrdinalIgnoreCase);
Lee
LINQ is good; even shorter would be `.AsEnumerable().Contains(value)`.
Pavel Minaev
I'm getting "the name 'col' dooes not exist in current context' bool valueExists = dt.AsEnumerable().Any(row => row.Field<object>(col).Equals(value));
zion
Yes that would be better, I don't know why I did it that way really...
Lee
@zion - use SETTINGS instead of col if your example above is the actual code
Lee
neither of those is working, I'm not getting errors but It's baffling. string value = "default"; //expected value bool valueExists = dt.AsEnumerable().Any(row => row.Field<object>(SETTINGS).ToString().Equals(value)); StatusText.Text = valueExists.ToString();
zion
it di'nt work still I'm getting a false result from the bool instead of true because hte 'dfault does exist'
zion
Are you sure it actually contains the value "default" (and not, say, "Default" or "DEFAULT" - i.e. case difference)?
Pavel Minaev
positive 'default'
zion
+1  A: 

There's no need to use Linq or iterate manually through your DataRows as plain old ADO.NET has a couple of solutions such as DataTable.Select and DataView.RowFilter.


string value = "default"; 
bool found = dt.Select("DEFAULTSETTINGS = " + value).Length > 0;

It's obvious that once you get the filtered rows, you can do whatever you want with them. In my example, I just checked to see if any row was within the criteria but you can manipulate them how you see fit.

Alfred Myers