First I have last update file from DB
DataTable excelData = ReadSCOOmega(lastUploadFile);
, after this iterate over this data
foreach (DataRow currentRow in rows)
{
currentRow.
}
Is that possible to change da data in the foreach loop.I can access only the value of this data
currentRow.Field<object>("Some column name")
but not to change it.My idea is selected.I have a multiple deals in excel file and when is upload to DB, I need to make changes in this file.Is that possible or I need to store the data in other collection?
You can do that like :
foreach (DataRow currentRow in excelData.Rows)
{
currentRow.BeginEdit();
currentRow["ColumnName"] = value;
//.....
currentRow.EndEdit();
}
You can use indexer to set the data stored to the field: currentRow["columnName"] = value.
See MSDN DataRow.Item Property
Related
I have a dataset with table in, and basically I call
DataTable aTable = dataSet.Tables["DocData"].GetChanges();
foreach (DataRow aRow in aTable.Rows)
{
switch (aRow.RowState)
{
case DataRowState.Unchanged:
break;
case DataRowState.Added:
aRow["ID"] = getNewID();
//...updates database here
aRow.AcceptChanges();
break;
}
}
Now the change to the ID on the changed row is not updated in the underlying table object the changed row came from... how can I make this happen? I need to add the id when a new row is saved.
Calling GetChanges loops over your rows to retrieve every changed row and builds a copy of that rows. Thus your update changes the copy not the original rows.
It seems that you couldn't avoid to have a loop somewhere to retrieve the added rows so, you could try with this simpler code, thanks to Linq.
foreach (DataRow aRow in aTable.AsEnumerable()
.Where(x => x.RowState == DataRowState.Added)
{
aRow["ID"] = getNewID();
}
I have a DataTable that I'm exporting to pdf and there are numeric value like status id that I want to change to strings for example:
dataRow["statusId"] = 1; //dataRow["statusId"] type is int
and I want it to be:
dataRow["statusId"] = "Open file";
How can I do it without coping the entire data table ?
You actually can't do it. The best way is to actually clone the dataTable and then copy each row:
DataTable dtCloned = dt.Clone();
dtCloned.Columns[0].DataType = typeof(Int32); //in the column you actually need.
foreach (DataRow row in dt.Rows)
{
dtCloned.ImportRow(row);
}
Source: How To Change DataType of a DataColumn in a DataTable?
I am iterating a DataTable in my C# code. I try to get the contents using of a column named "columnName" of row named "row" using -
object value = row["ColumnName"];
I get this error -
Error: System.Reflection.TargetInvocationException: Exception has been
thrown by the target of an invocation.
---> System.ArgumentException: Column 'FULL_COUNT' does not belong to table . at System.Data.DataRow.GetDataColumn(String columnName)
How is this possible ? My SQL query/result set has a column by that name and the query even runs in management studio.
How do I fix this error ?
I am guessing your code is iteration supposed to be something like this
DataTable table = new DataTable();
foreach (DataRow row in table.Rows) {
foreach (DataColumn col in table.Columns) {
object value = row[col.ColumnName];
}
}
If this is the case, row["ColumnName"] in each iteration looks for the same column with name ColumnName which obviously does not exists in your table.
The correct way is row[ColumnName] or row[col.ColumnName] in iteration above
I had a similar issue on my c# code, using a dataset which I had successfully initialized and populated with data from the DB.
So my return set was:
data = new Byte[0];
data = (Byte[])(dataset.Tables[0].Rows[0]["systemLogo_img"]);
Of course the error was in t finding the column 'systemLogo_img'.
I noted that you simply do NOT have to call /qualify the column name. So the correction is:
data = new Byte[0];
data = (Byte[])(dataset.Tables[0].Rows[0].ItemArray[0]);
Simply put: use "ItemArray" at position.
Thanks
Do not write Gridview column names instead of Database column names.
dataGridViewEmployeeClass.Rows[n].Cells[0].Value = item["write the Database Column names"].ToString();
Try this, make sure your column name is same
DataTable dt = new DataTable();
dt.Columns.Add("abc", typeof(string));
DataRow dr = dt.NewRow();
dr["abc"]="";
I had a similar issue which was very basic to fix.
I was querying with a specific column name rather than Select * (i.e. Select Title). Beginner's error but happens to everyone.
If you want to check if the column exists in the DataRow before accessing the value the following block can help...
if (dataRow.Table.Columns.Contains("theColumnName"))
{
// do work
string text = string.Empty;
if (dataRow["theColumnName"] != System.DBNull.Value)
{
text = Convert.ToString(dataRow["theColumnName"]);
}
}
If it doesn't exist and it needs to be added to the data table you can add the column using #Karthick Ganesan's example
// add a column
dataTable.Columns.Add("theColumnName", typeof(string));
I had same issue was trying to pass two different keys for same product.
item.Product = SqlHelper.GetSafeString(dr, "ProductName");
item.Product = SqlHelper.GetSafeString(dr, "Product");
I ran into a problem trying to remove a row from a datatable in C#. The problem is that the datatable is built from SQL, so it can have any number of columns and may or may not have a primary key. So, I can't remove a row based on a value in a certain column or on a primary key.
Here's the basic outline of what I'm doing:
//Set up a new datatable that is an exact copy of the datatable from the SQL table.
newData = data.Copy();
//...(do other things)
foreach (DataRow dr in data.Rows)
{
//...(do other things)
// Check if the row is already in a data copy log. If so, we don't want it in the new datatable.
if (_DataCopyLogMaintenance.ContainedInDataCopyLog(dr))
{
newData.Rows.Remove(dr);
}
}
But, that gives me an error message, "The given DataRow is not in the current DataRowCollection". Which doesn't make any sense, given that newData is a direct copy of data. Does anyone else have any suggestions? The MSDN site wasn't much help.
Thanks!
Your foreach needs to be on the copy, not the original set. You cannot remove an object contained in collection1 from collection2.
foreach (DataRow dr in newData.Rows)
Otherwise you could use a counter to remove at an index. Something like this:
for(int i = 0; i < data.Rows.Count; i++)
{
if (_DataCopyLogMaintenance.ContainedInDataCopyLog(data.Rows[i]))
{
newData.Rows.RemoveAt(i);
}
}
How do I add a new DataColumn to a DataTable object that already contains data?
PseudoCode
//call SQL helper class to get initial data
DataTable dt = sql.ExecuteDataTable("sp_MyProc");
dt.Columns.Add("NewColumn", type(System.Int32));
foreach(DataRow row in dr.Rows)
{
//need to set value to NewColumn column
}
Just keep going with your code - you're on the right track:
//call SQL helper class to get initial data
DataTable dt = sql.ExecuteDataTable("sp_MyProc");
dt.Columns.Add("NewColumn", typeof(System.Int32));
foreach(DataRow row in dt.Rows)
{
//need to set value to NewColumn column
row["NewColumn"] = 0; // or set it to some other value
}
// possibly save your Dataset here, after setting all the new values
Should it not be foreach instead of for!?
//call SQL helper class to get initial data
DataTable dt = sql.ExecuteDataTable("sp_MyProc");
dt.Columns.Add("MyRow", **typeof**(System.Int32));
foreach(DataRow dr in dt.Rows)
{
//need to set value to MyRow column
dr["MyRow"] = 0; // or set it to some other value
}
Only you want to set default value parameter. This calling third overloading method.
dt.Columns.Add("MyRow", type(System.Int32),0);
Here is an alternate solution to reduce For/ForEach looping, this would reduce looping time and updates quickly :)
dt.Columns.Add("MyRow", typeof(System.Int32));
dt.Columns["MyRow"].Expression = "'0'";
Try this
> dt.columns.Add("ColumnName", typeof(Give the type you want));
> dt.Rows[give the row no like or or any no]["Column name in which you want to add data"] = Value;