I just tried over it but i got the HTML tables in the manner of unique,i just need the tables to created one within another.
sample output: http://i.stack.imgur.com/drdXx.jpg][1]sample
In Design Page
<table id="tableContent" border="1" runat="server"></table>
protected void Page_Load(object sender, EventArgs e)
{
var s = 0;
Addtable(s);
}
public void Addtable(int j)
{
HtmlTableRow row = new HtmlTableRow();
HtmlTableCell cell = new HtmlTableCell();
cell.InnerText = "col 1";
row.Cells.Add(cell);
cell = new HtmlTableCell();
cell.InnerText = "col2";
row.Cells.Add(cell);
tableContent.Rows.Add(row);
tableContent.Border =1;
if( j < 5)
{
j++;
Addtable(j);
}
}
You need to change your recursion function as below
public void Addtable(HtmlTable baseTable, int j)
{
HtmlTable innerTable = new HtmlTable();
// change to stylesheet instead. Just added as an example to get the output
baseTable.Style.Add("margin-left", "25px");
baseTable.Style.Add("margin-right", "25px");
baseTable.Style.Add("margin-bottom", "25px");
baseTable.Style.Add("text-align", "center");
baseTable.Border = 1;
//Create a container cell for inner table
HtmlTableRow container = new HtmlTableRow();
HtmlTableCell containerCell = new HtmlTableCell();
Literal l = new Literal();
l.Text = "Table " + j;
containerCell.Controls.Add(l);
containerCell.Controls.Add(innerTable);
containerCell.ColSpan = 2;
container.Cells.Add(containerCell);
baseTable.Rows.Add(container);
if (j < 5)
{
j++;
Addtable(innerTable, j);
}
}
Then call the function
var s = 0;
Addtable(tableContent,s);
Related
I have created a dynamic table using Asp.net with c#. Now I want to store this dynamically created table in the session, How can i do that?
I am new to Asp.Net and Programming aswell.
Thanks.
public partial class WebForm1 : System.Web.UI.Page
{
}
protected void Page_Load(object sender, EventArgs e)
{
}
public void CreateRuntime_Table()
{
int tblRows = int.Parse(txtrow.Text);
int tblCols = int.Parse(txtcol.Text);
Table tbl = new Table();
tbl.BorderWidth = 3;
tbl.BorderStyle = BorderStyle.Solid;
tbl.ID = "myTable";
for (int i = 1; i <= tblRows; i++)
{
TableRow tr = new TableRow();
for (int j = 1; j <= tblCols; j++)
{
TableCell tc = new TableCell();
TextBox txtbox = new TextBox();
txtbox.Text = "Test Row:" + i + "Test Col:" + " " + j;
//Add the control to the table cell
tc.Controls.Add(txtbox);
tr.Controls.Add(tc);
}
tbl.Rows.Add(tr);
}
form1.Controls.Add(tbl);
}
protected void Unnamed_Click(object sender, EventArgs e)
{
CreateRuntime_Table();
}
To store the table in a session do:
Table tbl = new Table();
...
Session["myTable"] = tbl;
The to get the table from the session do:
Table getTableFromSession = (Table)Session["myTable"];
I have a question regarding creating controls in runtime in ASP.NET 4.0. I'm building a application and in admin.aspx page I have multiple controls (DropDownLists) which are dynamically created with values from a Sql database.
I know that for having events fired for dynamically created controls, I have to create this controls in Page_Load() or in Page_Init().
My project has a Master Page, in which I have a 1 second timer which updates a clock. This timer event calls my admin.aspx Page_Load() function, so my method which creates dynamic controls it's called every 1 second - connection to database is made every one second, please look below to my code.
It's a good practice to do that? Can you please propose some ideas?
protected void Page_Load(object sender, EventArgs e)
{
_SinopticBackgroundColor = ConfigurationManager.AppSettings["SinopticBackgroundColor"];
panelContent.Style.Add("background-color", _SinopticBackgroundColor);
Control c = GetControlThatCausedPostBack(this);
if (c != null)
{
if (c.ID.Equals("btnManageCategory"))
hfPageManage.Value = "category";
else if (c.ID.Equals("btnManageDevices"))
hfPageManage.Value = "device";
}
if (hfPageManage.Value.Equals("category"))
{
cbTreeViewGroup.Visible = false;
UpdateSinopticCategoryManager(TreeView1.SelectedNode); //this is the functions which loads controls from database..
}
else if (hfPageManage.Value.Equals("device"))
{
cbTreeViewGroup.Visible = true;
}
else
{
cbTreeViewGroup.Visible = false;
}
if (!Page.IsPostBack)
{
LoadFunctions(); // loads some values from database into datatables
}
else
{
}
}
And here is the functions which creates controls
private void UpdateSinopticCategoryManager(TreeNode node = null)
{
if (node == null)
return;
DataTable categoriiDT = null;
using (var connection = new SqlConnection(Database.ConnectionString))
{
using (var command = connection.CreateCommand())
{
command.CommandText = "SELECT * FROM categories WHERE CategoryID = #CategoryID";
command.Parameters.Add("CategoryID", node.Value);
SqlDataAdapter ad = new SqlDataAdapter(command);
DataSet ds = new DataSet("CATEGORYPROPERTIES");
connection.Open();
ad.Fill(ds);
// verificam sa avem date
if (ds.Tables.Count <= 0)
return;
if (ds.Tables[0].Rows.Count <= 0)
return;
categoriiDT = ds.Tables[0];
}
}
// generate table
Table table = new Table();
table.Style.Add("position", "relative");
table.Style.Add("top", "20px");
table.Style.Add("margin-left", "20px");
table.BorderStyle = BorderStyle.Solid;
table.BorderWidth = 1;
// header
TableHeaderRow hr = new TableHeaderRow();
for (int i = 0; i < 2; i++)
{
TableHeaderCell hc = new TableHeaderCell();
if (i > 0)
{
hc.Text = "FUNCTION";
//hc.Width = 200;
}
else
{
hc.Width = 100;
}
hr.Cells.Add(hc);
}
table.Rows.Add(hr);
var inputs = (from a in categoriiDT.Columns.Cast<DataColumn>()
where a.ColumnName.ToLowerInvariant().Contains("input")
select a.ColumnName).ToArray();
if (inputs.Count() <= 0)
return;
//rows input
for (int i = 0; i < inputs.Count(); i++)
{
TableRow tableRow = new TableRow();
for (int j = 0; j < 2; j++)
{
TableCell cell = new TableCell();
if (j > 0)
{
// adaugare 2 dropdownlist
DropDownList categList = new DropDownList();
categList.SelectedIndexChanged += new EventHandler(categList_SelectedIndexChanged);
foreach (DataRow row in functionsCategories.Rows)
{
categList.Items.Add(new ListItem(row["FunctionCategoryName"].ToString(), row["FunctionCategoryID"].ToString()));
}
DropDownList funcList = new DropDownList();
int selF = 0, selC = 0;
for (int fi = 0; fi < functions.Rows.Count; fi++)// (DataRow row in functions.Rows)
{
funcList.Items.Add(new ListItem(functions.Rows[fi]["FunctionName"].ToString(), functions.Rows[fi]["FunctionID"].ToString()));
if (functions.Rows[fi]["FunctionID"].ToString() == categoriiDT.Rows[0][inputs[i]].ToString())
{
selF = fi;
selC = Int32.Parse(functions.Rows[fi]["FunctionCategoryID"].ToString());
}
}
funcList.SelectedIndex = selF;
categList.SelectedIndex = functionsCategories.Rows.IndexOf(
(from c in functionsCategories.AsEnumerable()
where c["FunctionCategoryID"].ToString().Equals(selC.ToString())
select c).FirstOrDefault());
cell.Controls.Add(categList);
cell.Controls.Add(funcList);
}
else
{
Label label = new Label();
label.Text = "INPUT " + i.ToString();
label.Style.Add("font-weight", "bold");
cell.Controls.Add(label);
}
tableRow.Cells.Add(cell);
}
table.Rows.Add(tableRow);
}
//rows output
for (int i = 0; i < 4; i++)
{
TableRow row = new TableRow();
for (int j = 0; j < 2; j++)
{
TableCell cell = new TableCell();
if (j > 0)
{
DropDownList list = new DropDownList();
list.Width = 200;
list.Items.AddRange(GetOutputFunctions());
list.BorderColor = Color.Goldenrod;
cell.Controls.Add(list);
}
else
{
Label label = new Label();
label.Text = "OUTPUT " + i.ToString();
label.Style.Add("font-weight", "bold");
cell.Controls.Add(label);
}
row.Cells.Add(cell);
}
table.Rows.Add(row);
}
// add table to panel
panelContent.Controls.Add(table);
}
It's about this: DropDownList categList = new DropDownList();
This may get answered more quickly and effectively in codereview https://codereview.stackexchange.com/
I have successfully created generating new records into table rows but want to add table header, so how to do that?
private void GenerateTable(int rowsCount)
{
Table table = new Table();
table.ID = "Table1";
Page.Form.Controls.Add(table);
const int colsCount = 3;
for (int i = 0; i < rowsCount; i++)
{
TableRow row = new TableRow();
for (int j = 0; j < colsCount; j++)
{
TableCell cell = new TableCell();
TextBox tb = new TextBox();
tb.ID = "TextBoxRow_" + i + "Col_" + j;
cell.Controls.Add(tb);
row.Cells.Add(cell);
}
table.Rows.Add(row);
}
SetPreviousData(rowsCount, colsCount);
rowsCount++;
ViewState["RowsCount"] = rowsCount;
}
You do it like that:
TableHeaderRow header = new TableHeaderRow(); // Creating a header row
table.Rows.Add(header); // Add the header row to table tbl
For adding cells in the header row here is an example:
TableHeaderCell headerTableCell1 = new TableHeaderCell();
header.Cells.Add(headerTableCell1);
And this is where is goes in your code:
private void GenerateTable(int rowsCount)
{
Table table = new Table();
table.ID = "Table1";
Page.Form.Controls.Add(table);
const int colsCount = 3;
TableHeaderRow header = new TableHeaderRow();
table.Rows.Add(header);
//These two lines in iteir own loop
TableHeaderCell headerTableCell1 = new TableHeaderCell();
header.Cells.Add(headerTableCell1);
for (int i = 0; i < rowsCount; i++)
{
TableRow row = new TableRow();
for (int j = 0; j < colsCount; j++)
{
TableCell cell = new TableCell();
TextBox tb = new TextBox();
tb.ID = "TextBoxRow_" + i + "Col_" + j;
cell.Controls.Add(tb);
row.Cells.Add(cell);
}
table.Rows.Add(row);
}
SetPreviousData(rowsCount, colsCount);
rowsCount++;
ViewState["RowsCount"] = rowsCount;
}
Building on the suggested solution by #israel-altar, I struggled with adding the header into a <thead> tag and not into a <tbody>.
To achieve this, you have to use the TableSelection property of your TableHeaderRow:
private void GenerateTable(List<string> fieldsList)
{
Table table = new Table();
table.ID = "Table1";
Page.Form.Controls.Add(table);
TableHeaderRow header = new TableHeaderRow();
foreach (string field in fieldsList)
{
TableHeaderCell headerTableCell1 = new TableHeaderCell();
headerTableCell1.Controls.Add(new Literal() {
Text = field
});
header.Cells.Add(headerTableCell1);
}
// Set TableSection to TableHeader so that the TableHeaderRow is added within <thead> and not within <tbody>
header.TableSection = TableRowSection.TableHeader;
table.Rows.Add(header);
// loop rows ...
}
two part question:
1:
I am using a session state refresh to hold count of the page reloads but when using a series of if statements the validation isn't working. Code at the bottom. What am I doing wrong?
2:
Using session state against postback doesn't appear to be the most efficient method of doing this, if I added another table with the same functionality, the count would affect both tables.
For example if I only wanted people to be able to add a maximum of three rows to a table, on two tables, they would only be able to add four rows in total.
What would be a better method of storing a count for separate refreshes?
Update
I have found the issue with the code not adding rows to the existing but I'm unsure of how to fix it.
Basically each iteration is deleting the existing row then adding a single row again. So there will never be more than one row.
Any ideas?
namespace FormTest
{
public partial class About : Page
{
protected void Page_Load(object sender, System.EventArgs e)
{
tbl.BorderStyle = BorderStyle.Inset;
tbl.BorderWidth = Unit.Pixel(1);
if (!Page.IsPostBack)
{
Session["count"] = 0;
}
else
{
int count = (int)Session["count"];
count++;
Session["count"] = count;
}
}
protected void cmdCreate_Click(object sender, System.EventArgs e)
{
tbl.Controls.Clear();
int rows = 1;
int cols = 4;
if ((int)Session["count"] == 0)
{
for (int i = 0; i < rows; i++)
{
TableRow rowNew = new TableRow();
tbl.Controls.Add(rowNew);
for (int j = 0; j < cols; j++)
{
TableCell cellNew = new TableCell();
Label lblNew = new Label();
lblNew.Text = "(" + i.ToString() + "," + j.ToString() + ")<br />";
TextBox tbNew = new TextBox();
cellNew.Controls.Add(lblNew);
cellNew.Controls.Add(tbNew);
rowNew.Controls.Add(cellNew);
}
}
}
else
{
if ((int)Session["count"] == 1)
{
for (int i = 0; i < rows; i++)
{
TableRow rowNew = new TableRow();
tbl.Controls.Add(rowNew);
for (int j = 0; j < cols; j++)
{
TableCell cellNew = new TableCell();
Label lblNew = new Label();
lblNew.Text = "(" + i.ToString() + "," + j.ToString() + ")<br />";
TextBox tbNew = new TextBox();
cellNew.Controls.Add(lblNew);
cellNew.Controls.Add(tbNew);
rowNew.Controls.Add(cellNew);
}
}
}
else
{
if ((int)Session["count"] == 2)
{
for (int i = 0; i < rows; i++)
{
TableRow rowNew = new TableRow();
tbl.Controls.Add(rowNew);
for (int j = 0; j < cols; j++)
{
TableCell cellNew = new TableCell();
Label lblNew = new Label();
lblNew.Text = "(" + i.ToString() + "," + j.ToString() + ")<br />";
TextBox tbNew = new TextBox();
cellNew.Controls.Add(lblNew);
cellNew.Controls.Add(tbNew);
rowNew.Controls.Add(cellNew);
}
}
}
else
{
if ((int)Session["count"] == 3)
{
for (int i = 0; i < rows; i++)
{
TableRow rowNew = new TableRow();
tbl.Controls.Add(rowNew);
for (int j = 0; j < cols; j++)
{
TableCell cellNew = new TableCell();
Label lblNew = new Label();
lblNew.Text = "(" + i.ToString() + "," + j.ToString() + ")<br />";
TextBox tbNew = new TextBox();
cellNew.Controls.Add(lblNew);
cellNew.Controls.Add(tbNew);
rowNew.Controls.Add(cellNew);
}
}
}
else
{
Response.Redirect("http://www.google.co.uk");
}
}
}
}
}//end cmdCreate_Click
}
}
You don't need a list of if conditions, you just need to ensure the number of rows is less than your desired limit. You also should store the limit per table to avoid your count clashing if/when more tables are added.
This is how I would do it:
(note: This won't work "as-is" - I've assumed you've removed the code to assign tbl within cmdCreate_Click()and have left it as is for clarity)
namespace FormTest
{
public partial class About : Page
{
private int myFirstTableMaxRows = 3;
protected void Page_Load(object sender, System.EventArgs e)
{
tbl.BorderStyle = BorderStyle.Inset;
tbl.BorderWidth = Unit.Pixel(1);
if (!Page.IsPostBack)
{
Session["myFirstTable_count"] = "0";
}
else
{
int count = (int)Session["myFirstTable_count"];
Session["myFirstTable_count"] = ++count;
}
}
protected void cmdCreate_Click(object sender, System.EventArgs e)
{
tbl.Controls.Clear();
int cols = 4;
int currentRowCount = (int)Session["myFirstTable_count"];
if(currentRowCount <= myFirstTableMaxRows)
{
TableRow rowNew = new TableRow();
tbl.Controls.Add(rowNew);
for (int j = 0; j < cols; j++)
{
TableCell cellNew = new TableCell();
Label lblNew = new Label();
lblNew.Text = "(" + i.ToString() + "," + j.ToString() + ")<br />";
TextBox tbNew = new TextBox();
cellNew.Controls.Add(lblNew);
cellNew.Controls.Add(tbNew);
rowNew.Controls.Add(cellNew);
}
}
else
{
Response.Redirect("http://www.google.co.uk");
}
}//end cmdCreate_Click
}
Update after question edit
The existing rows will go due to this line in the code:
tbl.Controls.Clear();
The table is being cleared, then a single row is added per the logic in the cmdCreate_Click() method.
I was trying to create a table dynamically and put textboxes in it. Here in the following code, i was trying to create a textbox with a distinct name for each k. But only the last value of k is getting displayed in the textbox. I was wondering how i could give a name to Textbox so all are shown.
for (int k = 0; k < tblCols; k++)
{
TableCell tc = new TableCell();
TextBox txtCompanyName = new TextBox();
txtCompanyName.Text = dsmissing.Tables[0].Rows[tblCols- 1]["NewCompanyName"].ToString();
tc.Controls.Add(txtCompanyName);
}
Replace this line
dsmissing.Tables[0].Rows[tblCols- 1]["NewCompanyName"].ToString();
With
dsmissing.Tables[0].Rows[k]["NewCompanyName"].ToString();
I assume you are talking about ID like below.
for (int k = 0; k < tblCols; k++)
{
TableCell tc = new TableCell();
TextBox txtCompanyName = new TextBox();
txtCompanyName.Text = dsmissing.Tables[0].Rows[k]["NewCompanyName"].ToString();
txtCompanyName.ID = Guid.NewGuid().ToString("N");
tc.Controls.Add(txtCompanyName);
}
I think you may have meant to do this:
for (int k = 0; k < tblCols; k++)
{
TableCell tc = new TableCell();
TextBox txtCompanyName = new TextBox();
//txtCompanyName.Text = dsmissing.Tables[0].Rows[tblCols-1 ["NewCompanyName"].ToString();
txtCompanyName.Text = dsmissing.Tables[0].Rows[k]["NewCompanyName"].ToString();
tc.Controls.Add(txtCompanyName);
}
Surely this will work and it is easy to understand
protected void Page_Load(object sender, EventArgs e)
{
button1();
}
protected void Page_Init(object sender, EventArgs e)
{
try
{
Label lbl = new Label();
lbl.ID = "lbl_label";
lbl.Text = "Enter the values";
form1.Controls.Add(lbl);
TextBox tb = new TextBox();
tb.ID = "tbx_textbox";
form1.Controls.Add(tb);
Button bt = new Button();
bt.ID = "bt_button";
bt.Text = "click";
form1.Controls.Add(bt);
}
catch (Exception ex) { }
}
public void button1()
{
Table table = new Table();
TableRow row = null;
TableCell cell = null;
TextBox tbx1 = this.Page.FindControl("tbx_textbox") as TextBox;
try
{
int a = int.Parse(tbx1.Text);
for (int i = 0; i < a; i++)
{
row = new TableRow();
cell = new TableCell();
TextBox tx = new TextBox();
tx.ID = "box" + i.ToString();
cell.Controls.Add(tx);
row.Cells.Add(cell);
table.Rows.Add(row);
form1.Controls.Add(table);
}
}
catch (Exception ex) { }
finally
{
table = null;
}
}