Remove Row from DataTable Depending on Condition - c#

I have a List that holds some IDs. I want to remove the rows from a DataTable where = ListLinkedIds
List<string> ListLinkedIds = new List<string>(); //This has values such as 6, 8, etc.
DataSet ds = new DataSet();
SqlDataAdapter da = null;
DataTable dt = new DataTable();
da = new SqlDataAdapter("SELECT TicketID, DisplayNum, TranstypeDesc, SubQueueId, EstimatedTransTime,LinkedTicketId FROM vwQueueData WHERE (DATEADD(day, DATEDIFF(day, 0, Issued), 0) = DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0)) AND QueueId = #QueueId AND SubQueueId = #SubQueueId AND LinkedTicketId != #LinkedTicketId AND Called IS NULL", cs);
da.SelectCommand.Parameters.AddWithValue("#QueueId", Queue);
da.SelectCommand.Parameters.AddWithValue("#SubQueueId", SubQueue);
da.SelectCommand.Parameters.AddWithValue("#LinkedTicketId", ListLinkedIds[x]);
da.Fill(ds);
//Removes from DataTable
for (int x = 0; x < ListLinkedIds.Count(); x++)
{
//Remove Row from DataTable Where ListLinkedIds[x]
}
gvMain.DataSource = ds;
gvMain.DataBind();
I tried dt.Rows.RemoveAt(remove) but that removes only the row number. I want to remove every row that is in the ListLinkedIds.

Using LINQ you can create a new DataTable like:
DataTable newDataTable = dt.AsEnumerable()
.Where(r=> !ListLinkedIds.Contains(r.Field<string>("IDCOLUMN")))
.CopyToDataTable();

You can select the rows and then remove the returned result.
public void test() {
List<string> ListLinkedIds = new List<string>(); //This has values such as 6, 8, etc.
DataSet ds = new DataSet();
SqlDataAdapter da = null;
DataTable dt = new DataTable();
//Removes from DataTable
for (int x = 0; x < ListLinkedIds.Count(); x++)
{
DataRow[] matches = dt.Select("ID='" + ListLinkedIds[x] + "'");
foreach (DataRow row in matches) {
dt.Rows.Remove(row);
}
}
}

Try Delete after datatable is populated.
for (int x = 0; x < ListLinkedIds.Count(); x++)
{
foreach (DataRow dr in dt.rows)
{
if(dr["id"] == ListLinkedIds[x])
dr.Delete();
}
dt.AcceptChanges();
}

Related

'row' argument cannot be null.Parameter name: row

I am trying to load back values from a CSV to my class. Then display the values to my datatable. However, I get the error even after my values have been loaded into the class and placed inside the intended columns (See Figure 1). The error occurred at dt.Rows.Add(dr);. Below is my code:
public Newdatagrid()
{
InitializeComponent();
//Do datatable
ds = new DataSet();
dt = new DataTable();
dt.Columns.Add("Bus Model", typeof(string));//0
dt.Columns.Add("Bus Type", typeof(string));//1
dt.Columns.Add("Mileage", typeof(string));//2
if (Savestate.vehnochange_list.Count > 0)
{
foreach (DataRow dr in dt.Rows)
{
dr["Bus Model"] = Savestate.busmodel_list[Savestate.busmodel_list.Count];//0
dr["Bus Type"] = Savestate.bustype_list[Savestate.bustype_list.Count];//1
dr["Mileage"] = Savestate.busmileage_list[Savestate.busmileage_list.Count];//2
}
dt.Rows.Add(dr);
this.dataGridView2.DataSource = dt;
}
}
I think you want something like this:
public Newdatagrid()
{
InitializeComponent();
//Do datatable
ds = new DataSet();
dt = new DataTable();
dt.Columns.Add("Bus Model", typeof(string));//0
dt.Columns.Add("Bus Type", typeof(string));//1
dt.Columns.Add("Mileage", typeof(string));//2
if (Savestate.vehnochange_list.Count > 0)
{
for (int i=0; i < Savestate.vehnochange_list.Count; ++i)
{
DataRow dr = dt.NewRow();
dr["Bus Model"] = Savestate.busmodel_list[i];//0
dr["Bus Type"] = Savestate.bustype_list[i];//1
dr["Mileage"] = Savestate.busmileage_list[i];//2
dt.Rows.Add(dr);
}
this.dataGridView2.DataSource = dt;
}
}

How to add rows to datagridview while datagridview is bind

