fill gridview cell-by-cell - c#

I want to populate GridView below with images:
<asp:GridView ID="GrdDynamic" runat="server" AutoGenerateColumns="False">
<Columns>
</Columns>
</asp:GridView>
The code below iterates through directory, then I collect image titles and want them to be populated in gridview. code in bold is not working well, gridview is only filled with the last image in list.
List<string> imagelist = new List<string>();
protected void Page_Load(object sender, EventArgs e)
{
foreach (String image in Directory.GetFiles(Server.MapPath("example/")))
{
imagelist.Add("~/example/" + Path.GetFileName(image));
}
loadDynamicGrid(imagelist);
}
private void loadDynamicGrid(List<string> list)
{
DataTable dt = new DataTable();
DataColumn dcol = new DataColumn(NAME, typeof(System.String));
dt.Columns.Add(dcol);
dcol = new DataColumn("NAME1", typeof(System.String));
dt.Columns.Add(dcol);
dcol = new DataColumn("NAME2", typeof(System.String));
dt.Columns.Add(dcol);
dcol = new DataColumn("NAME3", typeof(System.String));
dt.Columns.Add(dcol);
DataRow drow = dt.NewRow();
dt.Rows.Add();
dt.Rows.Add();
**for (int i = 0; i < dt.Rows.Count; i++)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
foreach (string value in list)
{
dt.Rows[i][j] = value;
}
}
}**
foreach (DataColumn col in dt.Columns)
{
ImageField bfield = new ImageField();
bfield.DataImageUrlField = NAME;
bfield.HeaderText = col.ColumnName;
GrdDynamic.Columns.Add(bfield);
}
GrdDynamic.DataSource = dt;
GrdDynamic.DataBind();
}
how to fill gridview cell-by-cell only with available amount of images?
i know it is easy, i tried various methods like: dt.Rows.Add(list); and some other attempts, but they didn't work. i'm very stupid.
i'd be glad for any help.

You're repeatedly setting every cell to every string with your foreach. You need to addess a specific element in list that will correspond to the specific cell. Try something like this:
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
//below line assumes list has more than i*j elements
//how you want to handle anything outside that case
//is not clear
dt.Rows[i][j] = list[(i * dt.Columns.Count) + j] ;
}
}
Edit: Reading your question more carefully, your problem is fundamentally outside of that loop. Even if you applied the above fix, you still wouldn't get what you're hoping for. What you need to do is loop over the list, and add each item in the list a row, and add that row to the table. Something like this:
int currColIndex = 0;
DataRow drow = dt.NewRow();
foreach(string value in list)
{
if(currColIndex >= dt.Columns.Count)
{
dt.Rows.Add(drow);
drow = dt.NewRow();
currColIndex = 0;
}
drow[currColIndex++] = value;
}
if(currColIndex != dt.Columns.Count)
{
dt.Rows.Add(drow);
}

Related

C# Adding dynamic column and rows in Datatable

I tried to add values to DataTable columns by vertically in loops.
But output doesn't looks good as expected.
DataTables dynamictable = new DataTable()
foreach (DataColumn cl in dataTable.Columns)
{
dynamictable.Columns.Add(cl.ToString());
List<string> plainList = dataTable.AsEnumerable().Select(x => x[cl].ToString()).ToList();
for (int i=0; i< plainList.Count(); i++)
{
DataRow row = dynamictable.NewRow();
row[cl.ToString()] = plainList[i];
enryptedTable.Rows.Add(row);
}
}
Actual Output got from my code:
Expected Output:
change your code to :
DataTable dynamictable = new DataTable();
int col = 0;
foreach (DataColumn cl in dataTable.Columns)
{
dynamictable.Columns.Add(cl.ToString());
List<string> plainList = dataTable.AsEnumerable().Select(x => x[cl].ToString()).ToList();
DataRow row = null;
for (int i = 0; i < plainList.Count(); i++)
{
row = dynamictable.NewRow();
row[col] = plainList[i];
dynamictable.Rows.Add(row);
}
col++;
}
//now set dynamictable to datagridview or .....

I want to create the 'times table (2x2 = 4)' table using the GridView in Asp.net

