我正在创建一个动态HTML表,表内容来自数据库。 我想我能做到 - 但我有两个问题:
<th>
?我想命名我所拥有的列(CustomerId,ProductId等)。注意 - 我不允许使用DataTable - 只是HTML Table控件。
这是我的代码:
string SQL_Order_View = "SELECT * FROM Orders";
SqlCommand SQLcmdOrders = new SqlCommand(SQL_Order_View, Conn);
Conn.Open();
SqlDataReader myOrders = SQLcmdOrders.ExecuteReader();
while(myOrders.Read())
{
TableRow tr = new TableRow();
TableCell tdCustomerId = new TableCell();
TableCell tdProductId = new TableCell();
TableCell tdPrice = new TableCell();
tdCustomerId.Text = myOrders["CustomerId"].ToString();
tdProductId.Text = myOrders["ProductId"].ToString();
tdPrice.Text = myOrders["Price"].ToString();
tr.Cells.Add(tdCustomerId);
tr.Cells.Add(tdProductId);
tr.Cells.Add(tdPrice);
tblOrders.Rows.Add(tr);
}
Conn.Close();
答案 0 :(得分:2)
1.如何向每列添加
// Create a TableHeaderRow.
TableHeaderRow headerRow = new TableHeaderRow();
// Create TableCell objects to contain
// the text for the header.
TableHeaderCell headerTableCell1 = new TableHeaderCell();
TableHeaderCell headerTableCell2 = new TableHeaderCell();
TableHeaderCell headerTableCell3 = new TableHeaderCell();
headerTableCell1.Text = "CustomerId";
headerTableCell2.Text = "ProductId";
headerTableCell3.Text = "Price";
// Add the TableHeaderCell objects to the Cells
// collection of the TableHeaderRow.
headerRow.Cells.Add(headerTableCell1);
headerRow.Cells.Add(headerTableCell2);
headerRow.Cells.Add(headerTableCell3);
// Add the TableHeaderRow as the first item
// in the Rows collection of the table.
tblOrders.Rows.AddAt(0, headerRow);
2.如何点击特定行
tr.Attributes["onclick"] = "<some javascript code here>";
答案 1 :(得分:0)
使用TableHeaderCell。
其他信息:https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.tableheadercell.aspx
答案 2 :(得分:0)
string SQL_Order_View = "SELECT * FROM Orders";
SqlCommand SQLcmdOrders = new SqlCommand(SQL_Order_View, Conn);
Conn.Open();
SqlDataReader myOrders = SQLcmdOrders.ExecuteReader();
// adding header
TableHeaderRow headRow = new TableHeaderRow();
TableHeaderCell thCustomerId = new TableCell();
TableHeaderCell thProductId = new TableCell();
TableHeaderCell thPrice = new TableCell();
thCustomerID.Text = "Customer ID";
thProductId.Text = "Product ID";
thPrice.Text = "Price";
tblOrders.Rows.Add(headRow );
while(myOrders.Read())
{
TableRow tr = new TableRow();
TableCell tdCustomerId = new TableCell();
TableCell tdProductId = new TableCell();
TableCell tdPrice = new TableCell();
tdCustomerId.Text = myOrders["CustomerId"].ToString();
//tdProductId.Text = myOrders["ProductId"].ToString();
//create clickable----
HyperLink lnk= new HyperLink();
lnk.ID = myOrders["ProductId"].ToString();
lnk.NavigateUrl = "your url with some id here";
tdProductId.Controls.Add(lnk);
tdPrice.Text = myOrders["Price"].ToString();
tr.Cells.Add(tdCustomerId);
tr.Cells.Add(tdProductId);
tr.Cells.Add(tdPrice);
tblOrders.Rows.Add(tr);
}
Conn.Close();