How to Change order of columns in gridview? - c#

I want to change order of gridview columns (8th to be first, first to be second, second to be third...). I am filling my gridview (which has 9 columns) with data from text file. Code is here:
public DataTable ConvertToDataTable(string filePath, int numberOfColumns)
{
DataTable tbl = new DataTable();
for (int col = 0; col < numberOfColumns; col++)
tbl.Columns.Add(new DataColumn("Column" + (col + 1).ToString()));
string[] lines = File.ReadAllLines(filePath);
List<string> ekran = new List<string>();
foreach (string line in lines)
{
var cols = line.Split(',');
DataRow dr = tbl.NewRow();
for (int cIndex = 0; cIndex < 9; cIndex++)
{
if (cols[cIndex].Contains('_'))
{
cols[cIndex] = cols[cIndex].Substring(0, cols[cIndex].IndexOf('_'));
dr[cIndex] = cols[cIndex];
}
else
{
cols[cIndex] += '_';
cols[cIndex] = cols[cIndex].Substring(0, cols[cIndex].IndexOf('_'));
dr[cIndex] = cols[cIndex];
}
}
for (int cIndex = 0; cIndex < 9;cIndex++ )
if (dr[cIndex].ToString() == promenljiva)
tbl.Rows.Add(dr);
}
this.GridView1.DataSource = tbl;
this.GridView1.DataBind();
return tbl;
}
After that i have this:
ConvertToDataTable(filePath, 9);
This is gridview:
<asp:GridView ID="GridView1" runat="server"></asp:GridView>
How can i do that?

Before setting the DataSource of the grid
tbl.Columns[8].SetOrdinal(0);
This will change the Ordinal property of the DataColumn inside the DataTable.DataColumnCollection in a way that the grid sees, as first column, your 9th column. Of course all other columns move up to a new index position

For further reading, it's discussed in detail here!
https://www.codeproject.com/Questions/711397/How-to-Change-order-of-columns-in-gridview
How to reorder columns in gridview dynamically
Then some add/remove column pieces with "geekwithblogs" site
http://geekswithblogs.net/dotNETvinz/archive/2009/06/03/move--autogenerate-columns-at-leftmost-part-of-the-gridview.aspx

Related

transpose DataTable code gives one extra row indicating the index of the columns

I've to do the transpose of my DataTable and I used the code I found in internet. This code is giving an extra row at the top showing the column index. How can I remove this row?This extra row is at above the header row of my DataTable, and when I use the code dt_.Rows.Remove(dt_.Rows[0]); the header row is removed but not the top row. Reference taken from:
Transpose a datatable
How can I remove the top row?
DataTable dt_ = new DataTable();
DataTable table = new DataTable();
//Get all the rows and change into columns
for (int i = 0; i <= dt.Rows.Count; i++)
{
table.Columns.Add(Convert.ToString(i));
}
DataRow dr;
//get all the columns and make it as rows
for (int j = 0; j < dt.Columns.Count; j++)
{
dr = table.NewRow();
dr[0] = dt.Columns[j].ToString();
for (int k = 1; k <= dt.Rows.Count; k++)
{
dr[k] = dt.Rows[k - 1][j];
}
table.Rows.Add(dr);
}
dt_ = table;
//dt_.Rows.Remove(dt_.Rows[0]); removes the header row
My gridview code
<asp:GridView ID="GridView1"
runat="server"
CellPadding="3"
CellSpacing="2"
AutoGenerateColumns="true"
ShowFooter="true"
FooterStyle-HorizontalAlign="Left"
RowStyle-BorderColor="Black" HeaderStyle-BackColor="#0CA3D2">
<FooterStyle BackColor="#87CEFA" />
</asp:GridView>
I've not shown the footer section sum calculation code behind because it is irrelevant here.
snapshot:
I think if you start the loop from 1 it should work
DataTable dt = new DataTable();
DataTable dt_ = new DataTable();
DataTable table = new DataTable();
//Get all the rows and change into columns
for (int i = 0; i <= dt.Rows.Count; i++)
{
table.Columns.Add(Convert.ToString(i));
}
DataRow dr;
//get all the columns and make it as rows
//HERE THE LOOK STARTS FROM ONE
for (int j = 1; j < dt.Columns.Count; j++)
{
dr = table.NewRow();
dr[0] = dt.Columns[j].ToString();
for (int k = 1; k <= dt.Rows.Count; k++)
{
dr[k] = dt.Rows[k - 1][j];
}
table.Rows.Add(dr);
}
dt_ = table;
That's because
//Get all the rows and change into columns
for (int i = 0; i <= dt.Rows.Count; i++)
{
table.Columns.Add(Convert.ToString(i));
}
is creating columns named 0, 1, and 2. the problem is with Convert.ToString(i). That, and you will also need to change how you read k.
The code will look like this (not tested):
DataTable dt_ = new DataTable();
DataTable table = new DataTable();
//Get all the rows and change into columns
for (int i = 0; i <= dt.Rows.Count; i++)
{
table.Columns.Add(dt.Rows[i][0]); // the column name is in the first cell
}
DataRow dr;
//get all the columns and make it as rows
for (int j = 0; j < dt.Columns.Count; j++)
{
dr = table.NewRow();
dr[0] = dt.Columns[j].ToString();
// changed the for condition
for (int k = 1; k < dt.Rows.Count; k++)
{
dr[k] = dt.Rows[k][j]; // changed the 'k - 1' to 'k'
}
table.Rows.Add(dr);
}
dt_ = table;

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 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);
}

