使用asp的标准控件与撰写C#script,制作一个动态产生表格的网页
题目
请使用asp的标准控件与撰写C#script,制作一个动态产生表格的网页,可让使用者指定要出现几列几栏,并且每一个单元格内动态新增一个按钮。(可假设使用者输入的都是合法数值)
一、涉及的知识
学习资源 来源 菜鸟教程 Table
二、解决方法
1.运行截图
2.代码实现
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="4-computer.aspx.cs" Inherits="homework4._4_computer" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>4-computer</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label runat="server" >列数:</asp:Label>
<asp:TextBox id="TextBox1" runat="server"></asp:TextBox>
<br />
<asp:Label runat="server">行数:</asp:Label>
<asp:TextBox id="TextBox2" runat="server"></asp:TextBox>
<br />
<asp:Button id="Button" runat="server" style="margin:15px; background-color:lightskyblue" Text="产生表格的按钮" OnClick="Button_Click"/>
</div>
<div>
<asp:Label id="Label3" runat="server"></asp:Label>
<br />
<asp:Table id="Table1" runat="server" style="display:inline;" CellSpacing="5"></asp:Table>
</div>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace homework4
{
public partial class _4_computer : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button_Click(object sender, EventArgs e)
{
if (TextBox2.Text==""|| TextBox1.Text == "")
{
TextBox2.Text = "0";
TextBox1.Text = "0";
Label3.Text = "无法生成表格,请重新输入";
return;
}
int rows = int.Parse(TextBox2.Text);//行数
int cells = int.Parse(TextBox1.Text);//列数
int count = 0;//按钮 数/值 为 0
//string.IsNullOrEmpty 判断 为空?
if (rows <= 0 || cells <= 0)
{
Label3.Text = "无法生成表格,请重新输入";
return;
}
else if (rows != 0 && cells != 0)
{
//Label3.Text = "生成表格,如下:";
Label3.Text = "已产生" + rows * cells + "个按钮与存储表格";
for (int i = 0; i < rows; i++) // i<行,结束
{
TableRow r = new TableRow();//创建 新的 行
for (int j = 0; j < cells; j++) // j<列,结束
{
TableCell c = new TableCell();//创建 新的 单元格(列)
Button btn = new Button();//创建 新的 按钮
btn.Text = string.Format("按钮{0}", count);
btn.Height = 55;
btn.Width = 55;
c.Controls.Add(btn);//将 按钮 添加到table的 单元格(列) 中
r.Cells.Add(c); //将 单元格 添加到table的 行 中
count++;//按钮 计数
}
this.Table1.Rows.Add(r);// 将 行 添加到table中
}
}
}
}
}