ASP.NET C# Generate Table Dynamically doesn't work - c#

I've been trying to generate a table with n number of rows. Being used to PHP makes this all the worst. I tried the following code:
using System.Data;
// Create a DataTable instance
DataTable dTbl = new DataTable("myDynamicTable");
// Create a DataColumn instances
DataColumn dValue = new DataColumn();
DataColumn dMember = new DataColumn();
dValue.ColumnName = "Id";
dValue.DataType = Type.GetType("System.Int32");
dMember.ColumnName = "Name";
dMember.DataType = Type.GetType("System.String");
// Add these DataColumns into the DataTable
dTbl.Columns.Add(dValue);
dTbl.Columns.Add(dMember);
DataRow myrow = dTbl.NewRow();
myrow["Id"] = 1;
myrow["Name"] = "Tux";
// Add the row into the table
dTbl.Rows.Add(myrow);
but nothing displayed. Any idea why?
All I need is to display a table with 3 columns and n number of rows. This number will of rows will be dependent on number of records in database satisfying a certain conditions.
I also tried this:
HtmlTable table1 = new HtmlTable();
// Set the table's formatting-related properties.
table1.Border = 1;
table1.CellPadding = 3;
table1.CellSpacing = 3;
table1.BorderColor = "red";
// Start adding content to the table.
HtmlTableRow row;
HtmlTableCell cell;
for (int i = 1; i <= 5; i++)
{
// Create a new row and set its background color.
row = new HtmlTableRow();
row.BgColor = (i % 2 == 0 ? "lightyellow" : "lightcyan");
for (int j = 1; j <= 4; j++)
{
// Create a cell and set its text.
cell = new HtmlTableCell();
cell.InnerHtml = "Row: " + i.ToString() +
"<br>Cell: " + j.ToString();
// Add the cell to the current row.
row.Cells.Add(cell);
}
// Add the row to the table.
table1.Rows.Add(row);
}
// Add the table to the page.
this.Controls.Add(table1);
but it didn't work!

Instead of doing "this.Controls.Add(table1)" add the table to the .aspx page, and then modify it through the code.
Even better - use a databound GridView.

Related

How to add two column value in one final amount?

I have datatable in c#, I want to add two column value in one, Add means 2+2 =4 like that. please help me this my below code not working
for (int i = 0; i < dtOrdersDetail.Rows.Count; i++)
{
DataRow dtItemRow = dtOrderReceipt.NewRow();
dtItemRow["FinalAmount"] = dtOrdersDetail.Rows[i]["ComboAmount"] + dtOrdersDetail.Rows[i]["TotalPrice"];
}
In this Case you have to correct the code in two place.
Cast the source data table Columns.
dtItemRow["FinalAmount"] = Convert.ToInt32(dtOrdersDetail.Rows[i]["ComboAmount"]) + Convert.ToInt32(dtOrdersDetail.Rows[i]["TotalPrice"]);
Add the row in data table.
dtOrderReceipt.Rows.Add(dtItemRow);
So in summary your code look likes as below
for (int i = 0; i < dtOrdersDetail.Rows.Count; i++)
{
DataRow dtItemRow = dtOrderReceipt.NewRow();
dtItemRow["FinalAmount"] = Convert.ToInt32(dtOrdersDetail.Rows[i]["ComboAmount"]) + Convert.ToInt32(dtOrdersDetail.Rows[i]["TotalPrice"]);
dtOrderReceipt.Rows.Add(dtItemRow);
}
#john, look at the below logic
DataTable table = new DataTable();
table.Columns.Add("TotalPrice", typeof(int));
table.Columns.Add("ComboAmount", typeof(int));
// Here we add five DataRows.
table.Rows.Add(10,10);
table.Rows.Add(20,20);
table.Rows.Add(30,20);
DataTable dtOrderReceipt = new DataTable();
dtOrderReceipt.Columns.Add("FinalAmount", typeof(int));
for (int i = 0; i < table.Rows.Count; i++)
{
DataRow dtItemRow = dtOrderReceipt.NewRow();
dtOrderReceipt.Rows.InsertAt(dtItemRow, i);
dtItemRow["FinalAmount"] = (int)table.Rows[i]["ComboAmount"] + (int)table.Rows[i]["TotalPrice"];
}
I think after create a newrow you forgot to Inject it on your Datatable. i.e.
DataRow dtItemRow = dtOrderReceipt.NewRow();
dtOrderReceipt.Rows.InsertAt(dtItemRow, i);
Let me know is that logic works for you?

Set value of each DataTable row in specific column

I'm having some problem while trying to set column value.
I'v had a dataTable which get some values from SQL and then im adding two new columns by :
dataTable.Columns.Add("dest", typeof(int));
dataTable.Columns.Add("amount", typeof(int));
Which works great but now i want to put 0 in every row in column name dest - and later user will edit this, and then i want to set amount value as
amount = all(this column is in dataTable before I add these 2 columns) + dest;
int columnNumber = 5; //Put your column X number here
for (int i = 0; i < yourDataTable.Rows.Count; i++)
{
yourDataTable.Rows[i][columnNumber] = "0";
}
You can use foreach too.
foreach (DataRow row in myDataTable.Rows)
//if (row["X"] has condition) // or if any condition
row["colName"] = row[colIndex] = "abc";

Setting column width in Data grid view for my table

