Adding values to a Row ItemArray - c#

I am using some DataRow and with it, some ItemArray.
I know how to get the value into a ItemArray, but I don't know how to set values, when I create a new Row.
So I tried this :
DataRow newRow = vDsMod.Tables[0].NewRow();
newRow.ItemArray[0] = "".ToArray();
newRow.ItemArray[1] = "".ToArray();
newRow.ItemArray[2] = "Employee".ToArray();
newRow.ItemArray[3] = "".ToArray();
vDsMod.Tables[0].Rows.Add(newRow);
Or
DataRow newRow = vDsMod.Tables[0].NewRow();
newRow.ItemArray.SetValue("", 0);
newRow.ItemArray.SetValue("", 1);
newRow.ItemArray.SetValue("Employee", 2);
newRow.ItemArray.SetValue("", 3);
vDsMod.Tables[0].Rows.Add(newRow);
But I only got empty fields in the ItemArray.
The value 0,1,3 can be empty, and as the ItemArray of the other lines has a lenght of 4, I also set 4 values.
How can I do what I want?

ItemArray returns an object[] which includes all fields. By accessing it via index here:
newRow.ItemArray[0] = "".ToArray();
you are accessing a single field and asigning a new value. But you're assigning a char[] because you use String.ToArray(), that is pointless.
Instead i would use the strongly typed SetField method which also support nullable types:
DataRow newRow = vDsMod.Tables[0].Rows.Add();
newRow.SetField(0, "");
newRow.SetField(1, "");
newRow.SetField(2, "Employee");
newRow.SetField(3, "");
With Rows.Add(); the DataRow is already added. It's a matter of taste whether to use DataTable.NewRow() and add it later manually or DataTable.Rows.Add().

You can go as below ..
DataRow relation;
// Declare the array variable.
object [] rowArray = new object[2];
for(int i = 0; i <10; i++)
{
rowArray[0]=null;
rowArray[1]= "item " + i;
relation = dt.NewRow();
relation.ItemArray = rowArray;
dt.Rows.Add(relation);
}
I hope it will help you
Yeah it is on microsoft help. But according to your question you seems you didn't search a litle bit you just pposted the question. You want to know just how to initialize the ItemArray (As much i could understand) and you can find a lot of examples related to this.

Related

To assign datarow with new value in C#

iam looking into datatable and fetching line by line,
iam having 50 length values. i want to assign 10th length value as "text".
but it is not stored in datarow after assigned
foreach (DataRow row in dtSource.Rows)
{
if (row.ItemArray[17].ToString().Length > 32)
{
string ss= "text";
row.ItemArray[17] = ss; // here it is not added in itemarray
}
}
DataRow.ItemArray creates a new array on the fly that contains all fields. So when you modify this array you won't modify the DataRow itself. You should use the DataRow indexer:
row[17] = ss;
You can use ItemArray when you need all objects in an array or when you want to assign the whole row's fields at once by assigning an array to this property.

Insert datagridview column values into an Array c#

In my form I have this DataGridView (grid1), filled from a sqllite database.
I want select the column with the name "cap" and insert the column's values into an array.
How can I do?
I don't find a way to select the column cap by name, so I decided to indicate it with the index, but I don't like this way..
I don't know ho to insert these values into an array. there are a lot of columns/cell method but I don't figured out which one can help me!
I tryed to do this way (from an old answer here in the site) but it gives me error of "out of bounded matrix"
int[] wareCap = new int[grid1.Rows.Count];
...
//How I filled my dgv, if this can help
var context = new ForliCesenaEntities2();
BindingSource bi1 = new BindingSource();
bi1.DataSource = context.warehouses.ToList();
grid1.DataSource = bi1;
grid1.Refresh();
//How I try to insert the values into int[] wareCap
for (int i = 0; i<(grid1.Rows.Count-1); i++)
wareCap[i] = Convert.ToInt16(grid1.Rows[i].Cells[1].Value);
Thanks in advice
First you gridview has to be filled with values, then:
List<int> intValues = new List<int>();
foreach (DataGridViewRow row in grid.Rows)
{
intValues.Add(int.Parse(row.Cells["cap"].Value.ToString()));
}
int[] array = intValues.ToArray();
should do the trick.
Alternatively, you could use LINQ.
int[] intArray = dataGridView1.Rows
.Cast<DataGridViewRow>()
.Select(row => int.Parse(row.Cells["cap"].Value.ToString())).ToArray();
UPDATE:
The above solution might crash if the DataGridView's AllowUserToAddRows property is set to true. Because in that case your last row is the row for entering a new record, the Value is null, so invoking the ToString method on it causes a NullReferenceException.
I see two possibilities:
set your datagridview's AllowUserToAddRows property to false (but the user won't be able to add new rows),
use the following solution
Check if the row is the row for entering a new record:
int[] intArray = dataGridView1.Rows
.Cast<DataGridViewRow>()
.Where(row => !row.IsNewRow)
.Select(row => Convert.ToInt32(row.Cells["cap"].Value.ToString())).ToArray();
You already got all your values in a List, because you do sth. like this:
bi1.DataSource = context.warehouses.ToList();
You can easily store this in a reference:
var values = context.warehouses.ToList();
bi1.DataSource = values;
Your Grid is build based on Objekts in this List. So this should build your array:
int[] array = new int[values.Count];
int counter = 0;
foreach (var object in values)
{
array[counter++] = object.CAP;
}
int[] wareCap = new int[grid1.Rows.Count];
foreach(DataGridViewRow row in grid1.Rows)
{
wareCap.Add(Convert.ToInt32(cell["cap"].Value.ToString()));
}

