Can you declare a DataTable as an array? - c#

DataTable[] dt = new DataTable[2];
for(i = 0; i <= 1; i++)
{
dt[i].Columns.Add("id");
dt[i].Columns.Add("name");
}
When I run this I get:
Object reference not set to an instance of an object.
Can DataTable arrays be declared and used like this?

Yes you can do this, you get that error because dt[i] is not a DataTable instance:
You could do:
dt[i] = new DataTable();
Full code:
DataTable[] dt = new DataTable[2];
for(i = 0; i <= 1; i++)
{
dt[i] = new DataTable()
dt[i].Columns.Add("id");
dt[i].Columns.Add("name");
}

DataTable[] dt = new DataTable[2];
for(i = 0; i <= 1; i++)
{
dt[i].Columns.Add("id");
dt[i].Columns.Add("name");
}
I think in the code you are declaring an array with 2 positions (empty), but not actually filling them.
You need:
DataTable[] dt = new DataTable[2];
for(i = 0; i <= 1; i++)
{
dt[i] = new DataTable();
dt[i].Columns.Add("id");
dt[i].Columns.Add("name");
}
And to answer your question, yes you should be able to have an array of DataTable.

You have to initialize your DataTable[] array elements first:
dt[0] = new DataTable();
dt[1] = new DataTable();
or within the loop
for(i = 0; i <= 1; i++)
{
dt[i] = new DataTable();
dt[i].Columns.Add("id");
dt[i].Columns.Add("name");
}

Related

How to fill DataGridView from left to right, instead of top to bottom

How do I display a datasource in DataGridView from left to right in a row, instead of top to bottom in a column?
Thanks!
Assuming you want to display the columns in a DataGridView horizontally, instead of vertically, the only option you have is to pivot (flip) the dataset and then bind it to the grid. You can use the following code:
public DataSet FlipDataSet(DataSet my_DataSet)
{
DataSet ds = new DataSet();
foreach (DataTable dt in my_DataSet.Tables)
{
DataTable table = new DataTable();
for (int i = 0; i <= dt.Rows.Count; i++)
{ table.Columns.Add(Convert.ToString(i)); }
DataRow r;
for (int k = 0; k < dt.Columns.Count; k++)
{
r = table.NewRow();
r[0] = dt.Columns[k].ToString();
for (int j = 1; j <= dt.Rows.Count; j++)
{ r[j] = dt.Rows[j - 1][k]; }
table.Rows.Add(r);
}
ds.Tables.Add(table);
}
return ds;
}
The approach is well explained here

How to reverse rows in a DataGridView

I am using a data grid, but the values do not display as I would like them to. My current code is below, how would I go about inverting the rows?
string[] strOutput = strLine.Split('_', ',','=');
int totalRows = Convert.ToInt16(strOutput[4]);
int totalCols = Convert.ToInt16(strOutput[5]);
int itemIndex = 8;
for (int i = 0; i < totalCols; i++){
dataGridView1.Columns.Add("Col", "Col");
}
dataGridView1.Rows.Add(totalRows);
for (int i = 0; i < totalRows; i++) {
for (int j = 0; j < totalCols; j++) {
dataGridView1.Rows[i].Cells[j].Value = strOutput[itemIndex];
itemIndex += 2;
}
}
dataGridView1.Visible = true;
To invert i.e. reverse DataGridViewRows you can use this:
void ReverseDGVRows(DataGridView dgv)
{
List<DataGridViewRow> rows = new List<DataGridViewRow>();
rows.AddRange(dgv.Rows.Cast<DataGridViewRow>());
rows.Reverse();
dgv.Rows.Clear();
dgv.Rows.AddRange(rows.ToArray());
}
If you only need to do it once you could instead either:
loop over the lines of the source file in reverse
or instead of Adding the rows (to the end) Insert at the top:
dtnew.Rows.Insert(0, currentDataRowView.Row);
Inverting rows:
"DataGridView.Rows".- will give you "DataGridViewRowCollection"
Iterate the collection in reverse order and create a new datatable. (for loop from max size to zero)
Assign the new datatable to datagridview source.
This rough code written in note pad for your idea. I do not have IDE now.
DataGridViewRowCollection dgRowColllection = dataGridView1.Rows;
DataTable dtnew = new DataTable();
for(i = dataGridView1.RowCount; i < 1 ; i--)
{
DataRowView currentDataRowView = dgRowColllection[i].Row;
dtnew.Rows.Add(currentDataRowView.Row);
}
dataGridView1.source = dtnew;
Can't comment on Pavan's answer because I don't have 50 reputation, but are you getting the error because the loop should be something like:
int totalRows = Convert.ToInt16(strOutput[4]);
int totalCols = Convert.ToInt16(strOutput[5]);
int itemIndex = 8;
for (int i = 0; i < totalCols; i++)
{
dataGridView1.Columns.Add("Col", "Col");
}
dataGridView1.Rows.Add(totalRows);
for (int i = 0; i < totalRows; i++)
{
for (int j = 0; j < totalCols; j++)
{
dataGridView1.Rows[i].Cells[j].Value = strOutput[itemIndex];
itemIndex += 2;
}
DataGridViewRowCollection dgRowColllection = dataGridView1.Rows;
DataTable dtnew = new DataTable();
for (i = dataGridView1.Items.Count; i < 1; i--)
{
DataRowView currentDataRowView = dgRowColllection[i].Row;
dtnew.Rows.Add(currentDataRowView.Row);
}
dataGridView1.DataSource = dtnew;
}
dataGridView1.Visible = true;
}

