Summing Specific Column c# - c#

I wrote this formula here but for some reason it sums ALL the values in the amt column instead of the one that has the itemcolumn string. Any ideas?
foreach (DataGridViewRow row in itemGrid.Rows)
{
if (itemGrid.Rows[e.RowIndex].Cells["itemColumn"].Value.ToString() == itemcolumn)
total += Convert.ToDecimal(row.Cells["Amt"].Value.ToString());
}
Here's the full code so you can see what's going on here.
private void itemGrid_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
//
// [This string compares amt and amtvalue on Cell edit]
//
if (itemGrid.CurrentCell.ColumnIndex == 5 && isCalled)
{
// Prevents loop.
isCalled = false;
decimal total = 0;
string itemcolumn = String.Empty;
{
foreach (DataGridViewRow row in itemGrid.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
if (cell.Selected)
{
itemcolumn = Convert.ToString(row.Cells["itemColumn"].Value);
string strName = vendorBox.Text;
string Select = "select sum(case allocated when 'Received' then amt when 'Shipped' then -amt end) as amt from lineitem WHERE item='" + itemcolumn + "';";
MySql.Data.MySqlClient.MySqlConnection conDatabase = new
MySqlConnection(ConnectionString.connString);
MySql.Data.MySqlClient.MySqlCommand cmdDatabase = new
MySql.Data.MySqlClient.MySqlCommand(Select, conDatabase);
try
{
conDatabase.Open();
MySql.Data.MySqlClient.MySqlDataReader rdrRepairOrder;
rdrRepairOrder = cmdDatabase.ExecuteReader();
while (rdrRepairOrder.Read())
{
string rowz5 = string.Format("{0}", rdrRepairOrder.GetString(0));
string wut5 = rowz5.ToString();
itemamt = Convert.ToInt32(wut5);
}
rdrRepairOrder.Close();
conDatabase.Close();
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
MessageBox.Show("Error " + ex.Number + " has occurred: " + ex.Message,
"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
}
// Converts amt column.
// amt = The cell amount.
// itemamt = What's on the SQL table.
foreach (DataGridViewRow row in itemGrid.Rows)
{
if (itemGrid.Rows[e.RowIndex].Cells["itemColumn"].Value.ToString() == itemcolumn) total += Convert.ToDecimal(row.Cells["Amt"].Value.ToString());
}
MessageBox.Show("Total is: " + total.ToString());
int amt;
string amtz = itemGrid.Rows[e.RowIndex].Cells["Amt"].Value.ToString();
amt = Convert.ToInt32(amtz);
int value;
value = itemamt - amt;
if (value < 0)
{
MessageBox.Show("Cannot allocate more than what it is in inventory. You have " + itemamt.ToString() + " in stock.");
itemGrid[5, itemGrid.CurrentCell.RowIndex].Value = itemamt;
}
}
isCalled = true;
}

Instead of itemGrid.Rows[e.RowIndex], try using row in your condition.

Related

How to add values from selected fields through a DataReader to a DataGridView

I'm new to C#. I want to add data in selected fields of a table to a DataGridView. I used data reader. When executing only add one row. Second time of the while loop, error occurred as "Row provided already belongs to a DataGridView control". here my code. Anyone can help please...
public static void fillGrd(ref DataGridView obj, string tbl, string fld="*", string cond = "")
{
try
{
obj.Rows.Add();
DataGridViewRow row = (DataGridViewRow)obj.Rows[0].Clone();
obj.Rows.Clear();
cond = (cond == "") ? cond : " where " + cond;
string qry = "select " + fld+ " from " + tbl + cond;
cmd.CommandText = qry;
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
int ri = 0;
while (dr.Read())
{
for (int i = 0; i < dr.FieldCount - 1; i++)
{
row.Cells[i].Value = dr.GetString(i);
}
obj.Rows.Insert(ri,row);
ri++;
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error occured!" + ex.Message);
}
}

Insert string after 4 results

I'm using the following code to get results from a SQL Server:
string content = "Test value"
try {
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("select name from Persons",
myConnection);
myReader = myCommand.ExecuteReader();
while(myReader.Read())
{
Console.WriteLine("- " + myReader["name"].ToString());
}
} catch (Exception e) {
Console.WriteLine(e.ToString());
}
What I want is to insert the value of the string "Content" inside the while loop after 4 results, e.g:
Name 1 #
Name 2 #
Name 3 #
Name 4 #
Test value
Name 5 #
Just use an index variable:
var index = 0;
while(myReader.Read())
{
Console.WriteLine("- " + myReader["name"].ToString());
if (++index == 4) {
Console.WriteLine("Test value");
}
}
try this
string content = "Test value"
try
{
var counter = 1;
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("select name from Persons",
myConnection);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
if (counter == 4)
{
counter = 1;
Console.WriteLine(content);
}
Console.WriteLine("- " + myReader["name"].ToString());
counter++;
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Try This:
int index = 0;
while (myReader.Read()) {
if ((index != 4)) {
index++;
}
else {
// Intert your Code for the Content String Here
}
}

I can't seem to get my Gridview to update to my SQL Server database

Here is my current code behind for the OnRowUpdating event and SQL statement to update the database. It is throwing an exception:
System.NullReferenceException: Object reference not set to an instance of an object.error
Code:
protected void GV_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
TextBox txtSu = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox1"); // each textbox refers to the Am then Pm day
TextBox txtSu1 = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox2");// sun pm
TextBox txtMo = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox3");// mon am
TextBox txtMo1 = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox4");//mon pm
TextBox txtTu = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox5");
TextBox txtTu1 = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox6");
TextBox txtWe = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox7");
TextBox txtWe1 = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox8");
TextBox txtTh = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox9");
TextBox txtTh1 = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox10");
TextBox txtFr = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox11");
TextBox txtFr1 = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox12");
TextBox txtSa = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox13");
TextBox txtSa1 = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox14");
string sql = "UPDATE tblEMPLOYEE SET EmployeeID=#ID, " +
"AvailSun=#AvSu, " +
"AvailSun1=#AvSu1, " +
"AvailMon=#AvMo, " +
"AvailMon1=#AvMo1, " +
"AvailTues=#AvTu, " +
"AvailTues1=#AvTu1, " +
"AvailWedn=#AvWe, " +
"AvailWedn1=#AvWe1, " +
"AvailThurs=#AvTh, " +
"AvailThurs1=#AvTh1, " +
"AvailFri=#AvFr, " +
"AvailFri1=#AvFr1, " +
"AvailSat=#AvSa, " +
"AvailSat1=#AvSa1 " +
"WHERE EmployeeID=#ID";
CMethods.executeNonQuery(sql, "#ID", txtID.Text, "#AvSu", txtSu.Text, "#AvSu1", txtSu1.Text, "#AvMo", txtMo.Text, "#AvMo1", txtMo1.Text, "#AvTu", txtTu.Text, "#AvTu1", txtTu1.Text, "#AvWe", txtWe.Text, "#AvWe1", txtWe1.Text, "#AvTh", txtTh.Text, "#AvTh1", txtTh1.Text, "#AvFr", txtFr.Text, "#AvFr1", txtFr1.Text, "#AvSa", txtSa.Text, "#AvSa1", txtSa1.Text, "#ID", ID);
GV.EditIndex = -1;
fillUsers();
}
private void fillUsers()
{
GV.DataSource = CMethods.returnTable("SELECT * FROM tblEMPLOYEE WHERE EmployeeID=" + lblEmployee.Text);
GV.DataBind();
}
In Cmethods
public static class CMethods
{
public static DataTable returnTable(String CommandText, params Object[] values)
{
SqlConnection con =
new SqlConnection(ConfigurationManager.ConnectionStrings["Provider"].ConnectionString);
SqlCommand cmd = new SqlCommand(CommandText, con);
for (int i = 0; i < values.Length; i += 2)
{
cmd.Parameters.AddWithValue((String)values[i], values[i + 1]);
}
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds, "tbl");
return ds.Tables["tbl"];
}
public static bool executeNonQuery(String CommandText, params Object[] values)
{
bool bln = true;
SqlConnection con =
new SqlConnection(ConfigurationManager.ConnectionStrings["Provider"].ConnectionString);
SqlCommand cmd = new SqlCommand(CommandText, con);
for (int i = 0; i < values.Length; i += 2)
{
cmd.Parameters.AddWithValue((String)values[i], values[i + 1]);
}
try
{
con.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
bln = false;
}
finally
{
con.Close();
}
return bln;
}
public static double returnValue(string str)
{
double dblTemp = 0.0D;
string strTemp = String.Empty;
bool blnFirstDec = false;
bool blnFirstNeg = false;
for (int i = 0; i < str.Length; i++)
{
if (str.Substring(i, 1) == "-")
{
blnFirstNeg = true;
}
if (IsNumeric(str.Substring(i, 1)) || str.Substring(i, 1) == ".")
{
if (str.Substring(i, 1) == ".")
{
if (!blnFirstDec)
{
blnFirstDec = true;
strTemp += ".";
}
}
else
{
strTemp += str.Substring(i, 1);
}
}
}
FindControl control may not return control if you not provide correct control id
for example you have given txtBo13(missing x) but actually you may have txtBox13,
so below code return null for txtSa
TextBox txtSa = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBo13");
when you call Text property of txtSa you will get NullReferenceException
if you have given id as txtBox13, change the code accordingly
TextBox txtSa = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox13");
And also you may have forgot to set #student parameter value

DateTime Subtraction

My registration program logs people in with their name, id and "Time In:" when they scan themselves in, and hides them, but adds "Time Out: " to their name, and vice versa. What im looking to do is every time the person scans themselves "In" I want it to look at the Time "In"'s amd "out"'s and calculate thr total time IN the office.
Attached is the code :
private string CreateTimeEntry(string current)
{
var indexIn = current.LastIndexOf("Time In : "); // Get the last index of the word "in"
var indexOut = current.LastIndexOf("Time Out : "); // Get the last index of the word out
string timeIn = current + " " + "Time In : ";
string timeOut = current + " " + "Time Out : ";
if (indexOut > indexIn)
{
// if the last "out" comes after the last "in"
return timeIn;
}
else
{
// If the last "in" comes after the last "out"
return timeOut;
}
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
SqlConnection DBConnection = new SqlConnection("Data Source=DATABASE;Initial Catalog=imis;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
Object returnValue;
string txtend = textBox1.Text;
if (e.KeyChar == 'L')
{
DBConnection.Open();
}
if (DBConnection.State == ConnectionState.Open)
{
if (textBox1.Text.Length != 6) return;
{
cmd.CommandText = ("SELECT last_name +', '+ first_name from name where id =#Name");
cmd.Parameters.Add(new SqlParameter("Name", textBox1.Text.Replace(#"L", "")));
cmd.CommandType = CommandType.Text;
cmd.Connection = DBConnection;
returnValue = cmd.ExecuteScalar() + "\t (" + textBox1.Text.Replace(#"L", "") + ")";
DBConnection.Close();
bool found = false;
System.DateTime resultTime1 = new System.DateTime(;
foreach (var item in listBox1.Items)
{
var itemEntry = item.ToString();
string newEntry = CreateTimeEntry(itemEntry) + DateTime.Now.ToString("HH:mm") + " " + "Total Time: " + resultTime1 ;
if (itemEntry.Contains(returnValue.ToString()))
{
var indexIn = itemEntry.LastIndexOf("Time In : ");
var indexOut = itemEntry.LastIndexOf("Time Out : ");
if (indexOut > indexIn)
{
listBox2.Items.Remove(item);
listBox1.Items.Add(newEntry);
found = true;
break;
}
else
{
listBox1.Items.Remove(item);
listBox2.Items.Add(newEntry);
found = true;
break;
}
}
}
if (!found)
{
string newEntry2 = "";
foreach (string str in listBox2.Items)
{
var itemEntry2 = str;
newEntry2 = CreateTimeEntry(itemEntry2) + DateTime.Now.ToString("HH:mm");
//if (listBox2.Items.Contains(returnValue.ToString()))
if (listBox2.Items.Contains(str) && str.Contains(textBox1.Text))
{
var indexIn = itemEntry2.LastIndexOf("Time In : ");
var indexOut = itemEntry2.LastIndexOf("Time Out : ");
if (indexOut > indexIn)
{
listBox2.Items.Remove(str);
listBox1.Items.Add(newEntry2);
found = true;
break;
}
}
}
var itemEntry = listBox1.Items.ToString();
var itemEntry1 = listBox2.Items.ToString();
if (!listBox1.Items.Contains(newEntry2))
{
listBox1.Items.Add(returnValue + " " + "Time In : " + DateTime.Now.ToString("HH:mm"));
}
}
}
textBox1.Clear();
System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(fullFileName);
foreach (object item1 in listBox1.Items)
SaveFile.WriteLine(item1.ToString());
SaveFile.Flush();
SaveFile.Close();
if (listBox1.Items.Count != 0) { DisableCloseButton(); }
else
{
EnableCloseButton();
}
Current_Attendance_Label.Text = "Currently " + listBox1.Items.Count.ToString() + " in attendance.";
e.Handled = true;
}
You can get the difference between two DateTime objects using the following:
TimeSpan timePassed = timeOut.Subtract(timeIn);
where timeOut and timeIn are DateTime objects.
If you need the difference (or either of the times) displayed somewhere as a string, I would recommend converting them to strings only after doing the calculations that you need. Always work with strongly typed objects when possible.

How to remove empty rows from DataTable

I am working on importing data from an Excel sheet to database. The Excel sheet contains few empty rows and I want to remove those empty rows, then insert cleared data into database.
I have written a code by referring other code, this is the code for inserting values:
OleDbConnection cnn = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + txtExcelFile.Text + "';Extended Properties= 'Excel 8.0;HDR=Yes;IMEX=1'");
//DataTable dt = new DataTable();
try
{
cnn.Open();
OleDbDataAdapter data = new OleDbDataAdapter("select * from [Customers$]", cnn);
data.Fill(dsExcel);
dgvCustomers.ColumnHeadersVisible = false;
SqlConnection connection = new SqlConnection("Data Source=COMPUTER-8EB749;Initial Catalog=KITS;Integrated Security=true");
connection.Open();
for (int i = 0; i < dsExcel.Tables[0].Rows.Count; i++)
{
string ID = ds.Tables[0].Rows[i][0].ToString();
Int16 CustID = Convert.ToInt16(ID);
string CustName = dsExcel.Tables[0].Rows[i][1].ToString();
string CardScheme = dsExcel.Tables[0].Rows[i][2].ToString();
string Outlet = dsExcel.Tables[0].Rows[i][3].ToString();
string TerminalNum = dsExcel.Tables[0].Rows[i][4].ToString();
Int32 Terminal = Convert.ToInt32(TerminalNum);
string Date1 = dsExcel.Tables[0].Rows[i][5].ToString();
DateTime Date = Convert.ToDateTime(Date1);
string Time = dsExcel.Tables[0].Rows[i][6].ToString();
DateTime DateTime = Convert.ToDateTime(Time);
string Amount1 = ds.Tables[0].Rows[i][7].ToString();
double Amount = Convert.ToDouble(Amount1);
SqlCommand com = new SqlCommand("insert into Customer(CustID,CustName,CardScheme,Outlet,TerminalNum,TranDate,TranDateTime,Amount) values ('" + CustID + "','" + CustName + "','" + CardScheme + "','" + Outlet + "','" + Terminal + "','" + Date + "','" + DateTime + "','" + Amount + "')", connection);
com.ExecuteNonQuery();
}
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
MessageBox.Show("Data Inserted Successfully.");
}
Can anyone say me how can I remove empty rows so that i can insert only data?!
This will remove all rows that which each of it's columns contain either nothing or white space:
dataTable = dataTable.Rows
.Cast<DataRow>()
.Where(row => !row.ItemArray.All(field => field is DBNull ||
string.IsNullOrWhiteSpace(field as string)))
.CopyToDataTable();
Try this.
public bool InsertRowsToDataBase()
{
try
{
DataTable excelTable = new DataTable();
string connString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + txtExcelFile.Text + "';Extended Properties= 'Excel 8.0;HDR=Yes;IMEX=1'";
using (OleDbConnection cnn = new OleDbConnection(connString))
{
string query = "select * from [Customers$]";
using (OleDbDataAdapter data = new OleDbDataAdapter(query, cnn))
{
data.Fill(excelTable);
}
}
dgvCustomers.ColumnHeadersVisible = false;
connString = "Data Source=COMPUTER-8EB749;Initial Catalog=KITS;Integrated Security=true";
using (SqlConnection connection = new SqlConnection(connString))
{
connection.Open();
for (int i = 0; i < excelTable.Rows.Length; i++)
{
//takes from the 3rd row
if (i > 1)
{
DataRow row = excelTable.Rows[i];
object ID = row[0];
if (ID != null && !String.IsNullOrEmpty(ID.ToString().Trim()))
{
Int16 CustID = Convert.ToInt16(ID);
string CustName = row[1].ToString();
string CardScheme = row[2].ToString();
string Outlet = row[3].ToString();
string TerminalNum = row[4].ToString();
Int32 Terminal = Convert.ToInt32(TerminalNum);
string Date1 = row[5].ToString();
DateTime Date = Convert.ToDateTime(Date1);
string Time = row[6].ToString();
DateTime DateTime = Convert.ToDateTime(Time);
string Amount1 = row[7].ToString();
double Amount = Convert.ToDouble(Amount1);
string columnNames = "CustID,CustName,CardScheme,Outlet,TerminalNum,TranDate,TranDateTime,Amount";
string query = String.Format("insert into Customer(0}) values ('{1}', '{2}','{3}','{4}','{5}','{6}','{7}','{8}')",
columnNames, CustID, CustName, CardScheme, Outlet, Terminal, Date, DateTime, Amount);
using (SqlCommand com = new SqlCommand(query, connection))
{
com.ExecuteNonQuery();
}
}
}
//this is your last row. do whatever you want with this
DataRow lastRow = excelTable.Rows[excelTable.Rows.Count - 1];
}
}
return true;
}
catch (Exception exception)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(exception);
return false;
}
}
Please note that I am just checking if ID is null and not inserting any such rows as ID will be the PK in your table.
This will remove all empty rows from the data table:
DataTable dt = dt.Rows
.Cast<DataRow>()
.Where(row => !row.ItemArray.All(f => f is DBNull))
.CopyToDataTable();
OR
DataTable dt = dt.Rows
.Cast<DataRow>()
.Where(row => !row.ItemArray.All(f => f is DBNull ||
string.IsNullOrEmpty(f as string ?? f.ToString())))
.CopyToDataTable();
try
{
OpenOleDBConnection();
OleDbDataAdapter dataAdapter = new OleDbDataAdapter("select * from [" + SelectedSheet + "]", Connection);
dataAdapter.Fill(DataTable);
if ((DataTable != null) && (DataTable.Rows != null) && (DataTable.Rows.Count > 0))
{
List<System.Data.DataRow> removeRowIndex = new List<System.Data.DataRow>();
int RowCounter = 0;
foreach (System.Data.DataRow dRow in DataTable.Rows)
{
for(int index = 0; index < DataTable.Columns.Count; index++)
{
if (dRow[index] == DBNull.Value)
{
removeRowIndex.Add(dRow);
break;
}
else if (string.IsNullOrEmpty(dRow[index].ToString().Trim()))
{
removeRowIndex.Add(dRow);
break;
}
}
RowCounter++;
}
// Remove all blank of in-valid rows
foreach (System.Data.DataRow rowIndex in removeRowIndex)
{
DataTable.Rows.Remove(rowIndex);
}
}
}
catch(Exception e)
{
WPFMessageBox.Show(e.Message, Globalization.GetValue("Import_ImportOption_FormHeader"), WPFMessageBoxButtons.OK, WPFMessageBoxImage.Error);
}
finally
{
CloseOleDBConnection();
}
Here I m also skipping the rows if they have blank entry in any of the row.
I've made this private method that does the trick.
It takes a DataTable as argument and returns the same DataTable without empty rows.
private DataTable StripEmptyRows(DataTable dt)
{
List<int> rowIndexesToBeDeleted = new List<int>();
int indexCount = 0;
foreach(var row in dt.Rows)
{
var r = (DataRow)row;
int emptyCount = 0;
int itemArrayCount = r.ItemArray.Length;
foreach(var i in r.ItemArray) if(string.IsNullOrWhiteSpace (i.ToString())) emptyCount++;
if(emptyCount == itemArrayCount) rowIndexesToBeDeleted.Add(indexCount);
indexCount++;
}
int count = 0;
foreach(var i in rowIndexesToBeDeleted)
{
dt.Rows.RemoveAt(i-count);
count++;
}
return dt;
}
To check Empty Rows
Foreach(DataRow as row in datable.Rows) {
var isEmpty = row.ItemArray.All(c => c is DBNull);
if(!isEmpty) {
//Your Logic
}
}
Why not simply ignore empty rows directly before you are inserting them?
if(string.IsNullOrEmpty(ID + CustName + CardScheme /*.. and so on */))
{
continue;
}
Like this:
for (int i = 0; i < dsExcel.Tables[0].Rows.Count; i++)
{
string ID = ds.Tables[0].Rows[i][0].ToString();
Int16 CustID = Convert.ToInt16(ID);
string CustName = dsExcel.Tables[0].Rows[i][1].ToString();
string CardScheme = dsExcel.Tables[0].Rows[i][2].ToString();
string Outlet = dsExcel.Tables[0].Rows[i][3].ToString();
string TerminalNum = dsExcel.Tables[0].Rows[i][4].ToString();
Int32 Terminal = Convert.ToInt32(TerminalNum);
string Date1 = dsExcel.Tables[0].Rows[i][5].ToString();
DateTime Date = Convert.ToDateTime(Date1);
string Time = dsExcel.Tables[0].Rows[i][6].ToString();
DateTime DateTime = Convert.ToDateTime(Time);
string Amount1 = ds.Tables[0].Rows[i][7].ToString();
double Amount = Convert.ToDouble(Amount1);
/*** Add this if-statement to you code! ***/
if(string.IsNullOrEmpty(ID + CustName + CardScheme + Outlet + TerminalNum + Date1 + Time + Amount1))
{
continue;
}
SqlCommand com = new SqlCommand("insert into Customer(CustID,CustName,CardScheme,Outlet,TerminalNum,TranDate,TranDateTime,Amount) values ('" + CustID + "','" + CustName + "','" + CardScheme + "','" + Outlet + "','" + Terminal + "','" + Date + "','" + DateTime + "','" + Amount + "')", connection);
com.ExecuteNonQuery();
}
I modified Cfrim's answer. You need to check for both empty and whitespace strings. The white space comes from the deleted cells and the empty space comes from deleted data.
private DataTable StripEmptyRows(DataTable dt)
{
List<int> rowIndexesToBeDeleted = new List<int>();
int indexCount = 0;
foreach(var row in dt.Rows)
{
var r = (DataRow)row;
int emptyCount = 0;
int itemArrayCount = r.ItemArray.Length;
foreach (var i in dr.ItemArray)
{
if (string.IsNullOrEmpty(i.ToString()) || string.IsNullOrWhiteSpace(i.ToString()))
emptyCount++;
}
if(emptyCount == itemArrayCount) rowIndexesToBeDeleted.Add(indexCount);
indexCount++;
}
int count = 0;
foreach(var i in rowIndexesToBeDeleted)
{
dt.Rows.RemoveAt(i-count);
count++;
}
return dt;
}
for (int i = dt.Rows.Count - 1; i >= 0; i--) {
if (dt.Rows[i][1] == DBNull.Value) {
dt.Rows[i].Delete();
}
}
dt.AcceptChanges();
return dt;
Your DB itself has empty rows?? Thats quite strange. May be filter it while you do a select query by saying a primary key column is not NULL
public static DataTable RemoveEmptyRows(DataTable dt)
{
List removeRowIndex = new List();
foreach (DataRow dRow in dt.Rows)
{
for (int index = 0; index < dt.Columns.Count; index++)
{
if (string.IsNullOrEmpty(dRow[index].ToString().Trim()))
{
removeRowIndex.Add(dRow);
break;
}
else if (dRow[index] == DBNull.Value)
{
removeRowIndex.Add(dRow);
break;
}
}
}
foreach (DataRow rowIndex in removeRowIndex)
{
dt.Rows.Remove(rowIndex);
}
return dt;
}
this works perfect for me:
dt.Load(cmd.ExecuteReader());
var x = dt.Rows.Cast<DataRow>()
.Where(row => !Array.TrueForAll(row.ItemArray, value =>
{ return value.ToString().Length == 0; }
));
dt = x.CopyToDataTable();
I change a little in #Levitikon post https://stackoverflow.com/a/9233696/5848472
with #shA.t comment , and this code remove all empty Rows and Columns in datatable:
dt = ds.Tables[tablename].Rows
.Cast<DataRow>()
.Where(row => !row.ItemArray.All(field => field is DBNull ||
string.IsNullOrWhiteSpace(field as string ?? field.ToString())))
.CopyToDataTable();
foreach (var column in dt.Columns.Cast<DataColumn>().ToArray())
{
if (dt.AsEnumerable().All(dr => dr.IsNull(column)))
dt.Columns.Remove(column);
}
This worked for me. If we do not check rows and directly do CopyToDataTable() then you may get an exception when the data table has empty rows.
var rows = tbl.Rows.Cast<DataRow>()
.Where(row => !row.ItemArray.All(field => field is DBNull || String.IsNullOrWhiteSpace(field as string ?? field.ToString())));
if (rows.Any())
tbl = rows.CopyToDataTable();
Based on existing answers I use following
public static bool AllColumnsEmpty(this DataRow row)
{
if (row == null)
{
return true;
}
else
{
foreach (var value in row.ItemArray)
{
if (value != null && value.ToString() != "")
{
return false;
}
}
return true;
}
}
public static void RemoveEmptyRows(this DataTable data)
{
var rowsToDelete = data.Rows.Cast<DataRow>()
.Where(row => row.AllColumnsEmpty())
.ToList();
rowsToDelete.ForEach(row => data.Rows.Remove(row));
}
Usage is then
someDatatable.RemoveEmptyRows();
To remove Empty Rows from DataTable:
dt.Rows.Cast<DataRow>().ToList().FindAll(Row =>
{ return String.IsNullOrEmpty(String.Join("", Row.ItemArray)); }).ForEach(Row =>
{ dt.Rows.Remove(Row); });

Categories

Resources