I have a data table that contains the data like below.
I want to display it in my Grid View like Following. It is actually the transpose of above table and one additional Row added for Viewing Product Details that will be a link button.
Can you please help me how can I achieve the following requirement in ASP.net using C#.
Many Thanks,
Awais Afzal.
Assuming that you table is a DataTable, you could use such an extension to reorder it:
public static DataTable Pivot(this DataTable tbl)
{
var tblPivot = new DataTable();
tblPivot.Columns.Add(tbl.Columns[0].ColumnName);
for (int i = 1; i < tbl.Rows.Count; i++)
{
tblPivot.Columns.Add(Convert.ToString(i));
}
for (int col = 0; col < tbl.Columns.Count; col++)
{
var r = tblPivot.NewRow();
r[0] = tbl.Columns[col].ToString();
for (int j = 1; j < tbl.Rows.Count; j++)
r[j] = tbl.Rows[j][col];
tblPivot.Rows.Add(r);
}
return tblPivot;
}
and set it as new DataSource:
dataGridView1.DataSource = oldDataTable.Pivot();
Related
I have a datatable having columns like below
I want to break datatable into multiple datatables by splitting columns with every group of 4 columns like below
I can do it by simply by using loops and some calculations but wanted to get a better way if someone have.
DataTable has a copy method, you could use that, and remove the columns you don't need.
https://msdn.microsoft.com/en-us/library/system.data.datatable.copy(v=vs.110).aspx
System.Data.DataTable tbl = new System.Data.DataTable();
// Add Dummy Columns
for (int i = 0; i <= 11; i++)
{
tbl.Columns.Add(i.ToString());
}
// Assume We Have Data
// Split Table Into Lists of Tables
List <System.Data.DataTable> tables = new List<System.Data.DataTable>();
for ( int i = 0; i <= 2; i++)
{
int firstColumn = i * 4;
int lastColumn = i * 4 + 3;
System.Data.DataTable tblCopy = tbl.Copy();
for ( int j = 0; j < tbl.Columns.Count; j++)
{
if (j < firstColumn || j > lastColumn)
tblCopy.Columns.Remove(tbl.Columns[j].ColumnName);
}
tables.Add(tblCopy);
}
How can I query an Excel file where the rows and columns are reversed / rotated 90 degrees?
Can it be done with a SELECT query, or do I need to recurse the cells programmatically?
It's for a .NET app, so linq or other suggestions are welcome.
Transpose a Datatable with a code like this:
private DataTable GenerateTransposedTable(DataTable inputTable)
{
DataTable outputTable = new DataTable(inputTable.TableName);
outputTable.Columns.Add(inputTable.Columns[0].ColumnName);
foreach (DataRow inRow in inputTable.Rows)
{
string newColName = inRow[0].ToString();
outputTable.Columns.Add(newColName);
}
for (int rCount = 1; rCount <= inputTable.Columns.Count - 1; rCount++)
{
DataRow newRow = outputTable.NewRow();
newRow[0] = inputTable.Columns[rCount].ColumnName;
for (int cCount = 0; cCount <= inputTable.Rows.Count - 1; cCount++)
{
string colValue = inputTable.Rows[cCount][rCount].ToString();
newRow[cCount + 1] = colValue;
}
outputTable.Rows.Add(newRow);
}
return outputTable;
}
.NET does not include a method to transpose data tables. You have to make your own. This website Link has a tutorial on an example transpose method. I will copy and paste the code snippet below:
private DataTable Transpose(DataTable dt)
{
DataTable dtNew = new DataTable();
//adding columns
for(int i=0; i<=dt.Rows.Count; i++)
{
dtNew.Columns.Add(i.ToString());
}
//Changing Column Captions:
dtNew.Columns[0].ColumnName = " ";
for(int i=0; i<dt.Rows.Count; i++)
{
//For dateTime columns use like below
dtNew.Columns[i+1].ColumnName =Convert.ToDateTime(dt.Rows[i].ItemArray[0].ToString()).ToString("MM/dd/yyyy");
//Else just assign the ItermArry[0] to the columnName prooperty
}
//Adding Row Data
for(int k=1; k<dt.Columns.Count; k++)
{
DataRow r = dtNew.NewRow();
r[0] = dt.Columns[k].ToString();
for(int j=1; j<=dt.Rows.Count; j++)
r[j] = dt.Rows[j-1][k];
dtNew.Rows.Add(r);
}
return dtNew;
}
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 wanna show all my DataSource rows on a DataGridView, but not as rows but as columns of a row. Each 12 items retrieved, I wanna insert a new row on the DataGridView and populate this new row with more items from the DataSource (12 at each row).
My DataSource retrieves just one item each, and using it directly with the DataGridView is working nicely, but shown a different row for each item.
Any hints?
Thanks to #SriramSakthivel.
private void AddToList(DataTable dt)
{
possibleWords = 0;
// Cleans the data grid view
WordList.DataSource = null;
WordList.Refresh();
// Let's transform the original data table onto another, changing rows by columns
DataTable table = new DataTable();
for (int i = 0; i < 10; i++)
{
table.Columns.Add(Convert.ToString(i));
}
DataRow r;
int col = 0;
//for (int k = 0; k < dt.Columns.Count; k++)
{
r = table.NewRow();
for (int j = 0; j < dt.Rows.Count; j++)
{
if (col >= 10)
{
table.Rows.Add(r);
col = 0;
r = table.NewRow();
}
r[col++] = (dt.Rows[j][0]).ToString().ToUpper();
possibleWords++;
}
table.Rows.Add(r);
}
// Puts the new data table as datasource of the word list
DataView dv = table.DefaultView;
WordList.DataSource = dv;
if (possibleWords == 0)
return;
WordList.Columns[0].DefaultCellStyle.BackColor = Color.WhiteSmoke;
WordList.ColumnHeadersVisible = false;
WordList.RowHeadersVisible = false;
}
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");
}
}