Click here to Skip to main content
15,891,778 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I want to check in the grid and display it into the datatable: if the NPM already exists then the data will not be entered into the datatable

i have data in grid

NPM
123
121
122
124
124
124
128

in need datatable like this

NPM
123
121
122
124
128

but my code always get all data. please help

What I have tried:

C#
DataTable dt = new DataTable();

            dt.Columns.Add("NPM");
            grd2.DataSource = dt;

            string NPM = "";
            string NPM_CEK = "";

            for (int i = 0; i < grd.Rows.Count - 1; i++)
            {
                NPM = grd.Rows[i + 1]["NPM"].ToString();

                DataRow row = dt.NewRow();
                dt.Rows.Add(row);

                for (int j = 0; j < dt.Rows.Count; j++)
                {
                    NPM_CEK = dt.Rows[j]["NPM"].ToString();

                    if (NPM_CEK == NPM)
                    {
                        
                    }
                    else
                    {
                        grd2.Rows[i + 1]["NPM"] = NPM;
                    }
                }
            }

            grd2.AutoSizeCols();
Posted
Updated 26-Feb-19 0:23am

You always set all the data as your datasource:
grd2.DataSource = dt;

And then you alway add all rows to the DataTable:
for (int i = 0; i < grd.Rows.Count - 1; i++)
{
    NPM = grd.Rows[i + 1]["NPM"].ToString();

    DataRow row = dt.NewRow();
    dt.Rows.Add(row);
If you don't want a row, don't Add it!
 
Share this answer
 
You can filter data in grid via using DataTable.Select() method[^], which returns an array of DataRow objects.

C#
//get source datatable
DataTable srcdt = (DataDatable)grid.DataSource;
//create destination datatable -> a datasource for grid2
DataTable dstdt = new DataTable();
dstdt.Columns.Add(new DataColumn("NPM", typeof(int)));
for(int i=0; i<srcdt.Rows.Count;i++)
{
	var processedNPM = srcdt.Rows[i][0]; //replace 0 with correct column number
	var npmcheck = dstdt.Select(string.Format("NPM={0}", processedNPM)).FirstOrDefault();
	if(npmcheck!=null) 
	{
		//row already exists in a destination table! Do NOT add it!
	}
	else
	{
		dstdt.Rows.Add(srcdt.Rows[i].Clone());
	}
}


Another way is to use Linq:
C#
dstdt = srcdt.AsEnumerable()
	.GroupBy(x=>x.Field<int>("NPM")) //grou data by NMP field
	.Select(grp=>dstdt.LoadDataRow(new object[]{grp.Key}, false)) //get distinct data 
	.CopyToDataTable();


Note: change x.Field<int>("NPM") to your data type, for example: x.Field<string>("NPM") - if a NMP field is type of string.

Good luck!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900