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);
Related
How to Add DataTable value in DataSet Using every foreach loop in ASP.NET C# Webform, Actually I have one gridview and in gridview selected checkbox data should only download to xl.
I have below code for export to xl button.
foreach (GridViewRow row in gv_TotalAllReg.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
bool isChecked = ((CheckBox)row.FindControl("chk_box")).Checked;
if (isChecked == true)
{
//var ds = new DataSet();
//var dt = new DataTable("RegistrationDetails");
int index = row.RowIndex;
bo.Para1 = "4";
bo.Para2 = "Innovation";
bo.Para3 = gv_TotalAllReg.DataKeys[index].Values[0].ToString();//Id
}
}
}
dt = bl.Admin_GetInnovationbaseonParaType(bo);
if (gv_TotalAllReg.Rows.Count > 0)
{
dt.TableName = "RegistrationDetails";
ds.Tables.Add(dt);
ExcelHelper.ToExcel(ds, "ApplicationDetails.xls", Page.Response);
btnExport.Visible = true;
}
Actually base on selected checkbox in gridview that data is not showing in xl sheet, only last selected data is showing in xl sheet.
I am not getting logic ds.Tables.Add(dt); to add dt values in ds every foreach loop. I need all selected data into xl sheet. Why last select data only coming in xl sheet.
Instead of adding each row of datatable to dataset you can add entire datatable to dataset.
Dataset can hold collection of datatables so you can add multiple datatable to dataset.
DataTable tbl = new Datatable();//or your method that returns datatable.
DataSet ds = new DataSet(); //new dataset object
ds.Tables.Add(tbl); //add datatable object in dataset object.
Update
DataTable dt= new DataTable();
//Columns that should present in datatable
dt.Columns.Add("SN");
dt.Columns.Add("MyField");
int sn = 1;
foreach (GridViewRow row in gv_TotalAllReg.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
bool isChecked = ((CheckBox)row.FindControl("chk_box")).Checked;
if (isChecked == true)
{
DataRow row = dt.NewRow();
//Add necessary columns to row by index.
row[0] = sn;
row[1] = gv_TotalAllReg.DataKeys[index].Values[0].ToString();
dt.Rows.Add(row);
sn++;
}
}
}
if (tbl .Rows.Count > 0)
{
ds.Tables.Add(dt);
ExcelHelper.ToExcel(ds, "ApplicationDetails.xls", Page.Response);
btnExport.Visible = true;
}
I think you can crete DataTable before foreach loop, and add rows inside it. Here is an example with adding and retrieving data from DataTable:
DataTable dt = bl.Admin_GetInnovationbaseonParaType(bo);
if (gv_TotalAllReg.Rows.Count > 0)
{
dt.TableName = "RegistrationDetails";
ds.Tables.Add(dt);
foreach (GridViewRow row in gv_TotalAllReg.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
bool isChecked = ((CheckBox)row.FindControl("chk_box")).Checked;
if (isChecked == true)
{
// inserting data row
dr = dt.NewRow();
dr.SetField("Column_Name", "your_Value");
dt.Rows.Add(dr);
int index = row.RowIndex;
bo.Para1 = "4";
bo.Para2 = "Innovation";
bo.Para3 = gv_TotalAllReg.DataKeys[index].Values[0].ToString();//Id
}
}
}
ExcelHelper.ToExcel(ds, "ApplicationDetails.xls", Page.Response);
btnExport.Visible = true;
}
Retrieving data:
string[] values = dt.AsEnumerable().Select(r => r.Field<string>("Value")).ToArray();
The DataTable (dt) stores the retrieved values of carID's and makes so it stores like 3 rows within the DataTable, I also have another DataTable called dt2 which also stores carID's and makes, I am trying to loop through each row in the dt to see if any carID stored in the dt exists in any of the rows in dt2, here is what I have so far:
DataTable dt = w.getUserCars(userID);
foreach (DataRow dr in dt.Rows)
{
string carID = dr["carID"].ToString();
}
How do I do this?
You should be able to achieve this using DataTable.Select() method. You are on the right track. You just need to add the method to find the Row(s) in dt2.
DataTable dt = w.getUserCars(userID);
DataRow[] foundRows;
foreach (DataRow dr in dt.Rows)
{
string carID = dr["carID"].ToString();
foundRows = dt2.Select("carID = " + carID);
// do stuff here with foundRows
foreach (DataRow r in foundRows)
{
r.Delete();
}
}
Why does SqlDataAdapter's Fill method not allow me to add a row with the same its own rows' value as appearance? I could not success to provide a row's value that appears at the same row with filled one in DataTable.
Check this out:
using (SqlDataAdapter a = new SqlDataAdapter("SELECT SIPNO, SERINO, TARIH FROM SNOHAREKETLER WHERE Cast(TARIH as DATE) BETWEEN '2015/03/19' AND '2015/03/20' AND (TEZNO = 'T23' OR TEZNO = 'T31') AND CIKTI is null", c))
{
// 3
// Use DataAdapter to fill DataTable
DataTable t = new DataTable();
a.Fill(t);
t.Columns.Add("MyColumn", typeof(string));
DataRow workRow;
int iGetCount = t.Rows.Count;
for (int i = 0; i <= iGetCount - 1; i++)
{
workRow = t.NewRow();
workRow["MyColumn"] = i;
t.Rows.Add(workRow);
}
// 4
// Render data onto the screen
dataGridView1.DataSource = t;
}
Here is the solution of my issue. I searched and consulted someone. My issue was trying to add a NewRow and this causes the issue.
DataTable t = new DataTable();
a.Fill(t);
DataColumn newCol = new DataColumn("NewColumn", typeof(string));
newCol.AllowDBNull = true;
t.Columns.Add(newCol);
foreach (DataRow row in t.Rows)
{
row["NewColumn"] = "With String";
}
dataGridView1.DataSource = t;
I need to store datagridview selected rows into datatable in single columns like below
DataGridView
user1 user2 user3
ram sam ravi
DataTable
values
ram
sam
ravi
I tried below code
DataTable dt = new DataTable();
dt.Columns.Add("values",typeof(string));
foreach (DataGridViewRow gridRow in dataGridView_settings.Rows)
{
DataRow dtRow = dt.NewRow();
for (int i = 0; i < dataGridView_settings.Columns.Count; i++)
{
dtRow[0] = gridRow.Cells[i].Value;
dt.Rows.Add(dtRow);
}
}
Problem is its adding only one row in the datatable then showing error "This row already belongs to this table."
You should move the DataRow creation to the inner for
DataTable dt = new DataTable();
dt.Columns.Add("values",typeof(string));
foreach (DataGridViewRow gridRow in dataGridView_settings.Rows)
{
for (int i = 0; i < dataGridView_settings.Columns.Count; i++)
{
DataRow dtRow = dt.NewRow();
dtRow[0] = gridRow.Cells[i].Value;
dt.Rows.Add(dtRow);
}
}
I have a DataTable dt1 that contains this columns : PRODUCT_ID,MIN_VALUE,MAX_VALUE,AMOUNT
and another DataTable dt2 that contains this columns : ID,MIN,MAX,POINT_TO_ADD
dt1 contains multiple rows that I want to copy them to dt2 how can I do that ?
try this
foreach (DataRow sourcerow in dt1.Rows)
{
DataRow destRow = dt2.NewRow();
destRow["ID"] = sourcerow["PRODUCT_ID"];
destRow["MIN"] = sourcerow["MIN_VALUE"];
destRow["MAX"] = sourcerow["MAX_VALUE"];
destRow["POINT_TO_ADD"] = sourcerow["AMOUNT"];
dt2.Rows.Add(destRow);
}
Try this:
for(int i=0;i<dt1.Rows.Count;i++){
DataRow dr = dt2.NewRow();
dr["ID"] = dt1.Rows[i]["PRODUCT_ID"];
dr["MIN"] = dt1.Rows[i]["MIN_VALUE"];
dr["MAX"] = dt1.Rows[i]["MAX_VALUE"];
dr["POINT_TO_ADD"] = dt1.Rows[i]["AMOUNT"];
dt2.Rows.Add(dr);
}