bablu Parhi bablu Parhi - 1 year ago 90
ASP.NET (C#) Question

How can I delete row[6] from datarow row inside forech loop in the code below?

I have a

DataTable dt
in which I am trying to add two more columns. I succeed on that. But when I try to delete row[6] after getting the data, I am facing problems to delete that. I am looking for a way to remove a particular row.

protected void gvTimeSheet_DataBound(object sender, EventArgs e)
DataTable dt = new DataTable();
int intUserID = TypeConvert.IsNullInt32(ddlUsers.SelectedValue, 0);
DateTime fromDate = Convert.ToDateTime(UCFromDate.selectedDate);
DateTime toDate = Convert.ToDateTime(UCToDate.selectedDate);
string strQuery = "EXEC SPRptUserTimeSheet_AP @User=" + intUserID + ",@dateFrom='" + fromDate + "',@dateTo='" + toDate + "'";
dt = DataHelper.ExecuteQuery(strQuery);
dt.Columns.Add("Booked Hrs");
dt.Columns.Add("Time Zone");

foreach (DataRow row in dt.Rows)
string userName = row[0].ToString();
string bookedHr = row[6].ToString();
string timezone = row[7].ToString();

if (userName == string.Empty)
row[0] = ddlUsers.SelectedItem.Text;

if (bookedHr == string.Empty)
row["Booked Hrs"] = 0.0;
if (bookedHr != string.Empty)
row["Booked Hrs"] = objCommon.fnGetEffortInHrMinFormat(Convert.ToInt32(bookedHr));

if (timezone == "0")
row["Time Zone"] = "Offshore";

if (timezone == "1")
row["Time Zone"] = "Onsite";

ViewState["dtExport"] = dt;

Answer Source

What you are trying to do does not really make sense:

To understand why, you need to consider what the expression row[6] really means. It means

the value of column 6 in this row.

So the only way to realistically remove the column 6 from the row would be to delete it from the table:


That would get rid of the column alright. But then you have removed it for ALL rows.

So you cannot do this from within the foreach loop. If you did you would remove

  • the 6th column the first time,
  • the (orignally) 7th column the second time, and
  • the (originally) 8th column the third time through the loop,
  • etc..

Until you have an exception that you are trying to remove a column outside the bounds of the Column collection.

So, if you must indeed get rid of column 6 do so after the loop.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download