Delete data from existing DataTable and add new data in Windows Application

Mohal
 
on Nov 15, 2021 01:13 AM
303 Views

I have clear the data from Datatable

now I want to reinitiate datable but I am not able to do this.

Var row= dt.AsEnumerable().SingleOrDefault(r=>r.Field(Column)==5)
dt.claer()
dt.Rows.Add(row);
DataGridView1.datasource=dt;

I am deleting data from existing datatable and adding new data but

I am getting empty data in gridview.

could you please provide me the solution.

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Nov 15, 2021 01:13 AM

Hi Mohal,

Refer below sample code.

DataTable dt = new DataTable();
dt.Columns.Add("Id", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Rows.Add(1, "Mudassar Khan");
dt.Rows.Add(2, "Dharmendra");
dt.Rows.Add(3, "Arjun");
DataRow row = dt.AsEnumerable().SingleOrDefault(r => r.Field<int>("Id") == 2);
DataTable dtCopy = dt.Clone();
dtCopy.ImportRow(row);
DataGridView1.datasource = dt;

 

Mohal
 
on Nov 15, 2021 02:33 AM

Actually this solution is not resolving my issue.

Actually i want to clear that datatable 

Dt.clear()

Then adding the new data to that datatable 

dt.Rows.Add(row);

But i am getting that row is empty

dharmendr
 
on Nov 15, 2021 04:47 AM

Refer below code.

DataTable dt = new DataTable();
dt.Columns.Add("Id", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Rows.Add(1, "Mudassar Khan");
dt.Rows.Add(2, "Dharmendra");
dt.Rows.Add(3, "Arjun");
DataRow row = dt.AsEnumerable().SingleOrDefault(r => r.Field<int>("Id") == 2);
DataRow drNew = dt.NewRow();
for (int i = 0; i < row.ItemArray.Length; i++)
{
    drNew[i] = row.ItemArray[i];
}
dt.Rows.Clear();
dt.Rows.Add(drNew);
DataGridView1.datasource = dt;