c# adding row that already belongs to a datatable

I have a datatable DTgraph, that datatable has a column named Campaign. that column could have one of three unique values, which are IVR, City, City2`. So the rows are like this:
I have a datatable has data like this format
........ IVR........
.........IVR........
**.........IVR........**
.........City1......
.........City1......
**.........City1......**
.........City2......
.........City2......
**.........City2......**
I want to take the last row of each unique value for that column, In other words, I want to take the rows that are bold. I did almost everything like this:
var cRows = new Dictionary<string, DataRow>(StringComparer.InvariantCultureIgnoreCase);
foreach (DataRow oRow in DTgraph.Rows)
{
var sKey = oRow["Campaign"].ToString();
if (!cRows.ContainsKey(sKey))
{
cRows.Add(sKey, oRow);
}
else
{
cRows[sKey] = oRow;
}
}
var oNewTable = DTgraph.Clone();
foreach (var oRow in cRows.Values)
{
oNewTable.Rows.Add(oRow);
}
As you see, I put the data in dictionary and transferred the dictionary to a datatable at the end.
My problem is that on this line:
cRows.Add(sKey, oRow);
I get an error:
The row is already belongs to another datatable
Note: I need to solve that exception, I don't need a new way of doing my goal
Note: I was wrong, the exception is on this line
oNewTable.Rows.Add(oRow);
To be honest I don't 100% understand your question, however to fix the exception:
The row is already belongs to another datatable.
Change:
oNewTable.Rows.Add(oRow);
To:
oNewTable.ImportRow(oRow);
Alternatively create a new row and clone the ItemArray.
foreach (var oRow in cRows.Values)
{
var newRow = oNewTable.NewRow();
newRow.ItemArray = oRow.ItemArray.Clone() as object[];
oNewTable.Rows.Add(newRow);
}
Use NewRow() function of the new table and then use oRow.ItemArray property to get values from the source row and copy them the newly created row's ItemArray. An example would be:
Array.Copy(oRow.ItemArray, oNewTable.NewRow().ItemArray, oRow.ItemArray.Length)
However, remember that this would not preserve original values and current state from the source row (which I don't think you're using here anyway). If those things matter, go for ImportRow() solution which preserves source row's state when copying.

How to get a particular row from a DataRow[]?

DataRow[] headerRows = null;
headerRows = mappingTable.Select("FieldID LIKE '0_%'"); //mappingTable is of type DataTable.
I have three columns in the mappingTable "Id","Display", "Value"
Now, I need to get the Value where "Id" = 0_0_0 from the headerRows.
Is there any simple way to do this?
Thanks for any help.
If you have to use DataRow[] then with linq you can do this:
String value = (String)rows.Single(
row => String.Equals(row["Id"], "0_0_0"))["Value"];
You need to set the PrimaryKey on the DataTable and then you can use Find() on the Rows collection to find the row with that key.
dataTable.PrimaryKey = new DataColumn[] { dataTable.Columns["Id"] };
object value = dataTable.Rows.Find("0_0_0")["Value"];
You could use LINQ: but this might be overkill:
dt.AsEnumerable().Where(dr => dr.Field<object>("FieldId").StartsWith("0_"));
If you have to have DataRow[] then
headerRows = dt.AsEnumerable().Where(dr => dr.Field<object>("FieldId").StartsWith("0_")).ToArray();
From there you have only data rows that match your criteria, so you can cycle through for the value.

C#: How do I iterate the contents in a DataColumn?

I have a database column I simply need to check to see if a value is there.
DataTable dt = masterDataSet.Tables["Settings"];
DataColumn SETTINGS = dt.Columns["DEFAULTSETTINGS"];
I just need to iterate over the values in this column to see if a value exists.
Help
You iterate the rows, not the column
DataColumn SETTINGS = dt.Columns["DEFAULTSETTINGS"];
foreach(DataRow row in dt.Select())
{
object columnValue = row[SETTINGS];
// Do something with columnValue
}
There's no need to use Linq or iterate manually through your DataRows as plain old ADO.NET has a couple of solutions such as DataTable.Select and DataView.RowFilter.
string value = "default";
bool found = dt.Select("DEFAULTSETTINGS = " + value).Length > 0;
It's obvious that once you get the filtered rows, you can do whatever you want with them. In my example, I just checked to see if any row was within the criteria but you can manipulate them how you see fit.
You can use linq in .net 3.5:
DataColumn col = dt.Columns["DEFAULTSETTINGS"];
object value = //expected value
bool valueExists = dt.AsEnumerable().Any(row => row.Field<object>(col).Equals(value));
EDIT: It seems from the comments you're trying to see if the 'DEFAULTSETTINGS' column contains the string 'default'. The Field extension method simply casts the object in the datarow at that column into the given type, so you can change the type parameter rather than use ToString(). So for your example you can probably use this:
DataColumn col = dt.Columns["DEFAULTSETTINGS"];
bool valueExists = dt.AsEnumerable().Any(row => "default".Equals(row.Field<string>(col), StringComparison.OrdinalIgnoreCase);

Categories

Resources