Finding a field in a dataset c #

I am querying a mySQL database and storing the response in a datatable. I need to check a specific column to check if it is empty or null.Below is what I am doing

DataTable dataTab = new DataTable("ServiceOrderProtocol");

string strQuery = "select OrderID, ServiceOrder, ExternalID, Project_key, ProjectType from ServiceOrder;";

using (MySqlCommand cmd = new MySqlCommand(strQuery, conn))
{
using (MySqlDataAdapter sqlDa = new MySqlDataAdapter(cmd))
 {
 sqlDa.Fill(dataTab);
 return dataTab;
 }}

      

Now I'm not sure how to check if the ExternalID field returned from the request stored in the dataTab is null or empty.

+3


source to share


1 answer


If you want to know if any of the rows in the table contain a null value in the field ExternalID

:

bool anyNullExternalID = dataTab.AsEnumerable().Any(r => r.IsNull("ExternalID"));

      

If you want to know if all values ​​are null:

bool allNullExternalID = dataTab.AsEnumerable().All(r => r.IsNull("ExternalID"));

      



If you want all strings to be null:

IEnumerable<DataRow> allNullExternalIDRows = dataTab.AsEnumerable()
    .Where(r => r.IsNull("ExternalID"));

      


If it is not int

(e.g. title) but string

you want to include the null

empty line as well, add|| string.IsNullOrEmpty(r.Field<string>("ExternalID"))

+1


source







All Articles