I want to create a 9x9 GridView, list the numbers 1 through 9 in columns and rows, and then put the values ​​into an array.
I want to create it using for and Array, but I do not know what to do.
The current state is that the value is displayed below the column and all the values ​​appear only on one row.
I want to complete one program and help.
aspx.
<asp:GridView ID="GridView1" runat="server">
<Columns></Columns>
aspx.cs.
public partial class GridEX : System.Web.UI.Page{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dt = new DataTable();
int i = 1;
if (!Page.IsPostBack)
{
for (; i <= 9; i++)
{
dt.Columns.Add(i + "단");
}
for (int k = 1; k <= 9; k++)
{
DataRow dr = dt.NewRow();
for (int m = 1; m <= 9; m++)
{ dr[m] = i; }
dt.Rows.Add(dr);
dt.Rows.Add(i * k);
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
What I want image:
DataTable dt = new DataTable();
dt.Columns.Add("Factor1");
dt.Columns.Add("Factor2");
dt.Columns.Add("Result");
for(int i=2; i<=9; i++)
{
for (int j=1; j<=10; j++)
{
dt.Rows.Add(i, j, i*j);
}
}
GridView1.DataSource = dt;
GridView1.DataBind();
You may have your reasons for wanting to use a Gridview here, but in my opinion, it is not the right way to achieve your goal. DataBinding is a useful tool but it does come with processing overhead, at the very least it is another iteration.
You can use a DataTable to achieve the same thing without the binding overhead.
ASPX
<asp:Table ID="MulitiplicationTable" runat="server"></asp:Table>
C#
for(int row = 0; row < 10; row++)
{
TableRow newRow = new TableRow();
MulitiplicationTable.Rows.Add(newRow);
for (int column = 0; column < 10; column++)
{
TableCell newCell = new TableCell();
newRow.Cells.Add(newCell);
//Empty cell for our first cell...
if ((row + column) == 0)
{
newCell.Text = " ";
}
//Our Column and row headers are also
//Special Cases
else if(row == 0)
{
newCell.Text = column.ToString();
newCell.CssClass = "columnHead";
}
else if(column == 0)
{
newCell.Text = row.ToString();
newCell.CssClass = "rowHead";
}
//Now do the math
else
{
newCell.Text = (row * column).ToString();
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable table9x9 = new DataTable();
if (table9x9.Columns.Count == 0)
{
for (int i = 0; i < 10; i++)
{
if (i == 0)
table9x9.Columns.Add(" ");
else
table9x9.Columns.Add(i+"");
}
}
for (int row = 1; row <= 9; row++)
{
DataRow dr = table9x9.NewRow();
for (int column = 0; column <= 9; column++)
{
if (column == 0)
dr[" "] = row;
else
dr[column + ""] = row * column;
}
table9x9.Rows.Add(dr);
}
GridView2.DataSource = table9x9;
GridView2.DataBind();
}
}
Output:

Show datasource rows as columns on a DataGridView (Winforms)

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

Sum DataTable Columns

Trying to do a sum of each column in a DataTable that i have set up. The First 2 columns in the datatable contain text and the rest of the columns contain numeric values that i would like to sum.
I get a error saying there is no row at position 17.
when i scroll down the DataTable viewer you can see there is no row at 17 and cant see why the foreach is hitting this row.
I have the following code
for (int i = 2; i < DT.Columns.Count; i++)
{
foreach (DataRow DR in DT.Rows)
{
ColumnTotal = ColumnTotal + int.Parse(DR[i].ToString());
}
DT.Rows[DT.Rows.Count + 1][i] = ColumnTotal;
ColumnTotal = 0;
}
Can anyone advise me on what i am doing wrong and how i can improve on it.
Thanks
You are trying to assign in 17-th row but it does not exist. So first create it and then populate it like below:
var row = DT.NewRow();
for (int i = 2; i < DT.Columns.Count; i++)
{
ColumnTotal = 0;
foreach (DataRow DR in DT.Rows)
{
ColumnTotal = ColumnTotal + int.Parse(DR[i].ToString());
}
row[i] = ColumnTotal;
}
DT.Rows.Add(row);
You can not set the value in row like this
DT.Rows[DT.Rows.Count + 1][i] = ColumnTotal;
Because it has no 17th row, You may need to add a new row.
Do something like,
DataRow newRow = DT.NewRow();
for (int i = 2; i < DT.Columns.Count; i++)
{
foreach (DataRow DR in DT.Rows)
{
ColumnTotal = ColumnTotal + int.Parse(DR[i].ToString());
}
newRow[i] = ColumnTotal;
ColumnTotal = 0;
}
DT.Rows.Add(newRow);
simple my dear friend
Datatable Dt=new DataTable();
Dt.Columns.Add("Name");
Dt.Columns.Add("Amount");
Dt.Columns.Add("Id");
Dt.Rows.Add("Harsh","100", "1");
Dt.Rows.Add("Miller","200", "2");
now to calculate use this
object Sum = Dt.Compute(" SUM(Amount) ","");
double NetTotal = Double.Parse(Sum.ToString());

Change color in datagridview based on differences in two datatables?

I have two datatables, each with 1 column:
dtTempCM
dtOldTempCM
In both tables, the only column name is Column1
I also have 2 datagridviews in the form that are each bound to a datatable:
dgvCurrentCM.DataSource = dtTempCM;
dgvOldCM.DataSource = dtOldTempCM;
How can I compare each row, and highlight it in one (or both) of the datagridviews if they don't match? So far, I have this:
foreach (DataRow row1 in dtTempCM.Rows)
{
foreach (DataRow row2 in dtOldTempCM.Rows)
{
var array1 = row1.ItemArray;
var array2 = row2.ItemArray;
if (array1.SequenceEqual(array2))
{
//change row/cell color in dgvCurrentCM to red
//change row/cell color in dgvOldCM to red
}
}
}
Any ideas? Thank you!
EDIT: I tried this too, but it changes the color of every cell since it compares every row in dgvOldCM to a single row in dgvCurrentCM:
foreach (DataGridViewRow row1 in dgvCurrentCM.Rows)
{
foreach (DataGridViewRow row2 in dgvOldCM.Rows)
{
if (row1.Cells[0].Value != row2.Cells[0].Value)
{
row1.DefaultCellStyle.ForeColor = Color.Red;
row2.DefaultCellStyle.ForeColor = Color.Red;
}
}
}
I would iterate on one of the gridview, comparing to the other like this:
for (int i = 0; i < dgvCurrentCM.RowCount; i++)
{
if (dgvCurrentCM.Rows[i].Cells[0].Value != null)
{
if ((int)dgvCurrentCM.Rows[i].Cells[0].Value != (int)dgvOldCM.Rows[i].Cells[0].Value)
{
dgvCurrentCM.Rows[i].DefaultCellStyle.ForeColor = Color.Red;
dgvOldCM.Rows[i].DefaultCellStyle.ForeColor = Color.Red;
}
}
}
You can generate a Intersection of two Datatables, and then mark the rows:
DataTable dt1 = new DataTable();
DataTable dt2 = new DataTable();
dt1.Columns.Add("Col");
dt2.Columns.Add("Col");
for (int i = 0; i < 10; i++)
{
DataRow dr = dt1.NewRow();
dr["Col"] = i.ToString();
dt1.Rows.Add(dr);
}
for (int i = 5; i < 15; i++)
{
DataRow dr = dt2.NewRow();
dr["Col"] = i.ToString();
dt2.Rows.Add(dr);
}
var result = dt1.AsEnumerable().Intersect(dt2.AsEnumerable(), DataRowComparer.Default);
dataGridView1.DataSource = dt1;
dataGridView2.DataSource = dt2;
for (int i = 0; i < dataGridView1.RowCount -1; i++)
{
DataRow currRow = ((DataRowView)dataGridView1.Rows[i].DataBoundItem).Row;
if (result.Contains(currRow))
dataGridView1.Rows[i].DefaultCellStyle.ForeColor = Color.Red;
}
if (array1.SequenceEqual(array2))
{
}
else
{
//Do your action here!
}

Categories

Resources