In the DataTable i have n number rows want add those rows in array?
DataTable tbl = new DataTable();
tbl.Rows
Rows is array of your records...
The code below stores all the information in a datatable in a double array of strings. The code should be plug-and-play, just make sure you swap out "dataTable1" with the name of your actual DataTable.
string[,] stringArray = new string[dataTable1.Rows.Count, dataTable1.Columns.Count];
for (int row = 0; row < dataTable1.Rows.Count; ++row)
{
for (int col = 0; col < dataTable1.Columns.Count; col++)
{
stringArray[row, col] = dataTable1.Rows[row][col].ToString();
}
}
To access the first item out of stringArray, simply use call the code below, using the indices as you would for a normal array.
stringArray[0, 0]
Related
I have a data table named dt which is a SQL table converted.
All the data was sent from the server so I had to encrypt it. Now I need to decrypt every cell.
I wanted to do it like this:
foreach (DataRow row in dt.Rows)
{
for (int i = 0; i < dt.Columns.Count; i++)
{
row[i] = r.Decrypt(row[i].ToString());
}
}
Decrypt works fine but row[i] = r.Decrypt(row[i].ToString()); give me the number of the column instead of its content, how do I get the content?
to make the post make more sense.
i want row[i] = r.Decrypt(a string representing the value of row[i]);
This is the correct way to interact with a datatable
foreach(DataRow row in dt .Rows)
{
foreach(DataColumn column in dt .Columns)
{
Console.WriteLine(row[column]);
}
}
In your case you are literally passing an int to your row, because You are using count property.
** Edit
This is in case Your datarow contains an object.
DataTable dt = new DataTable();
dt.Columns.Add("Column 1");
dt.Columns.Add("Column 2");
DataRow dataRow = dt.NewRow();
dataRow.ItemArray = new object[]{"line 1 column 1", "line 1 column 2"
};
dt.Rows.Add(dataRow);
foreach (DataRow row in dt.Rows)
{
foreach (DataColumn column in dt.Columns)
{
var text = row[column.ToString()];
Console.WriteLine(text);
}
}
Result
If none of this work, We would have to see how Your data row is created.
As you mentioned that the other logic (Decrypt) is working fine and you just need to fetch the column content/values then you can try something like:
foreach(DataRow row in table.Rows)
{
foreach(DataColumn column in table.Columns)
{
// you can insert your logic to use column value row[column] here
Console.WriteLine(row[column]);
}
}
for (int i = 0; i < dt.Rows.Count ; i++)
{
for (int j = 1; j < dt.Columns.Count ; j++)
{
string cellValue = dt.Rows[i][j].ToString();
dt.Rows[i][j] = r.Decrypt(cellValue);
}
}
I used a simple dataTable to load my data before is this way:
DataTable dt = new DataTable("grid");
//split array to width X height dataTable
// create columns
for (int i = 0; i < width; i++)
{
dt.Columns.Add();
}
for (int i = 0; i < height; i++)
{
// create a DataRow using .NewRow()
DataRow row = dt.NewRow();
// iterate over all columns to fill the row
for (int j = 0; j < width; j++)
{
row[j] = grid.Cells[j + (width * i)].State.ToString();
}
// add the current row to the DataTable
dt.Rows.Add(row);
}
dataGridView1.DataSource = dt;
And that worked, but not good enough because i want to update 100x100 matrix of colors fast so i thought about an observable collection.
I have now this code:
ObservableCollection<String> data = new ObservableCollection<String>();
dataGridView1.DataSource = new BindingSource { DataSource = data };
for (int i = 0; i < grid.Cells.Length; i++)
{
data[i] = grid.Cells[i].State.ToString();
}
(grid is my model)
this seems to load all the data but i have no representation to the columns so i have only rows.
How do i specify the amount of columns?
And am i in the right direction?
I used my first lines of code, just added:
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;
And now it works just fine.
I'm new to C# and I can't find an example of this anywhere (although I have seen similar examples but the casting was ToString, whereas in my case I want arrays of integers). I have a DataTable object,
DataTable results = dbCon.ExecuteQuery("my query");
int m = results.Rows.Count;
int n = results.Columns.Count;
I want a jagged array consisting of n one-dimensional arrays (each array being a column of the DataTable (results, in this case).
int[][] jagged = new int[n][];
for (int i = 0; i < n; i++)
{
jagged[i] = new int[m];
//var coli = results.Columns.Cast<Array>().Select(column => Convert.ToInt32(column)).ToArray();
//jagged[i] = coli;
}
I've tried a few things (for example what I commented out) but I'm quite stuck now.
If anyone knows how to do this, please post something! Thanks!
Also, to be more specific, I'd really like to use a function like the one NumPy provides to Python... dataSet = np.array(dataList).astype('float'). Double for loops are not in my best interest as my DataTable is large.
I think you also need to make the array of type object. The DataTable DataRow holds things of type object, therefore that is what you need to store them as in your jagged array.
I think this will work:
DataTable table = dbCon.ExecuteQuery("my query");
int rowCount = table.Rows.Count;
int colCount = table.Columns.Count;
object[][] objs = new object[colCount][];
for (int currentColumn = 0; currentColumn < colCount; currentColumn++)
{
objs[currentColumn] = new object[rowCount];
for (int currentRow = 0; currentRow < rowCount; currentRow++)
{
objs[currentColumn][currentRow] = table.Rows[currentRow][currentColumn];
}
}
I think, you already have this. Try:
results.Rows[rowIndex][columnIndex]
To get it into jagged array, you may go for simple for loop:
for (int i = 0; i < results.Rows.Count; i++)
{
for (int j = 0; j < results.Columns.Count; j++)
{
jagged[i][j] = results.Rows[i][j];
}
}
You can get what you want just using LINQ against the DataTable. For each column in the DataTable, you need to iterate over the rows and select that column. You need to call Cast() to Select() on the columns and AsEnumerable() to be able to Select() on the rows:
int[][] jagged = results.Columns.Cast<DataColumn>()
.Select(
col => results.AsEnumerable()
.Select(row => row.Field<int>(col))
.ToArray()
).ToArray();
I want to insert datarow value in datatable particular row. Am having a datatable with values and then i want to overwrite the particular row value using c#.
my partial code id here:
for (int j = 0; j < DT.Rows.Count; j++)
{
row = DT2.NewRow();
row["Employee ID"] = Convert.ToString(DS.Rows[j]["fldempid"]);
row["Employee Name"] = Convert.ToString(DS.Rows[j]["fldempname"]);
string leavehstry = Convert.ToString(DS.Rows[j]["fldleavehistory"]);
string[] textarray1 = leavehstry.Split('-');
char[] delimiterChars1 = { ':' };
for (int i = 1; i <= textarray1.Length - 1; i++)
{
string[] words = textarray1[i - 1].Split(delimiterChars1);
string value = words[0].ToString();
string value1 = words[1].ToString();
row[value] = value1;
ivalue = i;
}
//DT2.Rows[j].Delete(); //I want to insert (or) overwrite the row value at j th position.
//DT2.Rows.Add(row);
//DT2.Rows[j].AcceptChanges();
}
please help me to insert it..
You can insert a DataRow in a DataTable at a specified index location by using the InsertAt method.
You might do this in place of your three commented out lines:
DT2.InsertAt(row, j);
If EmployerID is an unique value, then compare the DataColumn "EmployerID" value with EmployerID and Assign the datarow values as you want by using for loop.
I have a grid view which contains 10 rows and 3 columns.. Now i want to loop through all rows and all columns of the gridview and want to add them to a datatable..
DataRow row;
int rowscount = gv.Rows.Count;
int columnscount = gv.Columns.Count;
for (int i = 0; i < rowscount; i++)
{
for (int j = 0; j < columnscount; j++)
{
row = empTable.NewRow();
row["a"] = gv.Rows[i][column1].Tostring();
row["b"] = gv.Rows[i][column2].ToString();
MynewDatatable.Rows.Add(row);
}
}
gv - my gridview
Now my question is , Can i get the value of all columns of all rows in gv to my new datatable.. I dont know whether my loop is correct or not... I am using this datatable for a bulkcopy function...
Your code above is creating a new Row for every cell in the GridView.
within each row of the GridView your code is assigning every value in the row to the same column, Emp_Name.
Corrected, I think:
int rowscount = gv.Rows.Count;
int columnscount = gv.Columns.Count;
for (int i = 0; i < rowscount; i++)
{
// Create the row outside the inner loop, only want a new table row for each GridView row
DataRow row = empTable.NewRow();
for (int j = 1; j < columnscount; j++)
{
// Referencing the column in the new row by number, starting from 0.
row[j - 1] = gv.Rows[i][j].Tostring();
}
MynewDatatable.Rows.Add(row);
}
EDIT: You've been editing the source in your question, so my answer may grow out-of-date. :)
Your loop is incorrect, all lists start at 0. But you start at 1 when looping through the columns.
The JMD answer is correct, but depending on your use-case, maybe databinding the DataSource of your grid view to your DataTable would be a better approach.
Try this code:
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
string selectedempid = dataGridView1.SelectedRows[0].Cells["Deptno"].Value.ToString();
{
SqlCommand cmd = new SqlCommand("delete from Test_dept where Deptno=" + selectedempid, con);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
MessageBox.Show("deleted");
}
}