0
votes

I have a DataTable and want to add several values to the same cell.

Right now I add data through this: myDataTable.Rows[RowNumber]["ColumnName"] = "Value"

How can I add several values to the same cell in a similar manner (I want to be able to specify row number and column name)?

Edit: What I want (made in excel)

enter image description here

2
When you say several values to the same cell Do you want to add comma separated values? - progrAmmar
I added a picture to clarify! I want the values to be below each other. - Emelie
These values seem to be seperated by \n. A datatable can only hold one value per cell, you can append the values like myDataTable.Rows[RowNumber]["ColumnName"] = "Value1 " + "\nValue2" + "\nValue3". You can't use it to hold more than one value in a DataTable. - progrAmmar
What If I do not know how many values I have or what they are? I have a matrix where the first column is the column number (m), second column is the row number (n) and third and four columns are the values to be added to the cell with the index n,m. There might be multiple value-pairs with the same index. - Emelie
In that case I suggest you create Either a Dictionary or a List of your own defined object where you can save these values much more efficiently and do data operations on them - progrAmmar

2 Answers

1
votes

You can set the value of the cell to any string value which means that you can just create the string as usual and then set the cell value.

If you have a matrix of values you need to iterate through it to be able to populate the DataTable dynamically. Here is an example for you:

DataTable myDataTable = new DataTable();
myDataTable.Columns.Add(new DataColumn("Col1"));
myDataTable.Columns.Add(new DataColumn("Col2"));
myDataTable.Rows.Add();

object[,] matrix = new object[2, 4] {
                            { 0, 0, "line1", "line2" },
                            { 0, 1, "line3", "line4" }, };

for(int i = 0; i<matrix.GetLength(0); ++i)
{
    int row = Convert.ToInt32(matrix[i, 0]);
    int column = Convert.ToInt32(matrix[i, 1]);
    myDataTable.Rows[row][column] = matrix[i, 2].ToString() + Environment.NewLine + matrix[i, 3].ToString();
}

dataGrid.ItemsSource = myDataTable.DefaultView;
0
votes

You can use the special symbol for a new line and then append the strings. It may look something like this:

 myDataTable.Rows[RowNumber]["ColumnName"] = "Value" + "\nValue2" + "\nValue3"

and so on. Additionally, you can use the environment also like this:

 myDataTable.Rows[RowNumber]["ColumnName"] = "Value" + Environment.NewLine + "Value2"