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

3 Answers3

4

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
  • 22,635
  • 8
  • 65
  • 101
3

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
  • 6,384
  • 1
  • 40
  • 68
1

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
  • 142,018
  • 20
  • 234
  • 287
  • LINQ is good; even shorter would be `.AsEnumerable().Contains(value)`. – Pavel Minaev Sep 08 '09 at 23:34
  • I'm getting "the name 'col' dooes not exist in current context' bool valueExists = dt.AsEnumerable().Any(row => row.Field(col).Equals(value)); –  Sep 08 '09 at 23:34
  • @zion - use SETTINGS instead of col if your example above is the actual code – Lee Sep 08 '09 at 23:37
  • 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(SETTINGS).ToString().Equals(value)); StatusText.Text = valueExists.ToString(); –  Sep 08 '09 at 23:53
  • it di'nt work still I'm getting a false result from the bool instead of true because hte 'dfault does exist' –  Sep 09 '09 at 00:31
  • Are you sure it actually contains the value "default" (and not, say, "Default" or "DEFAULT" - i.e. case difference)? – Pavel Minaev Sep 09 '09 at 00:35