Tuesday, April 28, 2009

ASP.NET(C#) 畫表格

某噗友的作業,丟上來給他當參考

題目是:試寫一個網頁程式,當使用者輸入總列數(假設為X)與總列數(假設為Y)後,動態產生X*Y的表格



9x9.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="9x9.aspx.cs" Inherits="_9x9" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>未命名頁面</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="x"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<asp:Label ID="Label2" runat="server" Text="y"></asp:Label>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
<asp:Table ID="Table1" runat="server" BorderWidth="1">
</asp:Table>

</div>
</form>
</body>
</html>



9x9.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _9x9 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}

protected void Button1_Click(object sender, EventArgs e)
{
if (IsNumeric(TextBox1.Text) && IsNumeric(TextBox2.Text)) {
if (Convert.ToInt32(TextBox1.Text) > 0 && Convert.ToInt32(TextBox2.Text) > 0) {
for (int i = 0; i < Convert.ToInt32(TextBox1.Text); i++) {
TableRow tRow = new TableRow();
Table1.Rows.Add(tRow);
for (int j = 0; j < Convert.ToInt32(TextBox2.Text); j++)
{
TableCell tCell = new TableCell();
tCell.Text = i.ToString() + j.ToString();
tRow.Cells.Add(tCell);
}

} } } }

static bool IsNumeric(object Expression)
{
bool isNum;
double retNum;
isNum = Double.TryParse(Convert.ToString(Expression), System.Globalization.NumberStyles.Any, System.Globalization.NumberFormatInfo.InvariantInfo, out retNum);
return isNum;
}

}


1 comment: