how to check data table row has empty space - c#

how to check datatable row has empty space?
i know how to check datatable row has null or not now i want to know empty row
foreach (DataRow _dr in obj_dt.Rows)
{
if (obj_dt.Rows[0]["Measurement"] != DBNull.Value)
{
combo_mesurmnt.Items.Add(obj_dt.Rows[0]["Measurement"].ToString());
}
}

foreach (DataRow _dr in obj_dt.Rows)
{
if (obj_dt.Rows[0]["Measurement"].tostring() != "")
{
combo_mesurmnt.Items.Add(obj_dt.Rows[0]["Measurement"].ToString());
}
}
try this...,

use IsNullOrEmpty
var rowContent = combo_mesurmnt.Items.Add(obj_dr.Rows[0]["Measurement"].ToString());
if (!IsNullOrEmpty(rowContent))
{
combo_mesurmnt.Items.Add(rowContent);
}

First, you have a mistake in your code:
You access obj_dt.Rows[0], although you probably mean _dr.
Then, there are a few things that could be improved:
You can use DataRow.Field<string>, which is more elegant than ToString if you know that the underlying DB field is of type string.
Now, to answer your question: It depends on what you mean by "empty space".
If you mean "empty", you can just check with String.IsNullOrEmpty:
foreach (DataRow _dr in obj_dt.Rows)
{
string measurement = _dr.Field<String>("Measurement");
if (!String.IsNullOrEmpty(measurement))
combo_mesurmnt.Items.Add(measurement);
}
If strings consisting only of spaces should be filtered as well, the following will work:
foreach (DataRow _dr in obj_dt.Rows)
{
string measurement = _dr.Field<String>("Measurement");
if (measurement != null && measurement.Trim() != "")
combo_mesurmnt.Items.Add(measurement);
}

Related

How to find a string in a Column in a DataTable

I am trying to find a fast way to find a string in a Column in a DataTable and add it to a comboBox, and this is the code i tried so far :
adapter = new SqlDataAdapter("Select Id_Editeur ID,Libelle_Editeur Editeur from Editeur", myClass.cnx);
adapter.Fill(myClass.ds, "Editeur");
foreach (String str in myClass.ds.Tables["Editeur"].Columns[1].ToString())
editeurBox.Properties.Items.Add(str);
and that's doesn't work it gives me this error :
foreach statement cannot operate on variables of type
'System.Data.DataColumn' because 'System.Data.DataColumn' does not
contain a public definition for 'GetEnumerator'
How can I do that ? (I don't want the for loop solution).
foreach (var row in myClass.ds.Tables["Editeur"].AsEnumerable())
{
editeurBox.Properties.Items.Add(row[1].ToString());
}
or Full linq-style:
editeurBox.Properties.Items.AddRange(
myClass.ds.Tables["Editeur"]
.AsEnumerable()
.Select(dr => dr[1].ToString()
);
You can try with this code - based on LINQ Field operator
var results = from myRow in myDataTable.AsEnumerable()
where myRow.Field<string>("RowNo") == "yourSearch"
select myRow;
I think you need to loop through the rows and grab the column that you want. Your code is trying to loop through the column collection which doesn't contain any data:
foreach (DataRow row in myClass.ds.Tables["Editeur"].Rows)
editeurBox.Properties.Items.Add(row[1].ToString());
string TableSelect;
DataTable dt = GetSomeData();
foreach (DataRow row in dt.Rows)
{
TableSelect = "EmplNo = " + row["EmplNo"].ToString();
DataRow[] foundrows;
foundrows = dt.Select(TableSelect);
if (foundrows.Count() > 0)
{
//do something useful here :)
}
}

Which is more efficient, looping through DataTable or more database calls?

Basically I have a DataTable with a rows containing part numbers and a couple of columns that contain information on those parts.
In order to compare those infos with the data we have in the database, I have determined I have one of two options.
Option 1 - Loop through each row and SELECT the data
void CompareData(DataTable dt) {
foreach (DataRow entry in dt.Rows) {
//select that row
DataRow dbEntry = ExecuteQuery("SELECT * FROM Parts WHERE partno='" + entry["partno"] + "'").Rows[0];
if (dbEntry["info1"] == entry["info1"]) {
//do something
} else {
//do something
}
}
}
Option 2 - SELECT all data at once and compare via loops
void CompareData(DataTable dt, string[] parts) {
DataTable dbEntries = ExecuteQuery("SELECT * FROM Parts WHERE partno IN('" + String.Join(parts, "','") + "')");
foreach (DataRow entry in dt.Rows) {
foreach (DataRow dbEntry in dt.Rows) {
if (dbEntry["partno"] == entry["partno"]) {
if (dbEntry["info1"] == entry["info1"]) {
//do something
} else {
//do something
}
}
}
}
}
They both seem pretty inefficient, so I'm not really sure what to do. Would LINQ speed this process up? I've never really used it but just browsing around it looks like something that could help.
Make as few DB calls as possible. You'll be more efficient 99.9% of the time. (general rule to code by)

How to copy value of one data column into another data column in the same data table C#?

I want to copy itemarray[4] of datatable to itemarray[6] of that datatable. I used this code and I didn’t see any changes:
foreach (DataRow dr_row in dt_table.Rows)
{
foreach (var field_value in dr_row.ItemArray)
{
object cell_data = field_value;
if (dr_row.ItemArray[6].ToString() == "")
{
dr_row.ItemArray[6] = dr_row.ItemArray[4];
}
original_data += cell_data.ToString();
}
original_data += Environment.NewLine;
}
First of all never do this:
dr_row.ItemArray[6].ToString() == ""
Change it to this:
dr_row.ItemArray[6].ToString() == String.Empty
or:
String.IsNullOrEmpty(dr_row.ItemArray[6].ToString())
However, that is just good practice. Now, to the problem that you are facing.
What the Itemarray does is, it creates a new array from the row, so that if you change the array, you do not change the row.
Do this:
dr_row[6] = dr_row[4];
Should work.
Try this,
foreach (DataRow dr_row in dt_table.Rows)
{
dr_row[6] = dr_row[4];
}
and use System.Text.StringBuilder to append data.
System.Text.StringBuilder sb = new StringBuilder();
sb.Append(value1);

Problem removing row in datatable while enumerating

I get the following error while I try to delete a row while looping through it.
C#: Collection was modified; enumeration operation may not execute
I've been doing some research for a while, and I've read some similar posts here, but I still haven't found the right answer.
foreach (DataTable table in JobsDS.Tables)
{
foreach (DataRow row in table.Rows)
{
if (row["IP"].ToString() != null && row["IP"].ToString() != "cancelled")
{
string newWebServiceUrl = "http://" + row["IP"].ToString() + "/mp/Service.asmx";
webService.Url = newWebServiceUrl;
string polledMessage = webService.mpMethod(row["IP"].ToString(), row["ID"].ToString());
if (polledMessage != null)
{
if (polledMessage == "stored")
{
removeJob(id);
}
}
}
}
}
any help would be greatly appreciated
Instead of using foreach, use a reverse for loop:
for(int i = table.Rows.Count - 1; i >= 0; i--)
{
DataRow row = table.Rows[i];
//do your stuff
}
Removing the row indeed modifies the original collection of rows. Most enumerators are designed to explode if they detect the source sequence has changed in the middle of an enumeration - rather than try to handle all the weird possibilities of foreaching across something that is changing and probably introduce very subtle bugs, it is safer to simply disallow it.
You cannot modify a collection inside of a foreach around it.
Instead, you should use a backwards for loop.
If you want to remove Elements from a loop on a list of Elements, the trick is to use a for loop, start from the last Element and go to the first Element.
In your example :
int t_size = table.Rows.Count -1;
for (int i = t_size; i >= 0; i--)
{
DataRow row = table.Rows[i];
// your code ...
}
Edit : not quick enough :)
Also, if you depend on the order that you process the rows and a reverse loop does not work for you. You can add the rows that you want to delete to a List and then after you exit the foreach loop you can delete the rows added to the list. For example,
foreach (DataTable table in JobsDS.Tables)
{
List<DataRow> rowsToRemove = new List<DataRow>();
foreach (DataRow row in table.Rows)
{
if (row["IP"].ToString() != null && row["IP"].ToString() != "cancelled")
{
string newWebServiceUrl = "http://" + row["IP"].ToString() + "/mp/Service.asmx";
webService.Url = newWebServiceUrl;
string polledMessage = webService.mpMethod(row["IP"].ToString(), row["ID"].ToString());
if (polledMessage != null)
{
if (polledMessage == "stored")
{
//removeJob(id);
rowsToRemove.Add(row);
}
}
}
}
rowsToRemove.ForEach(r => removeJob(r["ID"].ToString()));
}
Somehow removeJob(id) changes one of the IEnumerables your enumerating (table.Rows or JobsDS.Tables, from the name of the method I guess it would be the latter), maybe via DataBinding.
I'm not sure the backwards for is going to work directly because it seems you're removing an element enumerated in the outer foreach from within the inner foreach. It's hard to tell without more info about what happens in removeJob(id).

export null values to xml from a dataset

If you have a null value in a field in a dataset and export it to xml it does "remove" the field tag .. anyway to avoid this..
An empty tag does not have the same meaning as null, especially for strings. How would you make the difference if the tag was present but empty?
//Try changing values of cells.
foreach (DataRow row in dtPr.Rows)
{
for (int i = 0; i < dtPr.Columns.Count; i++)
{
dtPr.Columns[i].ReadOnly = false;
if (string.IsNullOrEmpty(row[i].ToString()))
{
if (dtPr.Columns[i].DataType == typeof(string))
row[i] = string.Empty;
else if (dtPr.Columns[i].DataType == typeof(int))
row[i] = 0;
else if (dtPr.Columns[i].DataType == typeof(DateTime))
row[i] = new DateTime(1753, 1, 1);
}
}
}
Think of NULL as a state and everything else as a value. So if you want a blank value, just send in an empty string (single white space)
you have to paint your method with an attribute that tells it to stay there. not near my winblows machine so cant give you the actual code. but would look something like this,
[XMLElement(IsNullable = true)]
myProperty {get;set;}

Categories

Resources