Anyname Donotcare
Anyname Donotcare

Reputation: 11393

How to change specific column data in the datatable according to some condition

I have the following case :

I add row by row to Datatable dtItems according to the user data entry through a button .

One of the columns in my data table is Hours , and i wanna to achieve the following conditions :

LIKE this:

user_id | name | hours


323 | jo | 3

323 | jo | 1

323 | jo | 1

324 | jack | 4

324 | jack | 1


DataTable dtItems = GetDataTable();
DataRow dr = dtItems.NewRow();
dr["emp_num"] = txt_EmpNum.Text.Trim();
dr["name"] = txt_EmpName.Text.Trim();
dr["hours"] = 5;
dtItems.Rows.Add(dr);

GV_Employee.DataSource = dtItems;
GV_Employee.DataBind();

Session["ItemDT"] = dtItems;

Upvotes: 0

Views: 3416

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460128

I assume that you don't know how to change the DataRow's Hour fields accordingly before you insert them into database.

The only what you need to know is the new hour of the first DataRow, the others get 1 hour:

var firstHour = 5 + 1 - dtItems.Rows.Count; //where 5 is your MaxCount
for (var i = 0; i < dtItems.Rows.Count; i++) {
    if (i == 0) 
        dtItems.Rows[i]["hours"] = firstHour;
    else
        dtItems.Rows[i]["hours"] = 1;
}

To prevent users from inserting more than 5 rows, you only need to check for dtItems.Rows.Count < 5 before you insert the new.


Edit: If you need it to be calculated for every emp_num in the DataTable as commented:

var q = from r in dtItems.AsEnumerable()
        group r by r["emp_num"];

foreach(var empGrp in q){
    var rows=empGrp.ToList();
    var firstHour = 5 + 1 - rows.Count;
    for (var i = 0; i < rows.Count; i++){
        if (i == 0)
            rows[i]["hours"] = firstHour;
        else
            rows[i]["hours"] = 1;
    }
}

Upvotes: 1

Related Questions