How to add a column wise row value in data table from for loop

How to add a row in the data table
Code
DataTable dt = new DataTable();
dt.Clear();
DataColumn dc = new DataColumn("day1", typeof(String));
dt.Columns.Add(dc);
dc = new DataColumn("day2", typeof(String));
dt.Columns.Add(dc);
dc = new DataColumn("day3", typeof(String));
dt.Columns.Add(dc);
tString[0] = "Sat,mon,tue";
tString[1] = "Fri,,wed";
tString[2] = "Thu,";
int lengthA = tString.Length;
for (int i = 0; i <= lengthA - 1; i++)
{
string s = tString[i];
string[] words = s.Split(',');
foreach (string word in words)
{
dt.Rows.Add(word);
}
}
The issue in dt.Rows.Add(word) because it is inserting a row
Expected Output
Datatable value should be
day1, day2, day3
sun,mon,tue
Fri,Wed
Thu
Hot to achieve this, can any one help me
Just create a NewRow() and then add the values to its Item indexer for each column.
for (int i = 0; i <= lengthA - 1; i++)
{
string s = tString[i];
string[] words = s.Split(',');
// here is the new row
var row = dt.NewRow();
for(int w = 0; w < words.Length; w++)
{
// set each column
row[w] = words[w];
}
// don't forget to add the Row to the Rows collection
dt.Rows.Add(row);
}

How to edit Row Value of Column in datatable [duplicate]

This question already has answers here:
How to Edit a row in the datatable
(7 answers)
Closed 8 years ago.
i have got the values of my datatable using the following method
DataTable table = new DataTable();
table = GetTable();
string expression;
expression = "B.Id = " + textBox1.Text;
DataRow[] foundRows;
foundRows = table.Select(expression);
for (int i = 0; i < foundRows.Length; i++)
{
sno.Text = foundRows[i][1].ToString();
name.Text = foundRows[i][2].ToString();
dcn.Text = foundRows[i][3].ToString();
stat.Text = foundRows[i][4].ToString();
}
so how do i change the value of foundRows[i][4]
You are already using the DataRow's indexer to get the first column, so i don't understand the problem. If you want to access the second field use foundRows[i][1]:
MessageBox.Show(foundRows[i][1].ToString());
If you want to loop all fields:
for(int i = 0; i < foundRows.Length; i ++)
{
for(int c = 0; c < table.Columns.Count; c++)
MessageBox.Show(foundRows[i][c].ToString());
}
I suggest to use the strongly typed Field-extension method which also supports nullable types.
MessageBox.Show(foundRows[i].Field<string>(0));
use this
DataTable table = new DataTable();
table = GetTable();
string expression;
expression = "B.Id = " + textBox1.Text;
DataRow[] foundRows;
foundRows = table.Select(expression);
for (int i = 0; i < foundRows.Length; i++)
{
sno.Text = foundRows[i][1].ToString();
name.Text = foundRows[i][2].ToString();
dcn.Text = foundRows[i][3].ToString();
stat.Text = foundRows[i][4].ToString();
}
DataTable table = new DataTable();
table = GetTable();
string expression;
expression = "B.Id = "+textBox1.Text;
DataRow[] foundRows;
foundRows = table.Select(expression);
for(int i = 0; i < foundRows.Length; i ++)
{
if(button1.Text == "Make Preasent!")
{
foundRows[i][4] = true;
table.AcceptChanges();
}
else
{
foundRows[i].SetField(4, false);
table.AcceptChanges();
}
}

How to create (n) objects in c# based on loop

Say I want to create (n) DataTables named DT(n)... how can I go about that in a loop.
Pseudo code below
int n=99;
for (int i = 0; i < n; i++)
{
DataTable DT + n = new DataTable(); // <--- this
}
Is this possible?
Store them in a data structure.
Enumerable.Range(0,n).Select(x => new DataTable()).ToArray()
No, you can't have dynamic variable names in C#.
You can however, put them into an array (this is a much better approach anyways):
int n=99;
DataTable[] DT = new DataTable[99];
for (int i = 0; i < n; i++)
{
DT[i] = new DataTable();
}
You can't create dynamically named variables in C#.
For your purpose you are better off using Arrays or Dictionaries ( http://msdn.microsoft.com/en-us/library/xfhwa508%28v=vs.110%29.aspx )
try
List<DataTable> DTs = new List<DataTable>();
int n =99;
for(int(i=0;i<n;i++)
{
DataTable DT = new DataTable();
DTs.Add(DT);
}
Can you try this one
public List<T> CreateObjects<T>(int numbers) where T: new()
{
List<T> _return = new List<T>();
for (int i = 0; i <= numbers; i++)
{
_return.Add(new T());
}
return _return;
}
to use
var myList = CreateObjects<DataTable>(100);
var myList = CreateObjects<AnyClass>(100);
use any object type

Categories