Counting rows on a datagrid and adding it as a new column

I want to basically go this is row 1, row 2, 3, 4...until the last row and add that as a new column on my datagrid table, I am not trying to find the total amount of rows.
Here is my current code (I think this is terribly wrong but this is a lot of new code):
for (int i = 0; i < table.Rows.Count; i++)
{
string rowNum = table.Rows[i].ToString();
table.Columns.Add("Book num", typeof(string), rowNum);
}
The following code will add 1 new column to your table, and then populate each row in that column with the index number of that row.
If you don't want to start with 0, just change int i = 0; to int i = 1;
table.Columns.Add("Book num", typeof(string));
int i = 0;
foreach (DataRow dr in table.Rows)
{
dr["Book num"] = i;
i++;
}
Try for total rows,
int TotalRows = 0;
for (int i = 0; i < table.Rows.Count; i++)
{
if(i == 0)
{
TotalRows = 1;
}
else
{
TotalRows + = i;
}
string rowNum = table.Rows[i].ToString();
table.Columns.Add("Book num", typeof(string), rowNum);
}

Rows not showing up in DataTable c#

I am trying to copy data from my datagridview to a datatable so i can export to a csv file
here is the code
public DataTable createdatatablefromdgv()
{
DataTable dsptable = new DataTable();
for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
DataColumn dspcolumn = new DataColumn(dataGridView1.Columns[i].HeaderText);
dsptable.Columns.Add(dspcolumn);
}
int noOfColumns = dataGridView1.Columns.Count;
foreach (DataGridViewRow dgvr in dataGridView1.Rows)
{
DataRow dataRow = dsptable.NewRow();
for (int i = 0; i < noOfColumns; i++)
{
dataRow[i] = dgvr.Cells[i].Value.ToString();
}
}
return dsptable;
}
It seems like it copies the data from the the grid to to the table but when I return the datatable all there is the columns no rows
You are not adding dataRow to data table after assigning values to its columns.
public DataTable createdatatablefromdgv()
{
DataTable dsptable = new DataTable();
for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
DataColumn dspcolumn = new DataColumn(dataGridView1.Columns[i].HeaderText);
dsptable.Columns.Add(dspcolumn);
}
int noOfColumns = dataGridView1.Columns.Count;
foreach (DataGridViewRow dgvr in dataGridView1.Rows)
{
DataRow dataRow = dsptable.NewRow();
for (int i = 0; i < noOfColumns; i++)
{
dataRow[i] = dgvr.Cells[i].Value.ToString();
}
dsptable.Rows.Add(dataRow); //Add this statement to add rows to Data Table
}
return dsptable;
}
The above answer is correct but a little explanation as to why you encountered this problem. One would think that by calling NewRow() on the DataTable you would add a new row to the DataTable and then be able to access it.
What NewRow actually does is give you an instance of a DataRow which you can then use column names as apose to column identifiers (integers).
This allows you to do something like this
DataRow dataRow = dsptable.NewRow();
foreach(DataColumn dc in dsptable.Columns)
{
dataRow[dc.ColumnName] = dgvr.Cells[dc.ColumnName].Value.ToString()
}
Alternatively you could just call Rows.Add() which takes an object array or a as you were trying to do a DataRow.
List<string> rowData = new List<string>();
for (int i = 0; i < noOfColumns; i++)
{
rowData.Add(dgvr.Cells[i].Value.ToString());
}
dsptable.Rows.Add(rowData.ToArray());
This should explain adding rows to a datatable more simply :)

Categories