I am getting a error when I am trying to get a specific column from my table in the datagridview.
Here is how I populate the table----
public DataTable createGridForForm(int rows, int columns)
{
// Create the output table.
DataTable table = new DataTable();
for (int i = 1; i <= columns; i++)
{
table.Columns.Add("column " + i.ToString());
}
for (int i = 1; i < rows; i++)
{
DataRow dr = table.NewRow();
// populate data row with values here
table.Rows.Add(dr);
}
return table;
}
And here is how i create the datagridview------
private void createGridInForm(int rows, int columns)
{
DataGridView RunTimeCreatedDataGridView = new DataGridView();
RunTimeCreatedDataGridView.DataSource = createGridForForm(rows, columns);
DataGridViewColumn ID_Column = RunTimeCreatedDataGridView.Columns[0];
ID_Column.Width = 200;
int positionForTable = getLocationForTable();
RunTimeCreatedDataGridView.Size = new Size(800, 200);
RunTimeCreatedDataGridView.Location = new Point(5, positionForTable);
myTabPage.Controls.Add(RunTimeCreatedDataGridView);
}
The error I am getting is that the Index was out of range. It may not be negative and must be smaller than the size. What I am trying to do is that I'm getting a table from a text file and then in run time I am showing it in my form, but the table doesn't match my data grid view in size, it doesn't look good. So I want to make the table fit the Data grid view.
Try-
DataGridViewColumn ID_Column = dataGridView1.Columns[0];
ID_Column.Width = 200;

How to bind datagridview after giving datasource?

Hello sir i have one question
i am binding my data to datagridview like this
dataGridView1.DataSource = dt1;
Now based upon one of the column in datagridview i am adding no of columns to datagridview for example
this is the coding of binding columns to dynamic columns after binding datasource
for (int j = 0; j < i; j++)
{
if (j >= (dataGridView1.Columns.Count - 10))
{
DataGridViewColumn col = new DataGridViewTextBoxColumn();
col.DataPropertyName = "";
col.HeaderText = j.ToString();
col.Name = j.ToString();
dataGridView1.Columns.Add(col);
}
}
So now my real question starts now
now from database i have to bind values for this dynamic columns
so code looks likes
foreach (DataGridViewRow dgvr in this.dataGridView1.Rows)
{
foreach (DataGridViewColumn dgvc in this.dataGridView1.Columns)
{
string query3 = "select pcs from purchase_sr_details where purchase_details_id='" + dataGridView1.Rows[dgvr.Index].Cells[1].Value + "'";
if (dgvc.Index > 8)
{
DataTable dt2 = connection.getexecuted(query3);
if (dt2.Rows.Count > 0)
{
for (int i = 0; i < dt2.Rows.Count; i++)
{
dataGridView1.Rows[dgvr.Index].Cells[""+i+""].Value = dt2.Rows[i]["pcs"].ToString();
}
}
}
}
}
All is working fine but i can't retrivew values to columns nothing displays nothing retrieved dynamic columns generated but values not binded to that one this one is very confused i am stuck 2 days in this one
I think your problem is you are using a mixture of binding and non-binding. You can't change the cells directly if you are binding to the datagridview. You have two choices:
Change your original query so that you get the dynamic columns as well. Let sql do the work, not your code. That's what I would try and do.
If that is not possible you need to get the datatable that the grid is binding to, add your columns to it (i.e. DataColumns), and rebind to the new datatable.

Empty DataGridView after adding values from DataTable with large number of columns

my DataTable has over 1000 columns and I want to display values on the datagridview. Because of the FillWeigth problem I use the following method to fill the gridview,
public bool TransferDataTableToGrid(DataGridView dataGrid, DataTable dataTable)
{
dataGrid.SuspendLayout();
if ((dataGrid != null) && (dataTable != null))
{
dataGrid.Columns.Clear();
dataGrid.AutoGenerateColumns = false;
dataGrid.DataSource = dataTable;
for (int i = 0; i < dataTable.Columns.Count; i++)
{
DataGridViewColumn column = new DataGridViewColumn();
column.Name = dataTable.Columns[i].ColumnName;
column.FillWeight = 1;
column.CellTemplate = new DataGridViewTextBoxCell();
column.ValueType = dataTable.Columns[i].DataType;
dataGrid.Columns.Add(column);
}
for (int i = 0; i < dataTable.Columns.Count; i++)
{
for (int ii = 0; ii < dataTable.Rows.Count; ii++)
{
dataGrid[i, ii].Value = dataTable.Rows[ii][i];
}
}
}
dataGrid.ResumeLayout();
return true;
}
and sometimes I have an effect that my gridview is empty. Only after second execution data is displayed. Do you have any ideas, why...?
Thanks.
I recommend to use paging, i mean that you can show about 20 columns with navigation buttons
under your grid, it's like Google or others... even your are not programming a web application.
Use binding source to fill your grid
SqlDataAdapter adapter = new SqlDataAdapter(database.cmd);
dataSet1.Tables.Clear();
adapter.Fill(dataSet1, "Table");
bs = new BindingSource();
bs.DataSource = dataSet1.Tables["Table"];
dataGridView1.DataSource = bs;
now you dont need to worry about creating columns and fill cells in loops and its much better performance
Bind Data to Datagridview
Well, I solved my problem. With Ivan's suggestion I tried the alternative way to fill data: instead of using DataSource I add new rows manually
foreach (DataRow row in dataTable.Rows)
{
var dataGridRow = new DataGridViewRow();
dataGridRow.CreateCells(dataGrid);
for (int i = 0; i < row.ItemArray.Length; i++)
{
dataGridRow.Cells[i].Value = row.ItemArray[i];
}
dataGrid.Rows.Add(dataGridRow);
}
...and it works - data in dgv is displayed. Thanks!

Categories

Resources