To assign datarow with new value in C# - 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.

Related

How to get the name of the element in an array

I have a data table as part of a step in spec-flow. I want to 'read' the values put into the table and record the value as well as the column/row of the table it was entered in.
I have saved each cell of the table and created a string array with all boxes, and used the following code to check if anything exists in the table:
foreach (int value in tableInfo)
{
if (value > 0)
{
int number = value;
}
}
I have stored the number entered in the table as number, I also want to store the name of the element in the array that contains the number so I can search it against another list and assign the number to that.
I think you're looking for a dictionary. A dictionary is essentially a key value pair. The key would be your cell number or cell name, and the value, the value that was in your cell. Let's say that the key is a string and the value is an int. This is how you will initialize your dictionary:
Dictationary<string, int> myDictionary = new Dictionary<string, int>();
Then as you go through that table, you add entries to the dictionary. You can use the add method, or just assign it.
myDictionary.Add("MyCellName", 20);
or
myDictionary["MyCellName"] = 20;
Later in your code, if you need to retrieve the value for cell 'xyz', you would just use:
var myValue = myDictionary["xyz"];
If u have a DataTable u can use this loop:
foreach (DataRow dtRow in tableInfo.Rows)
{
foreach(DataColumn dc in tableInfo.Columns)
{
var field = dtRow[dc].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.

Adding values to a Row ItemArray

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.

Sort DataTable rows by length in c#

How to do following scenario:
I have some DataTable which contains for example some rows:
1.rowa
2.rowab
3.row
4.rowaba
...
n. rowabba
How to sort rows by lenght, not by name. I wan to to sort Table by length of fields.
You could add an extra column to your DataTable, supplying an expression containing a call to the len() function, causing the column's values to be automatically computed:
table.Columns.Add("LengthOfName", typeof(int), "len(Name)");
Then you can simply sort on your new column before binding the DataTable to a grid to whatever kind of UI control you plan to use:
table.DefaultView.Sort = "LengthOfName";
If you must use DataTable, you could introduce an extra column for the sort. In this case, you could set the value in the column simply to the length of each desired cell, and then sort by the new column:
DataTable table = new DataTable();
DataColumn val = table.Columns.Add("Value", typeof(string));
table.Rows.Add("abc");
table.Rows.Add("defgh");
table.Rows.Add("i");
table.Rows.Add("jklm");
// sort logic: ***** schou-rode's "len(...)" approach is better *****
DataColumn sort = table.Columns.Add("Sort", typeof(int));
foreach (DataRow row in table.Rows) {
row[sort] = ((string)row[val]).Length;
}
DataView view = new DataView(table);
view.Sort = "Sort";
foreach (DataRowView row in view) {
Console.WriteLine(row.Row[val]);
}
Personally, I'd use a typed list - of either a class, or a string in this case (since you only list one value):
List<string> list = new List<string> {
"abc", "defgh", "i", "jklm"};
list.Sort((x, y) => x.Length.CompareTo(y.Length));
foreach (string s in list) {
Console.WriteLine(s);
}

Cdd data to column series in wpf C#

I want to create a ColumnSeries Bar Chart in WPF using C#. I shall extract the data from the database and want to bind it to the bar chart.
The data extracted will contain two values. First is parameter name (string) and the other is its value (double). Which type of collection shall I use? and how to do the binding?
i finally used a simple KeyValuePair array and assigned it to the ItemsSource property of the ColumnSeries of barchart.
Just use the Dictionary as follows:
Dictionary<string,int> data = new Dictionary<string,int> ();
If you have a data in dataset then use foreach loop for item in the dataset
Example:
foreach (DataRow drv in DS.Tables[0].Rows)
{
string strvalue= Convert.ToString(drv["columnname string type"]);
string intvalue= Convert.ToString(drv["column name int type"]);
data.Add(Convert.ToString(strvalue), Convert.ToInt32(intvalue));
}
((ColumnSeries)msChart3.Series[0]).ItemsSource = data;
This way you can bind data to a column series chart type.

Categories

Resources