I have a datagridview and I filled with data.
DataTable table = new DataTable();
dataGridView1.DataSource = table;
con = new SqlDataAdapter("SELECT * FROM TABLE "'", con);
ds = new System.Data.DataSet();
con .Fill(ds, "TABLE");
My problem is I have to add rows manually like the code below but it is just add one row.But what I need foreach's count row.
foreach (var a in names.Split(new char[] { ';' }))
{
DataRow newRow = table.NewRow();
table.Rows.Add(newRow);
dataGridView2.Rows[i + 1].Cells[3].Value = a.ToString();
i = i +1;
}
Try to use
DataTable dataTable = (DataTable)dataGridView2.DataSource;
DataRow drToAdd = dataTable.NewRow();
drToAdd[3] = a.ToString();
dataTable.Rows.Add(drToAdd);

Delete Row From Data Table

I want to Delete the Multiple records from the DataTable
For example :
in my case PaperId is Repeating several Times.I want to Delete it all Duplicate records.
i have written code but loop is giving error
DataSet ds = new DataSet();
sqlDad.Fill(ds);
DataTable dt1 = new DataTable();
ds.Tables.Add(dt1);
dt1 = ds.Tables[0];
DataTable dt2 = new DataTable();
dt2 = dt1;
List<DataRow> rowsToDelete = new List<DataRow>();
foreach(DataRow dr in ds.Tables[0].Rows)
{
int r = ds.Tables[0].Columns.Count;
string x = dr.ItemArray[0].ToString();
int counter = 0;
foreach (DataRow dr1 in ds.Tables[0].Rows)
{
if (x == dr1.ItemArray[0].ToString())
{
counter++;
}
if (counter > 1)
{
rowsToDelete.Add(dr1);
foreach (DataRow row in rowsToDelete)
{
dt2.Rows.Remove(row);
}
dt2.AcceptChanges();
rowsToDelete.Clear();
}
}
Using the DefaultView of the DataTable and setting the sort order on the column that you don't want repeats to appear. You could loop over the rows and delete all the rows after the first one
// Work on the first table of the DataSet
DataTable dt1 = ds.Tables[0];
// No need to work if we have only 0 or 1 rows
if(dt1.Rows.Count <= 1)
return;
// Setting the sort order on the desidered column
dt1.DefaultView.Sort = dt1.Columns[0].ColumnName;
// Set an initial value ( I choose an empty string but you could set to something not possible here
string x = string.Empty;
// Loop over the row in sorted order
foreach(DataRowView dr in dt1.DefaultView)
{
// If we have a new value, keep it else delete the row
if(x != dr[0].ToString())
x = dr[0].ToString();
else
dr.Row.Delete();
}
// Finale step, remove the deleted rows
dt1.AcceptChanges();
Try This
DataRow[] rows;
rows=dataTable.Select("UserName = 'ABC'"); // UserName is Column Name
foreach(DataRow r in rows)
r.Delete();
If you want to remove the entire row from DataTable ,
try this
DataTable dt = new DataTable(); //User DataTable
DataRow[] rows;
rows = dt.Select("UserName = 'KarthiK'");
foreach (DataRow row in rows)
dt.Rows.Remove(row);

how to store multiple datatable into a single dataset

I have multiple datatable. I want to show all the datatable rows into a single gridview.
How can I do that?
DataTable dtbag101 = (DataTable)Session["bag101"];
DataTable dtwallet111 = (DataTable)Session["wallet111"];
DataSet ds= new DataSet();
ds.Tables.Add(dtbag101);
ds.Tables.Add(dtwallet111);
GridView1.DataSource= ds;
GridView1.DataBind();
The column names for both datatable are the same.
Here I was trying to use dataset but only first DataTable i.e. datbag101 was showing in the gridview.
How can I show all the values in one gridview?
Provided that your two data tables have the same columns, you can UNION them with some handy LINQ.
DataTable dtbag101 = (DataTable)Session["bag101"];
DataTable dtwallet111 = (DataTable)Session["wallet111"];
var result = dtbag101.AsEnumerable().Union(dtwallet111.AsEnumerable());
GridView1.DataSource = result;
GridView1.DataBind();
Otherwise try use DataTable.Merge:
DataTable dtbag101 = (DataTable)Session["bag101"];
DataTable dtwallet111 = (DataTable)Session["wallet111"];
dtbag101.Merge(dtwallet111, true);
GridView1.DataSource = dtbag101;
GridView1.DataBind();
I'm not sure why this isn't working for you. Try this method (grabbed from here):
public static DataTable Union(DataTable First, DataTable Second)
{
//Result table
DataTable table = new DataTable("Union");
//Build new columns
DataColumn[] newcolumns = new DataColumn[First.Columns.Count];
for(int i=0; i < First.Columns.Count; i++)
{
newcolumns[i] = new DataColumn(
First.Columns[i].ColumnName, First.Columns[i].DataType);
}
table.Columns.AddRange(newcolumns);
table.BeginLoadData();
foreach(DataRow row in First.Rows)
{
table.LoadDataRow(row.ItemArray,true);
}
foreach(DataRow row in Second.Rows)
{
table.LoadDataRow(row.ItemArray,true);
}
table.EndLoadData();
return table;
}
Call the method with your two datatables:
GridView1.DataSource = Union(dtbag101, dtwallet111);
You can simply use DataTable.Merge method
DataTable dtbag101 = (DataTable)Session["bag101"];
DataTable dtwallet111 = (DataTable)Session["wallet111"];
dtbag101.Merge(dtwallet111); //Merge action
GridView1.DataSource= dtbag101;
GridView1.DataBind();
I dont know much about this. Just referred it now.
or else
try for loop
DataSet ds = new DataSet();
addTables(dtbag101);
addTables(dtwallet111); //ds will be merge of both tables here
private void addTables(DataTable dt)
{
for(int intCount = ds.Tables[0].Rows.Count; intCount < dt.Rows.Count;intCount++)
{
for(int intSubCount = 0;intSubCount < dt.Columns.Count; intSubCount++)
{
ds.Tables[0].Rows[intCount][intSubCount] = dt.Rows[intCount][intSubCount];
}
}
}
You may need to use DataTable.Merge
DataTable dtAll = new DataTable();
dtAll = dtbag101 .Copy();
dtAll.Merge(dtwallet111, true);
GridView1.DataSource= dtAll;
GridView1.DataBind();
Edit to show how it should work
private void BindGridWithMergeTables()
{
DataTable dt1 = new DataTable();
DataTable dt2 = new DataTable();
dt1.Columns.Add("ID");
dt2.Columns.Add("ID");
DataRow dr1 = dt1.NewRow();
DataRow dr2 = dt2.NewRow();
dr1["ID"] = "1";
dr2["ID"] = "2";
dt1.Rows.Add(dr1);
dt2.Rows.Add(dr2);
DataTable dtAll = new DataTable();
dtAll = dt1.Copy();
dtAll.Merge(dt2, true);
dataGridView1.DataSource = dtAll;
dataGridView1.DataBind();
}

Convert datatable to datareader

For Performance improvement I want to convert datatable to datareader. I can not do that through query. So is there any other way to do so?
I know this is old, but the answers here seem to have missed the point of the OPs question.
DataTables have a method called CreateDataReader which will allow you to convert a DataTable to a DbDataReader object. In this case a DataTableReader.
DataTable table = new DataTable();
//Fill table with data
//table = YourGetDataMethod();
DataTableReader reader = table.CreateDataReader();
I should point out that this will not increase performance since you should be using one or the other.
Here are some more resources on the matter:
DataReader Vs DataTable
Is datareader quicker than dataset when populating a datatable?
For example
public DataTable ConvertDataReaderToDataTable(SqlDataReader dataReader)
{
DataTable datatable = new DataTable();
DataTable schemaTable = dataReader.GetSchemaTable();
try
{
foreach (DataRow myRow in schemaTable.Rows)
{
DataColumn myDataColumn = new DataColumn();
myDataColumn.DataType = myRow.GetType();
myDataColumn.ColumnName = myRow[0].ToString();
datatable.Columns.Add(myDataColumn);
}
while (dataReader.Read())
{
DataRow myDataRow = datatable.NewRow();
for (int i = 0; i < schemaTable.Rows.Count; i++)
{
myDataRow[i] = dataReader[i].ToString();
}
datatable.Rows.Add(myDataRow);
myDataRow = null;
}
schemaTable = null;
return datatable;
}
catch (Exception ex)
{
Error.Log(ex.ToString());
return datatable;
}
}
Use DataTable constructor,
DataTable table = new DataTable();
//Fill table with data
DataTableReader reader = new DataTableReader(table);
Good Look!
public DataTable GetTable(IDataReader _reader)
{
DataTable dataTable1 = _reader.GetSchemaTable();
DataTable dataTable2 = new DataTable();
string[] arrayList = new string[dataTable1.Rows.Count];
for (int i = 0; i < dataTable1.Rows.Count; i++)
{
DataColumn dataColumn = new DataColumn();
if (!dataTable2.Columns.Contains(dataTable1.Rows[i]["ColumnName "].ToString()))
{
dataColumn.ColumnName = dataTable1.Rows[i]["ColumnName "].ToString();
dataColumn.Unique = Convert.ToBoolean(dataTable1.Rows[i]["IsUnique "]);
dataColumn.AllowDBNull = Convert.ToBoolean(dataTable1.Rows[i]["AllowDBNull "]);
dataColumn.ReadOnly = Convert.ToBoolean(dataTable1.Rows[i]["IsReadOnly "]);
dataColumn.DataType = (Type)dataTable1.Rows[i]["DataType "];
arrayList[i] = dataColumn.ColumnName;
dataTable2.Columns.Add(dataColumn);
}
}
dataTable2.BeginLoadData();
while (_reader.Read())
{
DataRow dataRow = dataTable2.NewRow();
for (int j = 0; j < arrayList.Length; j++)
{
dataRow[arrayList[j]] = _reader[arrayList[j]];
}
dataTable2.Rows.Add(dataRow);
}
_reader.Close();
dataTable2.EndLoadData();
return dataTable2;
}

Categories

Resources